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
6 // RUN: ./NSCreateObjectFileImageFromMemory-basic.exe $RUN_DIR/foo.bundle
12 #include <sys/types.h>
18 #include <mach-o/dyld.h>
21 static void checkBundle(const char* path
, bool unlinkBeforeDestroy
)
23 int fd
= open(path
, O_RDONLY
, 0);
25 printf("[FAIL] open(%s) failed", path
);
30 if ( fstat(fd
, &stat_buf
) == -1) {
31 printf("[FAIL] fstat() failed\n");
35 void* loadAddress
= mmap(NULL
, stat_buf
.st_size
, PROT_READ
, MAP_FILE
| MAP_PRIVATE
, fd
, 0);
36 if ( loadAddress
== ((void*)(-1)) ) {
37 printf("[FAIL] mmap() failed\n");
43 NSObjectFileImage ofi
;
44 if ( NSCreateObjectFileImageFromMemory(loadAddress
, stat_buf
.st_size
, &ofi
) != NSObjectFileImageSuccess
) {
45 printf("[FAIL] NSCreateObjectFileImageFromMemory failed\n");
49 NSModule mod
= NSLinkModule(ofi
, path
, NSLINKMODULE_OPTION_NONE
);
51 printf("[FAIL] NSLinkModule failed\n");
55 if ( !unlinkBeforeDestroy
) {
56 // API lets you destroy ofi and NSModule lives on
57 if ( !NSDestroyObjectFileImage(ofi
) ) {
58 printf("[FAIL] NSDestroyObjectFileImage failed\n");
63 NSSymbol sym
= NSLookupSymbolInModule(mod
, "_fooInBundle");
65 printf("[FAIL] NSLookupSymbolInModule failed\n");
69 void* func
= NSAddressOfSymbol(sym
);
71 printf("[FAIL] NSAddressOfSymbol failed\n");
76 if ( dladdr(func
, &info
) == 0 ) {
77 printf("[FAIL] dladdr(&p, xx) failed\n");
80 //printf("_fooInBundle found in %s\n", info.dli_fname);
82 if ( !NSUnLinkModule(mod
, NSUNLINKMODULE_OPTION_NONE
) ) {
83 printf("[FAIL] NSUnLinkModule failed\n");
87 if ( dladdr(func
, &info
) != 0 ) {
88 printf("[FAIL] dladdr(&p, xx) found but should not have\n");
92 if ( unlinkBeforeDestroy
) {
93 if ( !NSDestroyObjectFileImage(ofi
) ) {
94 printf("[FAIL] NSDestroyObjectFileImage failed\n");
101 int main(int argc
, const char* argv
[])
103 printf("[BEGIN] NSCreateObjectFileImageFromMemory-basic\n");
105 checkBundle(argv
[1], true);
106 checkBundle(argv
[1], false);
108 // Now go again enough times to flush out any limits in our dlopen encodings.
109 for (unsigned i
= 0; i
!= 255; ++i
)
110 checkBundle(argv
[1], false);
112 printf("[PASS] NSCreateObjectFileImageFromMemory-basic\n");