5 #include <mach-o/nlist.h>
12 #include "Exception.hpp"
13 #include "Pooling.hpp"
14 #include "Trampoline.t.hpp"
16 extern "C" void _pthread_set_self(pthread_t
);
18 template <typename Type_
>
19 static void nlset(Type_
&function
, struct nlist
*nl
, size_t index
) {
20 struct nlist
&name(nl
[index
]);
21 uintptr_t value(name
.n_value
);
22 if ((name
.n_desc
& N_ARM_THUMB_DEF
) != 0)
24 function
= reinterpret_cast<Type_
>(value
);
27 void InjectLibrary(pid_t pid
) {
28 const char *library("/Library/MobileSubstrate/DynamicLibraries/Cycript.dylib");
30 static const size_t Stack_(8 * 1024);
31 size_t length(strlen(library
) + 1), depth(sizeof(Baton
) + length
);
32 depth
= (depth
+ sizeof(uintptr_t) + 1) / sizeof(uintptr_t) * sizeof(uintptr_t);
35 uint8_t *local(reinterpret_cast<uint8_t *>(apr_palloc(pool
, depth
)));
37 Baton
*baton(reinterpret_cast<Baton
*>(local
));
38 baton
->pthread_create
= &pthread_create
;
39 baton
->pthread_detach
= &pthread_detach
;
40 baton
->dlopen
= &dlopen
;
41 baton
->mach_thread_self
= &mach_thread_self
;
42 baton
->thread_terminate
= &thread_terminate
;
43 memcpy(baton
->library
, library
, length
);
46 memset(nl
, 0, sizeof(nl
));
47 nl
[0].n_un
.n_name
= (char *) "__pthread_set_self";
48 nlist("/usr/lib/libSystem.B.dylib", nl
);
49 nlset(baton
->_pthread_set_self
, nl
, 0);
51 vm_size_t
size(depth
+ Stack_
);
53 mach_port_t
self(mach_task_self()), task
;
54 _krncall(task_for_pid(self
, pid
, &task
));
57 _krncall(vm_allocate(task
, &data
, size
, true));
58 vm_address_t
stack(data
+ depth
);
59 vm_write(task
, data
, reinterpret_cast<vm_address_t
>(baton
), depth
);
62 _krncall(vm_allocate(task
, &code
, sizeof(Trampoline_
), true));
63 vm_write(task
, code
, reinterpret_cast<vm_address_t
>(Trampoline_
), sizeof(Trampoline_
));
64 _krncall(vm_protect(task
, code
, sizeof(Trampoline_
), false, VM_PROT_READ
| VM_PROT_EXECUTE
));
67 _krncall(thread_create(task
, &thread
));
69 thread_state_flavor_t flavor
;
70 mach_msg_type_number_t count
;
73 arm_thread_state_t state
;
74 memset(&state
, 0, sizeof(state
));
76 flavor
= ARM_THREAD_STATE
;
77 count
= ARM_THREAD_STATE_COUNT
;
79 _krncall(thread_get_state(thread
, flavor
, reinterpret_cast<thread_state_t
>(&state
), &count
));
80 _assert(count
== ARM_THREAD_STATE_COUNT
);
83 state
.r
[1] = RTLD_LAZY
| RTLD_GLOBAL
;
84 state
.sp
= stack
+ Stack_
;
87 if ((state
.pc
& 0x1) != 0) {
92 _krncall(thread_set_state(thread
, flavor
, reinterpret_cast<thread_state_t
>(&state
), count
));
97 _krncall(thread_resume(thread
));
99 //_krncall(thread_create_running(task, flavor, reinterpret_cast<thread_state_t>(&state), count, &thread));
101 //_krncall(mach_port_deallocate(self, task));