dyld-625.13.tar.gz
[apple/dyld.git] / testing / test-cases / _dyld_is_memory_immutable.dtest / main.c
1
2 // BUILD: $CC foo.c -dynamiclib -install_name $RUN_DIR/libfoo.dylib -o $BUILD_DIR/libfoo.dylib
3 // BUILD: $CC bar.c -dynamiclib -install_name $RUN_DIR/libbar.dylib -o $BUILD_DIR/libbar.dylib
4 // BUILD: $CC main.c -DRUN_DIR="$RUN_DIR" $BUILD_DIR/libfoo.dylib -o $BUILD_DIR/dyld_immutable_test.exe
5
6 // RUN: ./dyld_immutable_test.exe
7
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <dlfcn.h>
11 #include <mach-o/dyld.h>
12 #include <mach-o/dyld_priv.h>
13
14 #if __has_feature(ptrauth_calls)
15 #include <ptrauth.h>
16 #endif
17
18 static const void* stripPointer(const void* ptr)
19 {
20 #if __has_feature(ptrauth_calls)
21 return __builtin_ptrauth_strip(ptr, ptrauth_key_asia);
22 #else
23 return ptr;
24 #endif
25 }
26
27
28 typedef const char* (*BarProc)(void);
29
30 extern uint32_t _cpu_capabilities;
31 extern const char* foo();
32
33 const char* myStr = "myStr";
34
35 int myInt;
36
37
38 int main()
39 {
40 printf("[BEGIN] _dyld_is_memory_immutable\n");
41
42 if ( !_dyld_is_memory_immutable(myStr, 6) ) {
43 printf("[FAIL] _dyld_is_memory_immutable() returned false for string in main executable\n");
44 return 0;
45 }
46
47 if ( _dyld_is_memory_immutable(strdup("hello"), 6) ) {
48 printf("[FAIL] _dyld_is_memory_immutable() returned true for result from strdup()\n");
49 return 0;
50 }
51
52 if ( _dyld_is_memory_immutable(&myInt, 4) ) {
53 printf("[FAIL] _dyld_is_memory_immutable() returned true for global variabe in main executable\n");
54 return 0;
55 }
56
57 if ( !_dyld_is_memory_immutable(foo(), 4) ) {
58 printf("[FAIL] _dyld_is_memory_immutable() returned false for string in statically linked dylib\n");
59 return 0;
60 }
61
62 if ( !_dyld_is_memory_immutable(stripPointer((void*)&strcpy), 4) ) {
63 printf("[FAIL] _dyld_is_memory_immutable() returned false for strcpy function in dyld shared cache\n");
64 return 0;
65 }
66
67 if ( _dyld_is_memory_immutable(&_cpu_capabilities, 4) ) {
68 printf("[FAIL] _dyld_is_memory_immutable() returned true for global variable in shared cache\n");
69 return 0;
70 }
71
72 void* handle = dlopen(RUN_DIR "/libbar.dylib", RTLD_FIRST);
73 if ( handle == NULL ) {
74 printf("[FAIL] dlopen(libbar.dylib) failed");
75 return 0;
76 }
77
78 BarProc proc = dlsym(handle, "bar");
79 if ( proc == NULL ) {
80 printf("[FAIL] dlsym(bar) failed\n");
81 return 0;
82 }
83 const char* barStr = (*proc)();
84 if ( _dyld_is_memory_immutable(barStr, 4) ) {
85 printf("[FAIL] _dyld_is_memory_immutable() returned true for string in unloadable dylib\n");
86 return 0;
87 }
88
89
90 printf("[PASS] _dyld_is_memory_immutable\n");
91 return 0;
92 }
93