Move adu_strerror() to adu.c.
[adu.git] / string.c
1 /*
2 * Copyright (C) 2004-2008 Andre Noll <maan@systemlinux.org>
3 *
4 * Licensed under the GPL v2. For licencing details see COPYING.
5 */
6
7 /** \file string.c \brief Memory allocation and string handling functions. */
8
9 #include "adu.h"
10 #include "string.h"
11 #include <string.h>
12 #include "error.h"
13
14 /**
15 * Adu's version of realloc().
16 *
17 * \param p Pointer to the memory block, may be \p NULL.
18 * \param size The desired new size.
19 *
20 * A wrapper for realloc(3). It calls \p exit(\p EXIT_FAILURE) on errors,
21 * i.e. there is no need to check the return value in the caller.
22 *
23 * \return A pointer to the newly allocated memory, which is suitably aligned
24 * for any kind of variable and may be different from \a p.
25 *
26 * \sa realloc(3).
27 */
28 __must_check __malloc void *adu_realloc(void *p, size_t size)
29 {
30 /*
31 * No need to check for NULL pointers: If p is NULL, the call
32 * to realloc is equivalent to malloc(size)
33 */
34 assert(size);
35 if (!(p = realloc(p, size))) {
36 EMERG_LOG("realloc failed (size = %zu), aborting\n",
37 size);
38 exit(EXIT_FAILURE);
39 }
40 return p;
41 }
42
43 /**
44 * Adu's version of malloc().
45 *
46 * \param size The desired new size.
47 *
48 * A wrapper for malloc(3) which exits on errors.
49 *
50 * \return A pointer to the allocated memory, which is suitably aligned for any
51 * kind of variable.
52 *
53 * \sa malloc(3).
54 */
55 __must_check __malloc void *adu_malloc(size_t size)
56 {
57 assert(size);
58 void *p = malloc(size);
59
60 if (!p) {
61 EMERG_LOG("malloc failed (size = %zu), aborting\n",
62 size);
63 exit(EXIT_FAILURE);
64 }
65 return p;
66 }
67
68 /**
69 * Adu's version of calloc().
70 *
71 * \param size The desired new size.
72 *
73 * A wrapper for calloc(3) which exits on errors.
74 *
75 * \return A pointer to the allocated and zeroed-out memory, which is suitably
76 * aligned for any kind of variable.
77 *
78 * \sa calloc(3)
79 */
80 __must_check __malloc void *adu_calloc(size_t size)
81 {
82 void *ret = adu_malloc(size);
83
84 memset(ret, 0, size);
85 return ret;
86 }
87
88 /**
89 * Adu's version of strdup().
90 *
91 * \param s The string to be duplicated.
92 *
93 * A wrapper for strdup(3). It calls \p exit(EXIT_FAILURE) on errors, i.e.
94 * there is no need to check the return value in the caller.
95 *
96 * \return A pointer to the duplicated string. If \p s was the NULL pointer,
97 * an pointer to an empty string is returned.
98 *
99 * \sa strdup(3)
100 */
101 __must_check __malloc char *adu_strdup(const char *s)
102 {
103 char *ret;
104
105 if ((ret = strdup(s? s: "")))
106 return ret;
107 EMERG_LOG("strdup failed, aborting\n");
108 exit(EXIT_FAILURE);
109 }
110
111 /**
112 * Allocate a sufficiently large string and print into it.
113 *
114 * \param fmt A usual format string.
115 *
116 * Produce output according to \p fmt. No artificial bound on the length of the
117 * resulting string is imposed.
118 *
119 * \return This function either returns a pointer to a string that must be
120 * freed by the caller or aborts without returning.
121 *
122 * \sa printf(3).
123 */
124 __must_check __printf_1_2 __malloc char *make_message(const char *fmt, ...)
125 {
126 char *p;
127 int n;
128 size_t size = 100;
129
130 p = adu_malloc(size);
131 while (1) {
132 va_list ap;
133 /* Try to print in the allocated space. */
134 va_start(ap, fmt);
135 n = vsnprintf(p, size, fmt, ap);
136 va_end(ap);
137 /* If that worked, return the string. */
138 if (n > -1 && n < size)
139 break;
140 /* Else try again with more space. */
141 if (n > -1) /* glibc 2.1 */
142 size = n + 1; /* precisely what is needed */
143 else /* glibc 2.0 */
144 size *= 2; /* twice the old size */
145 p = adu_realloc(p, size);
146 }
147 return p;
148 }
149
150 /**
151 * adu's version of strcat().
152 *
153 * \param a String to be appended to.
154 * \param b String to append.
155 *
156 * Append \p b to \p a.
157 *
158 * \return If \a a is \p NULL, return a pointer to a copy of \a b, i.e.
159 * adu_strcat(NULL, b) is equivalent to adu_strdup(b). If \a b is \p NULL,
160 * return \a a without making a copy of \a a. Otherwise, construct the
161 * concatenation \a c, free \a a (but not \a b) and return \a c.
162 *
163 * \sa strcat(3).
164 */
165 __must_check __malloc char *adu_strcat(char *a, const char *b)
166 {
167 char *tmp;
168
169 if (!a)
170 return adu_strdup(b);
171 if (!b)
172 return a;
173 tmp = make_message("%s%s", a, b);
174 free(a);
175 return tmp;
176 }
177
178 /** \cond LLONG_MAX and LLONG_LIN might not be defined. */
179 #ifndef LLONG_MAX
180 #define LLONG_MAX (1 << (sizeof(long) - 1))
181 #endif
182 #ifndef LLONG_MIN
183 #define LLONG_MIN (-LLONG_MAX - 1LL)
184 #endif
185 /** \endcond */
186
187 /**
188 * Convert a string to a 64-bit signed integer value.
189 *
190 * \param str The string to be converted.
191 * \param result Result pointer.
192 *
193 * \return Standard.
194 *
195 * \sa strtol(3), atoi(3).
196 */
197 __must_check int atoi64(const char *str, int64_t *result)
198 {
199 char *endptr;
200 long long tmp;
201
202 errno = 0; /* To distinguish success/failure after call */
203 tmp = strtoll(str, &endptr, 10);
204 if (errno == ERANGE && (tmp == LLONG_MAX || tmp == LLONG_MIN))
205 return -E_ATOI_OVERFLOW;
206 if (errno != 0 && tmp == 0) /* other error */
207 return -E_STRTOLL;
208 if (endptr == str)
209 return -E_ATOI_NO_DIGITS;
210 if (*endptr != '\0') /* Further characters after number */
211 return -E_ATOI_JUNK_AT_END;
212 *result = tmp;
213 return 1;
214 }
215
216 /**
217 * Split a string and return pointers to its parts.
218 *
219 * \param args The string to be split.
220 * \param argv_ptr Pointer to the list of substrings.
221 * \param delim Delimiter.
222 *
223 * This function modifies \a args by replacing each occurance of \a delim by
224 * zero. A \p NULL terminated array of pointers to char* is allocated dynamically
225 * and these pointers are initialized to point to the broken-up substrings
226 * within \a args. A pointer to this array is returned via \a argv_ptr.
227 *
228 * \return The number of substrings found in \a args.
229 */
230 unsigned split_args(char *args, char *** const argv_ptr, const char *delim)
231 {
232 char *p = args;
233 char **argv;
234 size_t n = 0, i, j;
235
236 p = args + strspn(args, delim);
237 for (;;) {
238 i = strcspn(p, delim);
239 if (!i)
240 break;
241 p += i;
242 n++;
243 p += strspn(p, delim);
244 }
245 *argv_ptr = adu_malloc((n + 1) * sizeof(char *));
246 argv = *argv_ptr;
247 i = 0;
248 p = args + strspn(args, delim);
249 while (p) {
250 argv[i] = p;
251 j = strcspn(p, delim);
252 if (!j)
253 break;
254 p += strcspn(p, delim);
255 if (*p) {
256 *p = '\0';
257 p++;
258 p += strspn(p, delim);
259 }
260 i++;
261 }
262 argv[n] = NULL;
263 return n;
264 }
265
266
267 static int get_next_word(const char *line, char **word)
268 {
269 enum line_state_flags {LSF_HAVE_WORD = 1, LSF_BACKSLASH = 2,
270 LSF_QUOTE = 4};
271 const char *in;
272 char *out;
273 int ret, state = 0;
274
275 out = adu_malloc(strlen(line) + 1);
276 *out = '\0';
277 *word = out;
278 for (in = line; *in; in++) {
279 switch (*in) {
280 case '\\':
281 if (state & LSF_BACKSLASH) /* \\ */
282 break;
283 state |= LSF_BACKSLASH;
284 state |= LSF_HAVE_WORD;
285 continue;
286 case 'n':
287 case 't':
288 if (state & LSF_BACKSLASH) { /* \n or \t */
289 *out++ = (*in == 'n')? '\n' : '\t';
290 state &= ~LSF_BACKSLASH;
291 continue;
292 }
293 break;
294 case '"':
295 if (state & LSF_BACKSLASH) /* \" */
296 break;
297 if (state & LSF_QUOTE) {
298 state &= ~LSF_QUOTE;
299 continue;
300 }
301 state |= LSF_HAVE_WORD;
302 state |= LSF_QUOTE;
303 continue;
304 case ' ':
305 case '\t':
306 case '\n':
307 if (state & LSF_BACKSLASH)
308 break;
309 if (state & LSF_QUOTE)
310 break;
311 if (state & LSF_HAVE_WORD)
312 goto success;
313 /* ignore space at the beginning */
314 continue;
315 }
316 /* copy char */
317 state |= LSF_HAVE_WORD;
318 *out++ = *in;
319 state &= ~LSF_BACKSLASH;
320 }
321 ret = 0;
322 if (!(state & LSF_HAVE_WORD))
323 goto out;
324 ret = -ERRNO_TO_ERROR(EINVAL);
325 if (state & LSF_BACKSLASH) {
326 ERROR_LOG("trailing backslash\n");
327 goto out;
328 }
329 if (state & LSF_QUOTE) {
330 ERROR_LOG("unmatched quote character\n");
331 goto out;
332 }
333 success:
334 *out = '\0';
335 return in - line;
336 out:
337 free(*word);
338 *word = NULL;
339 return ret;
340 }
341
342 /**
343 * Free an array of words created by create_argv().
344 *
345 * \param argv A pointer previously obtained by \ref create_argv().
346 */
347 void free_argv(char **argv)
348 {
349 int i;
350
351 for (i = 0; argv[i]; i++)
352 free(argv[i]);
353 free(argv);
354 }
355
356 /**
357 * Split a line into words which are separated by whitespace.
358 *
359 * In contrast to gengetopt's string parser, double quotes, backslash-escaped
360 * characters and special characters like \p \\n are honored. The result
361 * contains pointers to copies of the words contained in \a line and has to be
362 * freed by using \ref free_argv().
363 *
364 * \param line The line to be split.
365 * \param result The array of words is returned here.
366 *
367 * \return Number of words in \a line, negative on errors.
368 */
369 int create_argv(const char *line, char ***result)
370 {
371 char *word, **argv = adu_malloc(2 * sizeof(char *));
372 const char *p;
373 int ret, num_words;
374
375 argv[0] = adu_strdup(line);
376 for (p = line, num_words = 1; ; p += ret, num_words++) {
377 ret = get_next_word(p, &word);
378 if (ret < 0)
379 goto err;
380 if (!ret)
381 break;
382 argv = adu_realloc(argv, (num_words + 2) * sizeof(char*));
383 argv[num_words] = word;
384 }
385 argv[num_words] = NULL;
386 *result = argv;
387 return num_words;
388 err:
389 while (num_words > 0)
390 free(argv[--num_words]);
391 free(argv);
392 return ret;
393 }
394
395 char *absolute_path(const char *path)
396 {
397 char *cwd, *ap;
398 long int path_max;
399
400 if (!path || !path[0])
401 return NULL;
402 if (path[0] == '/')
403 return adu_strdup(path);
404
405 #ifdef PATH_MAX
406 path_max = PATH_MAX;
407 #else
408 /*
409 * The result of pathconf(3) may be huge and unsuitable for mallocing
410 * memory. OTOH pathconf(3) may return -1 to signify that PATH_MAX is
411 * not bounded.
412 */
413 path_max = pathconf(name, _PC_PATH_MAX);
414 if (path_max <= 0 || path_max >= 4096)
415 path_max = 4096;
416 #endif
417 cwd = adu_malloc(path_max);
418 if (!getcwd(cwd, path_max)) {
419 free(cwd);
420 return NULL;
421 }
422 ap = make_message("%s/%s", cwd, path);
423 free(cwd);
424 return ap;
425 }