Merge commit 'fml/master'
[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 *msg;
127
128 VSPRINTF(fmt, msg);
129 return msg;
130 }
131
132 /**
133 * adu's version of strcat().
134 *
135 * \param a String to be appended to.
136 * \param b String to append.
137 *
138 * Append \p b to \p a.
139 *
140 * \return If \a a is \p NULL, return a pointer to a copy of \a b, i.e.
141 * adu_strcat(NULL, b) is equivalent to adu_strdup(b). If \a b is \p NULL,
142 * return \a a without making a copy of \a a. Otherwise, construct the
143 * concatenation \a c, free \a a (but not \a b) and return \a c.
144 *
145 * \sa strcat(3).
146 */
147 __must_check __malloc char *adu_strcat(char *a, const char *b)
148 {
149 char *tmp;
150
151 if (!a)
152 return adu_strdup(b);
153 if (!b)
154 return a;
155 tmp = make_message("%s%s", a, b);
156 free(a);
157 return tmp;
158 }
159
160 /** \cond LLONG_MAX and LLONG_LIN might not be defined. */
161 #ifndef LLONG_MAX
162 #define LLONG_MAX (1 << (sizeof(long) - 1))
163 #endif
164 #ifndef LLONG_MIN
165 #define LLONG_MIN (-LLONG_MAX - 1LL)
166 #endif
167 /** \endcond */
168
169 /**
170 * Convert a string to a 64-bit signed integer value.
171 *
172 * \param str The string to be converted.
173 * \param result Result pointer.
174 *
175 * \return Standard.
176 *
177 * \sa strtol(3), atoi(3).
178 */
179 __must_check int atoi64(const char *str, int64_t *result)
180 {
181 char *endptr;
182 long long tmp;
183
184 errno = 0; /* To distinguish success/failure after call */
185 tmp = strtoll(str, &endptr, 10);
186 if (errno == ERANGE && (tmp == LLONG_MAX || tmp == LLONG_MIN))
187 return -E_ATOI_OVERFLOW;
188 if (errno != 0 && tmp == 0) /* other error */
189 return -E_STRTOLL;
190 if (endptr == str)
191 return -E_ATOI_NO_DIGITS;
192 if (*endptr != '\0') /* Further characters after number */
193 return -E_ATOI_JUNK_AT_END;
194 *result = tmp;
195 return 1;
196 }
197
198 /**
199 * Split a string and return pointers to its parts.
200 *
201 * \param args The string to be split.
202 * \param argv_ptr Pointer to the list of substrings.
203 * \param delim Delimiter.
204 *
205 * This function modifies \a args by replacing each occurance of \a delim by
206 * zero. A \p NULL terminated array of pointers to char* is allocated dynamically
207 * and these pointers are initialized to point to the broken-up substrings
208 * within \a args. A pointer to this array is returned via \a argv_ptr.
209 *
210 * \return The number of substrings found in \a args.
211 */
212 __must_check unsigned split_args(char *args, char *** const argv_ptr, const char *delim)
213 {
214 char *p = args;
215 char **argv;
216 size_t n = 0, i, j;
217
218 p = args + strspn(args, delim);
219 for (;;) {
220 i = strcspn(p, delim);
221 if (!i)
222 break;
223 p += i;
224 n++;
225 p += strspn(p, delim);
226 }
227 *argv_ptr = adu_malloc((n + 1) * sizeof(char *));
228 argv = *argv_ptr;
229 i = 0;
230 p = args + strspn(args, delim);
231 while (p) {
232 argv[i] = p;
233 j = strcspn(p, delim);
234 if (!j)
235 break;
236 p += strcspn(p, delim);
237 if (*p) {
238 *p = '\0';
239 p++;
240 p += strspn(p, delim);
241 }
242 i++;
243 }
244 argv[n] = NULL;
245 return n;
246 }
247
248
249 static int get_next_word(const char *line, char **word)
250 {
251 enum line_state_flags {LSF_HAVE_WORD = 1, LSF_BACKSLASH = 2,
252 LSF_QUOTE = 4};
253 const char *in;
254 char *out;
255 int ret, state = 0;
256
257 out = adu_malloc(strlen(line) + 1);
258 *out = '\0';
259 *word = out;
260 for (in = line; *in; in++) {
261 switch (*in) {
262 case '\\':
263 if (state & LSF_BACKSLASH) /* \\ */
264 break;
265 state |= LSF_BACKSLASH;
266 state |= LSF_HAVE_WORD;
267 continue;
268 case 'n':
269 case 't':
270 if (state & LSF_BACKSLASH) { /* \n or \t */
271 *out++ = (*in == 'n')? '\n' : '\t';
272 state &= ~LSF_BACKSLASH;
273 continue;
274 }
275 break;
276 case '"':
277 if (state & LSF_BACKSLASH) /* \" */
278 break;
279 if (state & LSF_QUOTE) {
280 state &= ~LSF_QUOTE;
281 continue;
282 }
283 state |= LSF_HAVE_WORD;
284 state |= LSF_QUOTE;
285 continue;
286 case ' ':
287 case '\t':
288 case '\n':
289 if (state & LSF_BACKSLASH)
290 break;
291 if (state & LSF_QUOTE)
292 break;
293 if (state & LSF_HAVE_WORD)
294 goto success;
295 /* ignore space at the beginning */
296 continue;
297 }
298 /* copy char */
299 state |= LSF_HAVE_WORD;
300 *out++ = *in;
301 state &= ~LSF_BACKSLASH;
302 }
303 ret = 0;
304 if (!(state & LSF_HAVE_WORD))
305 goto out;
306 ret = -ERRNO_TO_ERROR(EINVAL);
307 if (state & LSF_BACKSLASH) {
308 ERROR_LOG("trailing backslash\n");
309 goto out;
310 }
311 if (state & LSF_QUOTE) {
312 ERROR_LOG("unmatched quote character\n");
313 goto out;
314 }
315 success:
316 *out = '\0';
317 return in - line;
318 out:
319 free(*word);
320 *word = NULL;
321 return ret;
322 }
323
324 /**
325 * Free an array of words created by create_argv().
326 *
327 * \param argv A pointer previously obtained by \ref create_argv().
328 */
329 void free_argv(char **argv)
330 {
331 int i;
332
333 for (i = 0; argv[i]; i++)
334 free(argv[i]);
335 free(argv);
336 }
337
338 /**
339 * Split a line into words which are separated by whitespace.
340 *
341 * In contrast to gengetopt's string parser, double quotes, backslash-escaped
342 * characters and special characters like \p \\n are honored. The result
343 * contains pointers to copies of the words contained in \a line and has to be
344 * freed by using \ref free_argv().
345 *
346 * \param line The line to be split.
347 * \param result The array of words is returned here.
348 *
349 * \return Number of words in \a line, negative on errors.
350 */
351 int create_argv(const char *line, char ***result)
352 {
353 char *word, **argv = adu_malloc(2 * sizeof(char *));
354 const char *p;
355 int ret, num_words;
356
357 argv[0] = adu_strdup(line);
358 for (p = line, num_words = 1; ; p += ret, num_words++) {
359 ret = get_next_word(p, &word);
360 if (ret < 0)
361 goto err;
362 if (!ret)
363 break;
364 argv = adu_realloc(argv, (num_words + 2) * sizeof(char*));
365 argv[num_words] = word;
366 }
367 argv[num_words] = NULL;
368 *result = argv;
369 return num_words;
370 err:
371 while (num_words > 0)
372 free(argv[--num_words]);
373 free(argv);
374 return ret;
375 }