commit:     167ded327a715f6378942f668f326ebc26f15d1a
Author:     Mike Frysinger <vapier <AT> gentoo <DOT> org>
AuthorDate: Sun Sep 20 06:57:54 2015 +0000
Commit:     Mike Frysinger <vapier <AT> gentoo <DOT> org>
CommitDate: Sun Sep 20 06:57:54 2015 +0000
URL:        https://gitweb.gentoo.org/proj/sandbox.git/commit/?id=167ded32

libsandbox: egetcwd: fix handling of NULL inputs

We don't want to let the C library do the memory allocation for us when
buf==NULL as it won't use our memory functions, so when we try to call
our free on it, we get corruption.  Handle the automatic allocation in
the code directly.

Signed-off-by: Mike Frysinger <vapier <AT> gentoo.org>

 libsandbox/libsandbox.c | 20 ++++++++++++++++----
 1 file changed, 16 insertions(+), 4 deletions(-)

diff --git a/libsandbox/libsandbox.c b/libsandbox/libsandbox.c
index 4f4589f..3bd3794 100644
--- a/libsandbox/libsandbox.c
+++ b/libsandbox/libsandbox.c
@@ -306,7 +306,16 @@ static char *resolve_path(const char *path, int 
follow_link)
 char *egetcwd(char *buf, size_t size)
 {
        struct stat st;
-       char *tmpbuf, *oldbuf = buf;
+       char *tmpbuf;
+
+       /* We can't let the C lib allocate memory for us since we have our
+        * own local routines to handle things.
+        */
+       bool allocated = (buf == NULL);
+       if (allocated) {
+               size = SB_PATH_MAX;
+               buf = xmalloc(size);
+       }
 
        /* If tracing a child, our cwd may not be the same as the child's */
        if (trace_pid) {
@@ -354,9 +363,9 @@ char *egetcwd(char *buf, size_t size)
                        errno = ENAMETOOLONG;
 
                if (errno && errno != EACCES) {
-                       /* If getcwd() allocated the buffer, free it. */
-                       if (NULL == oldbuf)
-                               free(tmpbuf);
+                       /* If getcwd() allocated the buffer, free it. */
+                       if (allocated)
+                               free(buf);
 
                        /* Not sure if we should quit here, but I guess if
                         * lstat() fails, getcwd could have messed up. Not
@@ -368,6 +377,9 @@ char *egetcwd(char *buf, size_t size)
 
                restore_errno();
        } else if (errno != 0) {
+               /* If getcwd() allocated the buffer, free it. */
+               if (allocated)
+                       free(buf);
 
                /* Make sure we do not return garbage if the current libc or
                 * kernel's getcwd() is buggy.

Reply via email to