3 // BUILD: $CC main.c -o $BUILD_DIR/NSCreateObjectFileImageFromMemory-basic.exe -Wno-deprecated-declarations
4 // BUILD: $CC foo.c -o $BUILD_DIR/foo.bundle -bundle
5 // BUILD: lipo -thin x86_64 $BUILD_DIR/foo.bundle -output $BUILD_DIR/foo-thin.bundle
7 // RUN: ./NSCreateObjectFileImageFromMemory-basic.exe $RUN_DIR/foo.bundle
8 // RUN: ./NSCreateObjectFileImageFromMemory-basic.exe $RUN_DIR/foo-thin.bundle
15 #include <sys/types.h>
21 #include <mach-o/dyld.h>
24 static void checkBundle(const char* path
, bool unlinkBeforeDestroy
)
26 int fd
= open(path
, O_RDONLY
, 0);
28 printf("[FAIL] open(%s) failed", path
);
33 if ( fstat(fd
, &stat_buf
) == -1) {
34 printf("[FAIL] fstat() failed\n");
38 void* loadAddress
= mmap(NULL
, stat_buf
.st_size
, PROT_READ
, MAP_FILE
| MAP_PRIVATE
, fd
, 0);
39 if ( loadAddress
== ((void*)(-1)) ) {
40 printf("[FAIL] mmap() failed\n");
46 NSObjectFileImage ofi
;
47 if ( NSCreateObjectFileImageFromMemory(loadAddress
, stat_buf
.st_size
, &ofi
) != NSObjectFileImageSuccess
) {
48 printf("[FAIL] NSCreateObjectFileImageFromMemory failed\n");
52 NSModule mod
= NSLinkModule(ofi
, path
, NSLINKMODULE_OPTION_NONE
);
54 printf("[FAIL] NSLinkModule failed\n");
58 if ( !unlinkBeforeDestroy
) {
59 // API lets you destroy ofi and NSModule lives on
60 if ( !NSDestroyObjectFileImage(ofi
) ) {
61 printf("[FAIL] NSDestroyObjectFileImage failed\n");
66 NSSymbol sym
= NSLookupSymbolInModule(mod
, "_fooInBundle");
68 printf("[FAIL] NSLookupSymbolInModule failed\n");
72 void* func
= NSAddressOfSymbol(sym
);
74 printf("[FAIL] NSAddressOfSymbol failed\n");
79 if ( dladdr(func
, &info
) == 0 ) {
80 printf("[FAIL] dladdr(&p, xx) failed\n");
83 //printf("_fooInBundle found in %s\n", info.dli_fname);
85 if ( !NSUnLinkModule(mod
, NSUNLINKMODULE_OPTION_NONE
) ) {
86 printf("[FAIL] NSUnLinkModule failed\n");
90 if ( dladdr(func
, &info
) != 0 ) {
91 printf("[FAIL] dladdr(&p, xx) found but should not have\n");
95 if ( unlinkBeforeDestroy
) {
96 if ( !NSDestroyObjectFileImage(ofi
) ) {
97 printf("[FAIL] NSDestroyObjectFileImage failed\n");
104 int main(int argc
, const char* argv
[])
106 printf("[BEGIN] NSCreateObjectFileImageFromMemory-basic\n");
108 checkBundle(argv
[1], true);
109 checkBundle(argv
[1], false);
111 // Now go again enough times to flush out any limits in our dlopen encodings.
112 for (unsigned i
= 0; i
!= 255; ++i
)
113 checkBundle(argv
[1], false);
115 printf("[PASS] NSCreateObjectFileImageFromMemory-basic\n");