Skip to content

Commit 7e001ec

Browse files
authored
Merge pull request #38960 from al45tair/problem/82124292
[Tests] Fix RemoteMirror test to work when DYLD_LIBRARY_PATH is set.
2 parents d43ea45 + 6976ead commit 7e001ec

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

test/RemoteMirror/Inputs/interop.m

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,12 +19,55 @@
1919
#import <Foundation/Foundation.h>
2020
#import <mach/mach.h>
2121
#import <mach-o/dyld.h>
22+
#import <libgen.h>
23+
#import <stdlib.h>
24+
#import <string.h>
2225

2326
#import "SwiftRemoteMirrorLegacyInterop.h"
2427

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+
}
2540

2641
void *Load(char *path) {
42+
const char *libpath = getenv("DYLD_LIBRARY_PATH");
43+
char *ourlibpath = NULL;
44+
const char *oldlibpath = NULL;
45+
46+
if (libpath && path[0] == '/') {
47+
// If DYLD_LIBRARY_PATH is set, and the path we've been given is absolute,
48+
// then prepend the directory part of the path we've been given to it.
49+
char *libdir = safe_dirname(path);
50+
size_t dirlen = strlen(libdir);
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+
57+
oldlibpath = ourlibpath + dirlen + 1;
58+
59+
setenv("DYLD_LIBRARY_PATH", ourlibpath, 1);
60+
}
61+
62+
// Actually open the dylib
2763
void *Handle = dlopen(path, RTLD_LOCAL);
64+
65+
if (ourlibpath) {
66+
// Reset DYLD_LIBRARY_PATH, if we changed it
67+
setenv("DYLD_LIBRARY_PATH", oldlibpath, 1);
68+
free(ourlibpath);
69+
}
70+
2871
if (Handle == NULL) {
2972
fprintf(stderr, "loading %s: %s\n", path, dlerror());
3073
exit(1);

0 commit comments

Comments
 (0)