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.
This commit is contained in:
Edward Thomson
2024-04-18 14:54:29 +01:00
parent cfd6e0148b
commit afb2ef21bc

View File

@@ -16,17 +16,35 @@
char *p_realpath(const char *pathname, char *resolved)
{
char *ret;
if ((ret = realpath(pathname, resolved)) == NULL)
char *result;
if ((result = realpath(pathname, resolved)) == NULL)
return NULL;
#ifdef __OpenBSD__
/* The OpenBSD realpath function behaves differently,
* figure out if the file exists */
if (access(ret, F_OK) < 0)
ret = NULL;
if (access(ret, F_OK) < 0) {
if (!resolved)
free(result);
return NULL;
}
#endif
return ret;
/*
* If resolved == NULL, the system has allocated the result
* string. We need to strdup this into _our_ allocator pool
* so that callers can free it with git__free.
*/
if (!resolved) {
char *dup = git__strdup(result);
free(result);
result = dup;
}
return result;
}
#endif