summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorTanguy LE CARROUR <tanguy@bioneland.org>2012-02-07 10:21:41 +0100
committerTanguy LE CARROUR <tanguy@bioneland.org>2012-02-07 10:21:41 +0100
commitace95019ae33f409647598d61fe979c24faf0564 (patch)
tree826eb3cb1fde65adec2a1b1c201c5fdc05f042d9
parentd8dacac1f72b24ebe741c3d98d0152150dec1edf (diff)
Add readlink_malloc() as an alternative to readlink().
-rw-r--r--user/tlecarrour/porting_guide_for_dummies.mdwn77
1 files changed, 52 insertions, 25 deletions
diff --git a/user/tlecarrour/porting_guide_for_dummies.mdwn b/user/tlecarrour/porting_guide_for_dummies.mdwn
index 91fdac95..176db195 100644
--- a/user/tlecarrour/porting_guide_for_dummies.mdwn
+++ b/user/tlecarrour/porting_guide_for_dummies.mdwn
@@ -148,31 +148,31 @@ use a new_buff to check if everything went fine Free buf if realloc failed (and
Function to read line (no size limit, ending with "\n") from a file.
- +static char *get_line(FILE *f)
- +{
- + char *buff = NULL;
- + char *new_buff = NULL;
- + size_t buff_size = 0;
- + size_t last = 0;
- +
- + while (!feof(f)) {
- + buff_size = buff_size ? buff_size * 2 : BUFSIZ;
- + new_buff = realloc(buff, buff_size);
- + if (new_buff == NULL) {
- + free(buff);
- + return NULL;
- + }
- + buff = new_buff;
- + if (fgets(buff + last, buff_size - last, f) == NULL) {
- + free(buff);
- + return NULL;
- + }
- + last = strlen(buff);
- + if (buff[last - 1] == '\n')
- + return buff;
- + }
- + return buff;
- +}
+ static char *get_line(FILE *f)
+ {
+ char *buff = NULL;
+ char *new_buff = NULL;
+ size_t buff_size = 0;
+ size_t last = 0;
+
+ while (!feof(f)) {
+ buff_size = buff_size ? buff_size * 2 : BUFSIZ;
+ new_buff = realloc(buff, buff_size);
+ if (new_buff == NULL) {
+ free(buff);
+ return NULL;
+ }
+ buff = new_buff;
+ if (fgets(buff + last, buff_size - last, f) == NULL) {
+ free(buff);
+ return NULL;
+ }
+ last = strlen(buff);
+ if (buff[last - 1] == '\n')
+ return buff;
+ }
+ return buff;
+ }
### Proper use of readlink()
@@ -201,3 +201,30 @@ Call readlink(), check return value and set the null char in the linkname:
...
linkname[sb.st_size] = '\0';
+
+### Alternative use of readlink()
+
+In some cases the above approch doesn't work.for instance when reading from
+**/proc/*/exe** on Linux. In this case you can try the following function.
+The code comes from [[https://buildsecurityin.us-cert.gov/bsi/articles/knowledge/coding/806-BSI.html]]
+
+ static char *readlink_malloc(const char *filename)
+ {
+ int size = 100;
+
+ while (1) {
+ char *buff = malloc(size);
+ if (buff == NULL)
+ return NULL;
+ int nchars = readlink(filename, buff, size);
+ if (nchars < 0)
+ return NULL;
+ if (nchars < size) {
+ buff[nchars] = '\0';
+ return buff;
+ }
+ free (buff);
+ size *= 2;
+ }
+ }
+