Ticket #23098: 0002-Refactor-retrieving-the-current-working-directory.patch

File 0002-Refactor-retrieving-the-current-working-directory.patch, 2.2 KB (added by cypherpunks, 2 years ago)
  • configure.ac

    From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001
    From: cypherpunks <cypherpunks@torproject.org>
    Date: Thu, 3 Aug 2017 19:45:46 +0000
    Subject: [PATCH] Refactor retrieving the current working directory
    
    The GNU C Library (glibc) offers an function which allocates the
    necessary memory automatically [0]. When it is available, we use that.
    
    Otherwise we depend upon the `getcwd` function which requires a
    preallocated buffer (and its size). This function was used incorrectly
    by depending on the initial buffer size being big enough and otherwise
    failing to return the current working directory. The proper way of
    getting the current working directory requires a loop which doubles the
    buffer size if `getcwd` requires it. This code was copied from [1] with
    modifications to fit the context.
    
    [0] https://www.gnu.org/software/hurd/hurd/porting/guidelines.html
    [1] http://pubs.opengroup.org/onlinepubs/9699919799/functions/getcwd.html
    ---
     configure.ac        |  1 +
     src/common/compat.c | 25 ++++++++++++++++++-------
     2 files changed, 19 insertions(+), 7 deletions(-)
    
    diff --git a/configure.ac b/configure.ac
    index 4092d10af..345e499ff 100644
    a b AC_CHECK_FUNCS( 
    481481        timingsafe_memcmp \
    482482        flock \
    483483        ftime \
     484        get_current_dir_name \
    484485        getaddrinfo \
    485486        getifaddrs \
    486487        getpass \
  • src/common/compat.c

    diff --git a/src/common/compat.c b/src/common/compat.c
    index 4d110aba3..8e3d97420 100644
    a b get_parent_directory(char *fname) 
    23492349static char *
    23502350alloc_getcwd(void)
    23512351{
    2352 #ifdef PATH_MAX
    2353 #define MAX_CWD PATH_MAX
     2352#ifdef HAVE_GET_CURRENT_DIR_NAME
     2353  return get_current_dir_name();
    23542354#else
    2355 #define MAX_CWD 4096
    2356 #endif
     2355  size_t size = 1024;
     2356  char *buf = NULL;
     2357  char *ptr = NULL;
     2358
     2359  while (ptr == NULL) {
     2360    buf = tor_realloc(buf, size);
     2361    ptr = getcwd(buf, size);
    23572362
    2358   char path_buf[MAX_CWD];
    2359   char *path = getcwd(path_buf, sizeof(path_buf));
    2360   return path ? tor_strdup(path) : NULL;
     2363    if (ptr == NULL && errno != ERANGE) {
     2364      tor_free(buf);
     2365      return NULL;
     2366    }
     2367
     2368    size *= 2;
     2369  }
     2370  return buf;
     2371#endif
    23612372}
    23622373#endif
    23632374