From 99b72c09726f1475202d3312d581e4d0cedf618c Mon Sep 17 00:00:00 2001
From: ridiculousfish <corydoras@ridiculousfish.com>
Date: Tue, 10 Oct 2017 23:31:27 -0700
Subject: [PATCH] Stop passing NULL for realpath()'s second param

macOS 10.5 and earlier do not support the convention of returning
a dynamically allocated string, plus this seems like an unnecessary
malloc. Always allocate a buffer for realpath() to write into.

(cherry picked from commit 05c0cb713d961c59fc55b8b718249d8d724d3c84)
---
 src/wutil.cpp | 18 ++++++------------
 1 file changed, 6 insertions(+), 12 deletions(-)

diff --git a/src/wutil.cpp b/src/wutil.cpp
index 6bc71c8cb..338019555 100644
--- a/src/wutil.cpp
+++ b/src/wutil.cpp
@@ -350,7 +350,8 @@ wchar_t *wrealpath(const wcstring &pathname, wchar_t *resolved_path) {
         narrow_path.erase(narrow_path.size() - 1, 1);
     }
 
-    char *narrow_res = realpath(narrow_path.c_str(), NULL);
+    char tmpbuf[PATH_MAX];
+    char *narrow_res = realpath(narrow_path.c_str(), tmpbuf);
     if (narrow_res) {
         real_path.append(narrow_res);
     } else {
@@ -360,14 +361,15 @@ wchar_t *wrealpath(const wcstring &pathname, wchar_t *resolved_path) {
             // single path component and thus doesn't need conversion.
             real_path = narrow_path;
         } else {
+            char tmpbuff[PATH_MAX];
             if (pathsep_idx == cstring::npos) {
                 // No pathsep means a single path component relative to pwd.
-                narrow_res = realpath(".", NULL);
-                assert(narrow_res != NULL);
+                narrow_res = realpath(".", tmpbuff);
+                assert(narrow_res != NULL && "realpath unexpectedly returned null");
                 pathsep_idx = 0;
             } else {
                 // Only call realpath() on the portion up to the last component.
-                narrow_res = realpath(narrow_path.substr(0, pathsep_idx).c_str(), NULL);
+                narrow_res = realpath(narrow_path.substr(0, pathsep_idx).c_str(), tmpbuff);
                 if (!narrow_res) return NULL;
                 pathsep_idx++;
             }
@@ -377,14 +379,6 @@ wchar_t *wrealpath(const wcstring &pathname, wchar_t *resolved_path) {
             real_path.append(narrow_path.substr(pathsep_idx, cstring::npos));
         }
     }
-#if __APPLE__ && __DARWIN_C_LEVEL < 200809L
-// OS X Snow Leopard is broken with respect to the dynamically allocated buffer returned by
-// realpath(). It's not dynamically allocated so attempting to free that buffer triggers a
-// malloc/free error. Thus we don't attempt the free in this case.
-#else
-    free(narrow_res);
-#endif
-
     wcstring wreal_path = str2wcstring(real_path);
     if (resolved_path) {
         wcslcpy(resolved_path, wreal_path.c_str(), PATH_MAX);