rework long option handling. saves ~1.2k
[oweals/busybox.git] / libbb / xreadlink.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  *  xreadlink.c - safe implementation of readlink.
4  *  Returns a NULL on failure...
5  */
6
7 #include "libbb.h"
8
9 /*
10  * NOTE: This function returns a malloced char* that you will have to free
11  * yourself. You have been warned.
12  */
13
14 char *xmalloc_readlink_or_warn(const char *path)
15 {
16         enum { GROWBY = 80 }; /* how large we will grow strings by */
17
18         char *buf = NULL;
19         int bufsize = 0, readsize = 0;
20
21         do {
22                 buf = xrealloc(buf, bufsize += GROWBY);
23                 readsize = readlink(path, buf, bufsize); /* 1st try */
24                 if (readsize == -1) {
25                         bb_perror_msg("%s", path);
26                         free(buf);
27                         return NULL;
28                 }
29         }
30         while (bufsize < readsize + 1);
31
32         buf[readsize] = '\0';
33
34         return buf;
35 }
36
37 char *xmalloc_realpath(const char *path)
38 {
39 #if defined(__GLIBC__) && !defined(__UCLIBC__)
40         /* glibc provides a non-standard extension */
41         return realpath(path, NULL);
42 #else
43         char buf[PATH_MAX+1];
44
45         /* on error returns NULL (xstrdup(NULL) ==NULL) */
46         return xstrdup(realpath(path, buf));
47 #endif
48 }