Report abuse

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
/*

lookup_function_pointers.c ... An extremely fast and simple function to replace nlist.
 
Copyright (c) 2009, KennyTM~
All rights reserved.
 
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
 
 * Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, 
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.
 * Neither the name of the KennyTM~ nor the names of its contributors may be
   used to endorse or promote products derived from this software without
   specific prior written permission.
 
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 
*/

#include <mach-o/nlist.h>	// struct nlist
#include <mach-o/dyld.h>	// _dyld_image_count, etc.
#include <mach-o/loader.h>	// mach_header, etc.
#include <mach-o/fat.h>		// fat_header, etc.
#include <mach/mach.h>		// mach_host_self, etc.
#include <stdarg.h>
#include <stdlib.h>
#include <unistd.h>		// open
#include <fcntl.h>		// close
#include <sys/mman.h>		// mmap
#include <sys/stat.h>		// fstat

struct ImageLoaderMachO {
	void* vptr;
	// why?
#if __arm || __arm__
	void* vptr2;
#endif
	char _ImageLoader[68];
	
	const struct mach_header* fMachOData;
	const uint8_t* fLinkEditBase;
	const struct nlist* fSymbolTable;
	const char* fStrings;
	const struct dysymtab_command* fDynamicInfo;
	uintptr_t fSlide;
	// the rest are not important.
};

typedef struct ImageLoaderMachO* (*FPTR)(unsigned index);
static FPTR dyld_getIndexedImage = NULL;

static int get_image_index(const char* filename) {
	unsigned img_count = _dyld_image_count();
	size_t filename_len = strlen(filename);
	for (unsigned i = 0; i < img_count; ++ i) {
		const char* img_name = _dyld_get_image_name(i);
		size_t img_name_len = strlen(img_name);
		if (filename_len > img_name_len)
			continue;
		if (strncmp(filename, img_name - filename_len + img_name_len, filename_len) == 0)
			return i;
	}
	return -1;
}

/*
 Big big big assumptions:
 (1) dyld is at /usr/lib/dyld
 (2) there is a function called  dyld::getIndexedImage(unsigned)
 (3) it returns an ImageLoaderMachO pointer with fields compatible with above.
 (4) dyld's slide is zero.
 If any of these breaks, we're in great trouble.
 */
static int obtain_dyld() {
	int retval = 0;
	
	if (dyld_getIndexedImage == NULL) {
		int f = open("/usr/lib/dyld", O_RDONLY);
		if (f == -1)
			return -1;
		struct stat f_status;
		fstat(f, &f_status);
		char* m = (char*)mmap(NULL, f_status.st_size, PROT_READ, MAP_PRIVATE, f, 0);
		if ((int)m == -1) {
			close(f);
			return -2;
		}
		
		const struct mach_header* header = (const struct mach_header*)m;
		
		// Partly ref: http://svn.saurik.com/repos/menes/trunk/mobilesubstrate/nlist.c
		if (OSSwapBigToHostInt32(header->magic) == FAT_MAGIC) {				
			// Get our host info
			host_t                 host_self       = mach_host_self();
			unsigned               host_info_count = HOST_BASIC_INFO_COUNT;
			struct host_basic_info host_info_struct;
			kern_return_t          host_res        = host_info(host_self, HOST_BASIC_INFO, (host_info_t)&host_info_struct, &host_info_count);
			mach_port_deallocate(mach_task_self(), host_self);
			if (host_res != KERN_SUCCESS) {
				retval = -2;
				goto cleanup;
			}
			
			/* Read in the fat header */
			const struct fat_header* p_fat          = (const struct fat_header*)m;
			uint32_t                 fat_arch_count = OSSwapBigToHostInt32(p_fat->nfat_arch);
			const struct fat_arch*   arch           = (const struct fat_arch*)(p_fat+1);
			for (uint32_t i = 0; i < fat_arch_count; ++i, ++arch)
				if (OSSwapBigToHostInt32(arch->cputype) == host_info_struct.cpu_type) {
					header = (const struct mach_header*)(m + OSSwapBigToHostInt32(arch->offset));
					goto found_arch;
				}
			retval = -3;
			goto cleanup;
		}
		
found_arch:
		if (header->magic == MH_MAGIC) {
			const struct symtab_command* curcmd = (const struct symtab_command*)(header + 1);
			for (uint32_t i = 0; i < header->ncmds; ++ i) {
				if (curcmd->cmd == LC_SYMTAB) {
					const struct nlist* symbols  = (const struct nlist*)((const char*)header + curcmd->symoff);
					const char*         strings  = (const char*)header + curcmd->stroff;
					for (uint32_t j = 0; j < curcmd->nsyms; ++j, ++symbols) {
						if (strcmp(strings + symbols->n_un.n_strx, "__ZN4dyld15getIndexedImageEj") == 0) {
							dyld_getIndexedImage = (FPTR)symbols->n_value;
							retval = 0;
							goto cleanup;
						}	
					}
					retval = -4;
					goto cleanup;
				} else
					curcmd = (const struct symtab_command*)((const char*)(curcmd) + curcmd->cmdsize);
			} 
			retval = -5;
		} else
			retval = -6;
cleanup:
		munmap(m, f_status.st_size);
		close(f);
	}
	return retval;
}

