Skip to content

Commit afb2ef2

Browse files
committed
util: don't return system allocated strings in realpath
realpath(3) _may_ allocate strings (if the second param is NULL) using the system allocator. However, callers need an assurance that they can free memory using git__free. If we made realpath do an allocation, then make sure that we strdup it into our allocator's memory. More importantly, avoid this behavior by always providing a buffer to p_realpath invocations.
1 parent cfd6e01 commit afb2ef2

File tree

1 file changed

+23
-5
lines changed

1 file changed

+23
-5
lines changed

src/util/unix/realpath.c

Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,17 +16,35 @@
1616

1717
char *p_realpath(const char *pathname, char *resolved)
1818
{
19-
char *ret;
20-
if ((ret = realpath(pathname, resolved)) == NULL)
19+
char *result;
20+
21+
if ((result = realpath(pathname, resolved)) == NULL)
2122
return NULL;
2223

2324
#ifdef __OpenBSD__
2425
/* The OpenBSD realpath function behaves differently,
2526
* figure out if the file exists */
26-
if (access(ret, F_OK) < 0)
27-
ret = NULL;
27+
if (access(ret, F_OK) < 0) {
28+
if (!resolved)
29+
free(result);
30+
31+
return NULL;
32+
}
2833
#endif
29-
return ret;
34+
35+
/*
36+
* If resolved == NULL, the system has allocated the result
37+
* string. We need to strdup this into _our_ allocator pool
38+
* so that callers can free it with git__free.
39+
*/
40+
if (!resolved) {
41+
char *dup = git__strdup(result);
42+
free(result);
43+
44+
result = dup;
45+
}
46+
47+
return result;
3048
}
3149

3250
#endif

0 commit comments

Comments
 (0)