From 9fd7a4d08b6414ce4b5b130316b688f36c6a6265 Mon Sep 17 00:00:00 2001 From: Masamichi Hosoda Date: Sat, 11 Mar 2017 19:12:15 +0900 Subject: [PATCH] Issue 5077/2: Improve portability of get_working_directory() We used `getcwd()` with `PATH_MAX` to get the current directory. However, `PATH_MAX` does not exist in environments such as GNU Hurd. Debian developers avoided `PATH_MAX` by using `get_current_dir_name()` instead of `getcwd()`. It needed to protected with `#ifdef _GNU_SOURCE` since `get_current_dir_name()` is glibc specific. So `PATH_MAX` was still required in non-glibc environments. There is a `getcwd()` extention that can avoid `PATH_MAX` by setting the first argument to NULL. The extension can be used in many environments, including glibc, but POSIX does not recommend it in conforming applications. This commit improves portability by obtaining the current directory with a method conforming to the standard. --- flower/file-name.cc | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/flower/file-name.cc b/flower/file-name.cc index e5dd6f6160..990e3d6d91 100644 --- a/flower/file-name.cc +++ b/flower/file-name.cc @@ -77,16 +77,21 @@ dir_name (const string &file_name) string get_working_directory () { -#ifdef _GNU_SOURCE - char *cwd = get_current_dir_name(); - string scwd(cwd); - free(cwd); - return scwd; +#ifdef PATH_MAX + vector cwd (PATH_MAX); #else - char cwd[PATH_MAX]; - // getcwd returns NULL upon a failure, contents of cwd would be undefined! - return string (getcwd (cwd, PATH_MAX)); + vector cwd (1024); #endif + while (getcwd (cwd.data (), cwd.size ()) == NULL) + { + if (errno != ERANGE) + { + // getcwd () fails. + return ""; + } + cwd.resize (cwd.size () * 2); + } + return string (cwd.data ()); } /* Join components to full file_name. */ -- 2.39.2