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 */ 13char *xmalloc_readlink(const char *path) 14{ 15 enum { GROWBY = 80 }; /* how large we will grow strings by */ 16 17 char *buf = NULL; 18 int bufsize = 0, readsize = 0; 19 20 do { 21 buf = xrealloc(buf, bufsize += GROWBY); 22 readsize = readlink(path, buf, bufsize); 23 if (readsize == -1) { 24 free(buf); 25 return NULL; 26 } 27 } while (bufsize < readsize + 1); 28 29 buf[readsize] = '\0'; 30 31 return buf; 32} 33 34char *xmalloc_readlink_or_warn(const char *path) 35{ 36 char *buf = xmalloc_readlink(path); 37 if (!buf) { 38 /* EINVAL => "file: Invalid argument" => puzzled user */ 39 bb_error_msg("%s: cannot read link (not a symlink?)", path); 40 } 41 return buf; 42} 43 44/* UNUSED */ 45