Skip to content

Commit 6976ead

Browse files
committed
[Tests] Don't use dirname() - it isn't safe. Also, use asprintf().
Replaced dirname() as the man page says (alarmingly) that it might write to the input string. Also use asprintf() to build the new value for DYLD_LIBRARY_PATH.
1 parent d39e069 commit 6976ead

File tree

1 file changed

+19
-6
lines changed

1 file changed

+19
-6
lines changed

test/RemoteMirror/Inputs/interop.m

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,18 @@
2525

2626
#import "SwiftRemoteMirrorLegacyInterop.h"
2727

28+
// dirname() is *not* safe - it may modify the input string; so instead just
29+
// copy anything up to the last slash.
30+
char *safe_dirname(const char *path) {
31+
const char *slash = strrchr(path, '/');
32+
if (!slash)
33+
return strdup(".");
34+
size_t len = slash - path;
35+
char *result = (char *)malloc(len + 1);
36+
memcpy(result, path, len);
37+
result[len] = '\0';
38+
return result;
39+
}
2840

2941
void *Load(char *path) {
3042
const char *libpath = getenv("DYLD_LIBRARY_PATH");
@@ -34,14 +46,15 @@
3446
if (libpath && path[0] == '/') {
3547
// If DYLD_LIBRARY_PATH is set, and the path we've been given is absolute,
3648
// then prepend the directory part of the path we've been given to it.
37-
const char *libdir = dirname(path);
38-
size_t pathlen = strlen(libpath);
49+
char *libdir = safe_dirname(path);
3950
size_t dirlen = strlen(libdir);
40-
ourlibpath = (char *)malloc(pathlen + dirlen + 2);
41-
memcpy(ourlibpath, libdir, dirlen);
42-
ourlibpath[dirlen] = ':';
51+
if (asprintf(&ourlibpath, "%s:%s", libdir, oldlibpath) < 0) {
52+
fprintf(stderr, "Unable to form new DYLD_LIBRARY_PATH!\n");
53+
exit(1);
54+
}
55+
free(libdir);
56+
4357
oldlibpath = ourlibpath + dirlen + 1;
44-
memcpy(ourlibpath + dirlen + 1, libpath, pathlen + 1);
4558

4659
setenv("DYLD_LIBRARY_PATH", ourlibpath, 1);
4760
}

0 commit comments

Comments
 (0)