static int get_image_symbol_count(const struct ImageLoaderMachO* image) {
	if (image == NULL)
		return -2;
	const struct load_command* curcmd = (const struct load_command*)(image->fMachOData + 1);
	for (unsigned i = 0; i < image->fMachOData->ncmds; ++ i) {
		if (curcmd->cmd == LC_SYMTAB)
			return ((const struct symtab_command*)curcmd)->nsyms;
		else
			curcmd = (const struct load_command*)((const char*)(curcmd) + curcmd->cmdsize);
	}
	return -1;
}

/*
 The worst case of this algorithm is O(nml), where
  - n is number of symbols in _filename_
  - m is number of symbols to be found.
  - l is the maximum string length of each symbol.
 This is the case where all symbols are undefined.
 
 If you sort the symbols in "nm -p" order and ensure all symbols are defined,
 the complexity can be reduced to O(n + ml).
 
 (In principle I could define a hash table can further reduce the worst case 
 complexity to amortized O(n+ml), but it wastes too much resource and gain a 
 little since m << n and l is small normally.)
 */

int lookup_function_pointers(const char* filename, ...) {
	if (obtain_dyld() != 0)
		return -1;
	int index = get_image_index(filename);
	if (index < 0)
		return -2;
	const struct ImageLoaderMachO* image = dyld_getIndexedImage(index);
	int symcount = get_image_symbol_count(image);
	if (symcount < 0)
		return -2 + symcount;
	
	int current_index = 0;
	va_list ap;
	va_start(ap, filename);
	const char* requested_symname;
	const char* previously_requested_symname = "";
	
	while ((requested_symname = va_arg(ap, const char*)) != NULL) {
		uint32_t* p_addr = va_arg(ap, uint32_t*);
		
		unsigned requested_symname_len1 = strlen(requested_symname) + 1;
		int scan_direction = memcmp(requested_symname, previously_requested_symname, requested_symname_len1);
		int stop_index = current_index;
		if (scan_direction >= 0) {
			for (; current_index < symcount; ++current_index)
				if (memcmp(image->fStrings+image->fSymbolTable[current_index].n_un.n_strx, requested_symname, requested_symname_len1) == 0)
					goto found;
			for (current_index = 0; current_index < stop_index; ++current_index)
				if (memcmp(image->fStrings+image->fSymbolTable[current_index].n_un.n_strx, requested_symname, requested_symname_len1) == 0)
					goto found;
		} else {
			for (; current_index >= 0; --current_index)
				if (memcmp(image->fStrings+image->fSymbolTable[current_index].n_un.n_strx, requested_symname, requested_symname_len1) == 0)
					goto found;
			for (current_index = symcount-1; current_index > stop_index; --current_index)
				if (memcmp(image->fStrings+image->fSymbolTable[current_index].n_un.n_strx, requested_symname, requested_symname_len1) == 0)
					goto found;
		}
		
		*p_addr = 0;
		continue;
		
found:
		*p_addr = image->fSymbolTable[current_index].n_value + image->fSlide;
		previously_requested_symname = requested_symname;
	}
	return 0;
}

//------------------------------------------------------------------------------

#pragma push_macro("NDEBUG")
#define NDEBUG 1
#include <assert.h>
#pragma pop_macro("NDEBUG")
#include <CoreFoundation/CFString.h>
#include <sys/time.h>
#include <stdio.h>
#include <objc/runtime.h>
#include <objc/message.h>

extern void* NSPushAutoreleasePool(unsigned capacity);
extern void NSPopAutoreleasePool(void* poolObject);
extern int __fdnlist(int fd, struct nlist *list);
// int $__fdnlist(int fd, struct nlist *list);
// void MSHookFunction(void *symbol, void *replace, void **result);

