2 * Copyright (C) 2004-2008 Andre Noll <maan@systemlinux.org>
4 * Licensed under the GPL v2. For licencing details see COPYING.
7 /** \file string.c Memory allocation and string handling functions. */
12 #include <sys/time.h> /* gettimeofday */
14 #include <sys/utsname.h> /* uname() */
20 * Paraslash's version of realloc().
22 * \param p Pointer to the memory block, may be \p NULL.
23 * \param size The desired new size.
25 * A wrapper for realloc(3). It calls \p exit(\p EXIT_FAILURE) on errors,
26 * i.e. there is no need to check the return value in the caller.
28 * \return A pointer to the newly allocated memory, which is suitably aligned
29 * for any kind of variable and may be different from \a p.
33 __must_check __malloc
void *para_realloc(void *p
, size_t size
)
36 * No need to check for NULL pointers: If p is NULL, the call
37 * to realloc is equivalent to malloc(size)
40 if (!(p
= realloc(p
, size
))) {
41 PARA_EMERG_LOG("realloc failed (size = %zu), aborting\n",
49 * Paraslash's version of malloc().
51 * \param size The desired new size.
53 * A wrapper for malloc(3) which exits on errors.
55 * \return A pointer to the allocated memory, which is suitably aligned for any
60 __must_check __malloc
void *para_malloc(size_t size
)
67 PARA_EMERG_LOG("malloc failed (size = %zu), aborting\n",
75 * Paraslash's version of calloc().
77 * \param size The desired new size.
79 * A wrapper for calloc(3) which exits on errors.
81 * \return A pointer to the allocated and zeroed-out memory, which is suitably
82 * aligned for any kind of variable.
86 __must_check __malloc
void *para_calloc(size_t size
)
88 void *ret
= para_malloc(size
);
95 * Paraslash's version of strdup().
97 * \param s The string to be duplicated.
99 * A wrapper for strdup(3). It calls \p exit(EXIT_FAILURE) on errors, i.e.
100 * there is no need to check the return value in the caller.
102 * \return A pointer to the duplicated string. If \p s was the NULL pointer,
103 * an pointer to an empty string is returned.
107 __must_check __malloc
char *para_strdup(const char *s
)
111 if ((ret
= strdup(s
? s
: "")))
113 PARA_EMERG_LOG("strdup failed, aborting\n");
118 * Allocate a sufficiently large string and print into it.
120 * \param fmt A usual format string.
122 * Produce output according to \p fmt. No artificial bound on the length of the
123 * resulting string is imposed.
125 * \return This function either returns a pointer to a string that must be
126 * freed by the caller or aborts without returning.
130 __must_check __printf_1_2 __malloc
char *make_message(const char *fmt
, ...)
134 PARA_VSPRINTF(fmt
, msg
);
139 * Paraslash's version of strcat().
141 * \param a String to be appended to.
142 * \param b String to append.
144 * Append \p b to \p a.
146 * \return If \a a is \p NULL, return a pointer to a copy of \a b, i.e.
147 * para_strcat(NULL, b) is equivalent to para_strdup(b). If \a b is \p NULL,
148 * return \a a without making a copy of \a a. Otherwise, construct the
149 * concatenation \a c, free \a a (but not \a b) and return \a c.
153 __must_check __malloc
char *para_strcat(char *a
, const char *b
)
158 return para_strdup(b
);
161 tmp
= make_message("%s%s", a
, b
);
167 * Paraslash's version of dirname().
169 * \param name Pointer to the full path.
171 * Compute the directory component of \p name.
173 * \return If \a name is \p NULL or the empty string, return \p NULL.
174 * Otherwise, Make a copy of \a name and return its directory component. Caller
175 * is responsible to free the result.
177 __must_check __malloc
char *para_dirname(const char *name
)
183 ret
= para_strdup(name
);
184 p
= strrchr(ret
, '/');
193 * Paraslash's version of basename().
195 * \param name Pointer to the full path.
197 * Compute the filename component of \a name.
199 * \return \p NULL if (a) \a name is the empty string or \p NULL, or (b) name
200 * ends with a slash. Otherwise, a pointer within \a name is returned. Caller
201 * must not free the result.
203 __must_check
const char *para_basename(const char *name
)
209 ret
= strrchr(name
, '/');
217 * Cut trailing newline.
219 * \param buf The string to be chopped.
221 * Replace the last character in \p buf by zero if it is euqal to
222 * the newline character.
229 if (buf
[n
- 1] == '\n')
234 * Get a random filename.
236 * This is by no means a secure way to create temporary files in a hostile
237 * direcory like \p /tmp. However, it is OK to use for temp files, fifos,
238 * sockets that are created in ~/.paraslash. Result must be freed by the
241 * \return A pointer to a random filename.
243 __must_check __malloc
char *para_tmpname(void)
248 gettimeofday(&now
, NULL
);
251 return make_message("%08i", rand());
255 * Get the logname of the current user.
257 * \return A dynammically allocated string that must be freed by the caller. On
258 * errors, the string "unknown user" is returned, i.e. this function never
263 __must_check __malloc
char *para_logname(void)
265 struct passwd
*pw
= getpwuid(getuid());
266 return para_strdup(pw
? pw
->pw_name
: "unknown_user");
270 * Get the home directory of the current user.
272 * \return A dynammically allocated string that must be freed by the caller. If
273 * the home directory could not be found, this function returns "/tmp".
275 __must_check __malloc
char *para_homedir(void)
277 struct passwd
*pw
= getpwuid(getuid());
278 return para_strdup(pw
? pw
->pw_dir
: "/tmp");
282 * Split string and return pointers to its parts.
284 * \param args The string to be split.
285 * \param argv_ptr Pointer to the list of substrings.
286 * \param delim Delimiter.
288 * This function modifies \a args by replacing each occurance of \a delim by
289 * zero. A \p NULL-terminated array of pointers to char* is allocated dynamically
290 * and these pointers are initialized to point to the broken-up substrings
291 * within \a args. A pointer to this array is returned via \a argv_ptr.
293 * \return The number of substrings found in \a args.
295 __must_check
unsigned split_args(char *args
, char *** const argv_ptr
, const char *delim
)
301 p
= args
+ strspn(args
, delim
);
303 i
= strcspn(p
, delim
);
308 p
+= strspn(p
, delim
);
310 *argv_ptr
= para_malloc((n
+ 1) * sizeof(char *));
313 p
= args
+ strspn(args
, delim
);
316 j
= strcspn(p
, delim
);
319 p
+= strcspn(p
, delim
);
323 p
+= strspn(p
, delim
);
332 * Ensure that file descriptors 0, 1, and 2 are valid.
334 * Common approach that opens /dev/null until it gets a file descriptor greater
337 * \sa okir's Black Hats Manual.
339 void valid_fd_012(void)
342 int fd
= open("/dev/null", O_RDWR
);
353 * Get the own hostname.
355 * \return A dynammically allocated string containing the hostname.
359 __malloc
char *para_hostname(void)
364 return para_strdup(u
.nodename
);
368 * Used to distinguish between read-only and read-write mode.
370 * \sa for_each_line(), for_each_line_ro().
372 enum for_each_line_modes
{
373 /** Activate read-only mode. */
375 /** Activate read-write mode. */
379 static int for_each_complete_line(enum for_each_line_modes mode
, char *buf
,
380 size_t size
, line_handler_t
*line_handler
, void *private_data
)
382 char *start
= buf
, *end
;
383 int ret
, i
, num_lines
= 0;
385 // PARA_NOTICE_LOG("buf: %s\n", buf);
386 while (start
< buf
+ size
) {
390 next_cr
= memchr(start
, '\n', buf
+ size
- start
);
391 next_null
= memchr(start
, '\0', buf
+ size
- start
);
392 if (!next_cr
&& !next_null
)
394 if (next_cr
&& next_null
) {
395 end
= next_cr
< next_null
? next_cr
: next_null
;
396 } else if (next_null
) {
405 if (mode
== LINE_MODE_RO
) {
406 size_t s
= end
- start
;
407 char *b
= para_malloc(s
+ 1);
410 // PARA_NOTICE_LOG("b: %s, start: %s\n", b, start);
411 ret
= line_handler(b
, private_data
);
415 ret
= line_handler(start
, private_data
);
421 if (!line_handler
|| mode
== LINE_MODE_RO
)
423 i
= buf
+ size
- start
;
425 memmove(buf
, start
, i
);
430 * Call a custom function for each complete line.
432 * \param buf The buffer containing data seperated by newlines.
433 * \param size The number of bytes in \a buf.
434 * \param line_handler The custom function.
435 * \param private_data Pointer passed to \a line_handler.
437 * If \p line_handler is \p NULL, the function returns the number of complete
438 * lines in \p buf. Otherwise, \p line_handler is called for each complete
439 * line in \p buf. The first argument to \p line_handler is the current line,
440 * and \p private_data is passed as the second argument. The function returns
441 * if \p line_handler returns a negative value or no more lines are in the
442 * buffer. The rest of the buffer (last chunk containing an incomplete line)
443 * is moved to the beginning of the buffer.
445 * \return If \p line_handler is not \p NULL, this function returns the number
446 * of bytes not handled to \p line_handler on success, or the negative return
447 * value of the \p line_handler on errors.
449 * \sa for_each_line_ro().
451 int for_each_line(char *buf
, size_t size
, line_handler_t
*line_handler
,
454 return for_each_complete_line(LINE_MODE_RW
, buf
, size
, line_handler
,
459 * Call a custom function for each complete line.
461 * \param buf Same meaning as in \p for_each_line().
462 * \param size Same meaning as in \p for_each_line().
463 * \param line_handler Same meaning as in \p for_each_line().
464 * \param private_data Same meaning as in \p for_each_line().
466 * This function behaves like \p for_each_line(), but \a buf is left unchanged.
468 * \return On success, the function returns the number of complete lines in \p
469 * buf, otherwise the (negative) return value of \p line_handler is returned.
471 * \sa for_each_line().
473 int for_each_line_ro(char *buf
, size_t size
, line_handler_t
*line_handler
,
476 return for_each_complete_line(LINE_MODE_RO
, buf
, size
, line_handler
,
481 * Safely print into a buffer at a given offset
483 * \param b Determines the buffer, its size, and the offset.
484 * \param fmt The format string.
486 * This function prints into the buffer given by \a b at the offset which is
487 * also given by \a b. If there is not enough space to hold the result, the
488 * buffer size is doubled until the underlying call to vsnprintf() succeeds
489 * or the size of the buffer exceeds the maximal size specified in \a pb.
491 * In the latter case the unmodified \a buf and \a offset values as well as the
492 * private_data pointer of \a b are passed to the \a max_size_handler of \a b.
493 * If this function succeeds, i.e. returns a non-negative value, the offset of
494 * \a b is reset to zero and the given data is written to the beginning of the
497 * Upon return, the offset of \a b is adjusted accordingly so that subsequent
498 * calls to this function append data to what is already contained in the
501 * It's OK to call this function with \p b->buf being \p NULL. In this case, an
502 * initial buffer is allocated.
504 * \return The number of bytes printed into the buffer (not including the
505 * therminating \p NULL byte).
507 * \sa make_message(), vsnprintf(3).
509 __printf_2_3
int para_printf(struct para_buffer
*b
, const char *fmt
, ...)
514 b
->buf
= para_malloc(128);
519 char *p
= b
->buf
+ b
->offset
;
520 size_t size
= b
->size
- b
->offset
;
524 ret
= vsnprintf(p
, size
, fmt
, ap
);
526 if (ret
> -1 && ret
< size
) { /* success */
531 /* check if we may grow the buffer */
532 if (!b
->max_size
|| 2 * b
->size
< b
->max_size
) { /* yes */
533 /* try again with more space */
535 b
->buf
= para_realloc(b
->buf
, b
->size
);
538 /* can't grow buffer */
539 if (!b
->offset
|| !b
->max_size_handler
) /* message too large */
540 return -ERRNO_TO_PARA_ERROR(ENOSPC
);
541 ret
= b
->max_size_handler(b
->buf
, b
->offset
, b
->private_data
);
548 /** \cond LLONG_MAX and LLONG_LIN might not be defined. */
550 #define LLONG_MAX (1 << (sizeof(long) - 1))
553 #define LLONG_MIN (-LLONG_MAX - 1LL)
558 * Convert a string to a 64-bit signed integer value.
560 * \param str The string to be converted.
561 * \param value Result pointer.
565 * \sa para_atoi32(), strtol(3), atoi(3).
567 int para_atoi64(const char *str
, int64_t *value
)
572 errno
= 0; /* To distinguish success/failure after call */
573 tmp
= strtoll(str
, &endptr
, 10);
574 if (errno
== ERANGE
&& (tmp
== LLONG_MAX
|| tmp
== LLONG_MIN
))
575 return -E_ATOI_OVERFLOW
;
576 if (errno
!= 0 && tmp
== 0) /* other error */
579 return -E_ATOI_NO_DIGITS
;
580 if (*endptr
!= '\0') /* Further characters after number */
581 return -E_ATOI_JUNK_AT_END
;
587 * Convert a string to a 32-bit signed integer value.
589 * \param str The string to be converted.
590 * \param value Result pointer.
596 int para_atoi32(const char *str
, int32_t *value
)
600 const int32_t max
= 2147483647;
602 ret
= para_atoi64(str
, &tmp
);
605 if (tmp
> max
|| tmp
< -max
- 1)
606 return -E_ATOI_OVERFLOW
;