|
19 | 19 | #import <Foundation/Foundation.h>
|
20 | 20 | #import <mach/mach.h>
|
21 | 21 | #import <mach-o/dyld.h>
|
| 22 | +#import <libgen.h> |
| 23 | +#import <stdlib.h> |
| 24 | +#import <string.h> |
22 | 25 |
|
23 | 26 | #import "SwiftRemoteMirrorLegacyInterop.h"
|
24 | 27 |
|
| 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 | +} |
25 | 40 |
|
26 | 41 | 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 |
27 | 63 | 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 | + |
28 | 71 | if (Handle == NULL) {
|
29 | 72 | fprintf(stderr, "loading %s: %s\n", path, dlerror());
|
30 | 73 | exit(1);
|
|
0 commit comments