int main() {
	void* pool = NSPushAutoreleasePool(0);
	
	bool (*KBCharIsPunctuation)(wchar_t c) = NULL;
	id UIDevice = objc_getClass("UIDevice");
	void* (*currentDevice)(id uidevice_class) = NULL;
	CFStringRef (*systemVersion)(void* uidevice_object) = NULL;
	void* (*CA_Render_Object_ref)  (void*) = NULL;
	void  (*CA_Render_Object_unref)(void*) = NULL;
	unsigned (*CA_Render_Object_refcount)(void*) = NULL;
	bool (*x_pointer_compare)(void*, void*) = NULL;
	uint32_t blah = 1;
	
	struct timeval start_time, end_time, diff_time;
	
//#if USE_SAURIK_MS_FUNCTION
//	MSHookFunction(&__fdnlist, &$__fdnlist, NULL);
//#endif
	
	gettimeofday(&start_time, NULL);
	
#if USE_KENNYTM_DIRECT_FUNCTION
	// C function & ObjC objects
	// (If possible, sort the objects to seek in "nm -p" order.)
	lookup_function_pointers("UIKit",
							 "+[UIDevice currentDevice]", &currentDevice,
							 "-[UIDevice systemVersion]", &systemVersion,
							 "xxx_definitely_won't_found_this", &blah,
							 "_KBCharIsPunctuation", &KBCharIsPunctuation,
							 0);
	
	// C++ function
	lookup_function_pointers("QuartzCore",
							 "__ZN2CA6Render6Object5unrefEv",     &CA_Render_Object_unref,
							 "__ZNK2CA6Render6Object3refEv",      &CA_Render_Object_ref,
							 "__ZNK2CA6Render6Object8refcountEv", &CA_Render_Object_refcount,
							 "_x_pointer_compare",                &x_pointer_compare,
							 0);
#else
	// saurik's re-implementation seems not able the following cases:
	//  - undefined symbols
	//  - obj-c symbols
	//  - out-of-order symbols
	// therefore, statistics cannot be obtained.
	
	struct nlist symbols[5];
	memset(symbols, 0, sizeof(symbols));
	symbols[0].n_un.n_name = "+[UIDevice currentDevice]";
	symbols[1].n_un.n_name = "-[UIDevice systemVersion]";
	symbols[2].n_un.n_name = "xxx_definitely_won't_found_this";
	symbols[3].n_un.n_name = "_KBCharIsPunctuation";
	nlist("/System/Library/Frameworks/UIKit.framework/UIKit", symbols);
	currentDevice = (void*)symbols[0].n_value;
	systemVersion = (void*)symbols[1].n_value;
	blah = symbols[2].n_value;
	KBCharIsPunctuation = (void*)symbols[0].n_value;
	
	memset(symbols, 0, sizeof(symbols));
	symbols[0].n_un.n_name = "__ZN2CA6Render6Object5unrefEv";
	symbols[1].n_un.n_name = "__ZNK2CA6Render6Object3refEv";
	symbols[2].n_un.n_name = "__ZNK2CA6Render6Object8refcountEv";
	symbols[3].n_un.n_name = "_x_pointer_compare";
	nlist("/System/Library/Frameworks/QuartzCore.framework/QuartzCore", symbols);
	CA_Render_Object_unref = (void*)symbols[0].n_value;
	CA_Render_Object_ref = (void*)symbols[1].n_value;
	CA_Render_Object_refcount = (void*)symbols[2].n_value;
	x_pointer_compare = (void*)symbols[3].n_value;
	
#endif
	
	gettimeofday(&end_time, NULL);
	timersub(&end_time, &start_time, &diff_time);
	
	printf("Time taken to fetch 8 symbols from UIKit and QuartzCore = %d.%06ds.\n", diff_time.tv_sec, diff_time.tv_usec);
	
	assert( blah == 0 );
	assert( KBCharIsPunctuation != NULL );
	assert( KBCharIsPunctuation(',') && !KBCharIsPunctuation('A') );
	
	assert( UIDevice != NULL && currentDevice != NULL && systemVersion != NULL );
	CFStringRef sysVers = systemVersion(currentDevice(UIDevice));
	
	CFShow(sysVers);
	bool is2_X = CFStringHasPrefix(sysVers, CFSTR("2."));
	
	assert( x_pointer_compare != NULL );
	assert( x_pointer_compare((void*)443, (void*)3442) != 0 );
	assert( x_pointer_compare((void*)4490, (void*)4490) == 0 );
	
	if (is2_X) {
		// these 3 functions do not exist until 3.x
		assert( CA_Render_Object_ref == NULL && CA_Render_Object_unref == NULL && CA_Render_Object_refcount == NULL );
	} else {
		assert( CA_Render_Object_ref != NULL && CA_Render_Object_unref != NULL && CA_Render_Object_refcount != NULL );
		void* renderObject = objc_msgSend(objc_msgSend(objc_getClass("CATransition"), sel_getUid("animation")), sel_getUid("CA_copyRenderValue"));
		unsigned initRefCount = CA_Render_Object_refcount(renderObject);
		assert( renderObject == CA_Render_Object_ref(renderObject) );
		assert( initRefCount+1 == CA_Render_Object_refcount(renderObject) );
		CA_Render_Object_unref(renderObject);
		assert( initRefCount == CA_Render_Object_refcount(renderObject) );
		CA_Render_Object_unref(renderObject);	// cleanup to prevent leakage.
	}
	
	NSPopAutoreleasePool(pool);
	
	return 0;
}