changeset 1273:79e847fec774 draft

In function readfile(), the buffer buf is free'd when readall() fails. This free can cause a crash, if the buffer passed by user of function is not malloc'ed one. names_to_pid() is one usecase example here.
author Ashwini Sharma <ak.ashwini1981@gmail.com>
date Fri, 02 May 2014 06:24:11 -0500
parents 17935382d2c1
children c47218ccbfdf
files lib/lib.c
diffstat 1 files changed, 5 insertions(+), 3 deletions(-) [+]
line wrap: on
line diff
--- a/lib/lib.c	Fri May 02 06:17:48 2014 -0500
+++ b/lib/lib.c	Fri May 02 06:24:11 2014 -0500
@@ -323,9 +323,10 @@
 
 // Read contents of file as a single nul-terminated string.
 // malloc new one if buf=len=0
-char *readfile(char *name, char *buf, off_t len)
+char *readfile(char *name, char *ibuf, off_t len)
 {
   int fd;
+  char *buf;
 
   fd = open(name, O_RDONLY);
   if (fd == -1) return 0;
@@ -335,12 +336,13 @@
     // proc files don't report a length, so try 1 page minimum.
     if (len<4096) len = 4096;
   }
-  if (!buf) buf = xmalloc(len+1);
+  if (!ibuf) buf = xmalloc(len+1);
+  else buf = ibuf;
 
   len = readall(fd, buf, len-1);
   close(fd);
   if (len<0) {
-    free(buf);
+    if (ibuf != buf) free(buf);
     buf = 0;
   } else buf[len] = 0;