-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathinterpose.mm
465 lines (409 loc) · 13.5 KB
/
interpose.mm
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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
// Template for an interpose library that can be used to hook C/C++ methods
// and/or swizzle Objective-C methods for debugging/reverse-engineering.
//
// A number of methods are provided to be called from your hooks that make use
// of Apple's Symbolication framework (which though undocumented is heavily
// used by Apple utilities such as crashreporterd and dtrace). Particularly
// useful is PrintStackTrace().
//
// Once the interpose library is built, use it as follows:
//
// A) From a Terminal prompt:
// 1) export DYLD_INSERT_LIBRARIES=/full/path/to/interpose.dylib
// 2) /path/to/application
//
// B) From gdb:
// 1) set DYLD_INSERT_LIBRARIES /full/path/to/interpose.dylib
// 2) run
#include <dlfcn.h>
#include <pthread.h>
#include <execinfo.h>
#import <Cocoa/Cocoa.h>
#import <Carbon/Carbon.h>
#import <OpenGL/OpenGL.h>
#import <objc/Object.h>
class nsAutoreleasePool {
public:
nsAutoreleasePool()
{
mLocalPool = [[NSAutoreleasePool alloc] init];
}
~nsAutoreleasePool()
{
[mLocalPool release];
}
private:
NSAutoreleasePool *mLocalPool;
};
char *GetOwnerName(void *address);
char *GetAddressName(void *address);
void PrintAddress(void *address);
void PrintStackTrace(NSArray *addresses = nil);
BOOL SwizzleMethods(Class aClass, SEL orgMethod, SEL posedMethod, BOOL classMethods);
Class gSymbolicatorClass = nil;
static BOOL gSymbolicationLoaded = NO;
static BOOL loadSymbolication()
{
if (gSymbolicationLoaded) {
return YES;
}
// Needed for printing stack traces. Available on OS X 10.5 and up.
if (dlopen("/System/Library/PrivateFrameworks/Symbolication.framework/Symbolication", RTLD_LAZY)) {
gSymbolicationLoaded = YES;
Class VMUDebugMapExtractorClass = ::NSClassFromString(@"VMUDebugMapExtractor");
SwizzleMethods(VMUDebugMapExtractorClass, @selector(debugMapExtractorWithMachOHeader:),
@selector(VMUDebugMapExtractor_debugMapExtractorWithMachOHeader:), YES);
gSymbolicatorClass = ::NSClassFromString(@"VMUSymbolicator");
// Swizzle other methods here
}
return gSymbolicationLoaded;
}
pthread_t gMainThreadID = 0;
bool IsMainThread()
{
return (gMainThreadID == pthread_self());
}
static int Hooked_pthread_once(pthread_once_t *once_control, void (*init_routine)(void))
{
int retval = pthread_once(once_control, init_routine);
if (!gMainThreadID) {
gMainThreadID = pthread_self();
}
return retval;
}
extern "C" void *NSPushAutoreleasePool();
static void *Hooked_NSPushAutoreleasePool()
{
void *retval = NSPushAutoreleasePool();
if (IsMainThread()) {
loadSymbolication();
}
return retval;
}
// Put other hooked methods and swizzled classes here
class ReconfigurationCallbackInfo {
public:
ReconfigurationCallbackInfo(CGDisplayReconfigurationCallBack aCallback,
void *aUserInfo, char *aOwnerName)
{
mCallbackProc = aCallback;
mUserInfo = aUserInfo;
size_t ownerNameLength = strlen(aOwnerName);
mOwnerName = (char *) calloc(ownerNameLength + 2, 1);
if (mOwnerName) {
strcpy(mOwnerName, aOwnerName);
}
}
~ReconfigurationCallbackInfo()
{
free(mOwnerName);
}
CGDisplayReconfigurationCallBack getCallback() { return mCallbackProc; }
void *getUserInfo() { return mUserInfo; }
char *getOwnerName() { return mOwnerName; }
private:
CGDisplayReconfigurationCallBack mCallbackProc;
void *mUserInfo;
char *mOwnerName;
};
Boolean CallbackInfoEqualCallback(const void *value1,
const void *value2)
{
ReconfigurationCallbackInfo *info1 = (ReconfigurationCallbackInfo *) value1;
ReconfigurationCallbackInfo *info2 = (ReconfigurationCallbackInfo *) value2;
return ((info1->getUserInfo() == info2->getUserInfo()) &&
(info1->getCallback() == info2->getCallback()));
}
CFHashCode CallbackInfoHashCallback(const void *value)
{
ReconfigurationCallbackInfo *info = (ReconfigurationCallbackInfo *) value;
CFHashCode retval = (((CFHashCode)info->getUserInfo()) << 1);
retval += (CFHashCode) info->getCallback();
return retval;
}
CFMutableSetRef gCallbackInfo = NULL;
static bool CheckCallbackInfo()
{
if (gCallbackInfo) {
return true;
}
CFSetCallBacks callbacks = {0};
callbacks.equal = CallbackInfoEqualCallback;
callbacks.hash = CallbackInfoHashCallback;
gCallbackInfo = CFSetCreateMutable(kCFAllocatorDefault, 0, &callbacks);
return (gCallbackInfo != NULL);
}
static void ReconfigurationCallback(CGDirectDisplayID display,
CGDisplayChangeSummaryFlags flags,
void *userInfo)
{
ReconfigurationCallbackInfo *info = (ReconfigurationCallbackInfo *) userInfo;
CGDisplayReconfigurationCallBack orgCallback = info->getCallback();
void *orgUserInfo = info->getUserInfo();
char *orgOwnerName = info->getOwnerName();
nsAutoreleasePool localPool;
NSLog(@"ReconfigurationCallback(): display %p, flags %p, userInfo %p, ownerName %s, calling ...",
(void *) display, (void *) flags, orgUserInfo, orgOwnerName);
PrintAddress((void *)orgCallback);
orgCallback(display, flags, orgUserInfo);
}
static CGError Hooked_CGDisplayRegisterReconfigurationCallback(CGDisplayReconfigurationCallBack proc,
void *userInfo)
{
char *ownerName = NULL;
void **addresses = (void **) calloc(2, sizeof(void *));
if (addresses) {
int count = backtrace(addresses, 2);
if (count == 2) {
ownerName = GetOwnerName(addresses[1]);
}
free(addresses);
}
ReconfigurationCallbackInfo *info = new ReconfigurationCallbackInfo(proc, userInfo, ownerName);
bool succeeded = CheckCallbackInfo();
if (succeeded) {
succeeded = !CFSetContainsValue(gCallbackInfo, info);
}
CGError retval;
if (succeeded) {
CFSetAddValue(gCallbackInfo, info);
retval = CGDisplayRegisterReconfigurationCallback(ReconfigurationCallback, info);
} else {
delete info;
retval = CGDisplayRegisterReconfigurationCallback(proc, userInfo);
}
nsAutoreleasePool localPool;
NSLog(@"CGDisplayRegisterReconfigurationCallback(): proc %p, userInfo %p, returning %i, ownerName %s",
proc, userInfo, retval, ownerName);
PrintStackTrace();
return retval;
}
static CGError Hooked_CGDisplayRemoveReconfigurationCallback(CGDisplayReconfigurationCallBack proc,
void *userInfo)
{
CGError retval;
ReconfigurationCallbackInfo info(proc, userInfo, (char *) "");
bool succeeded = CheckCallbackInfo();
if (succeeded) {
succeeded = CFSetContainsValue(gCallbackInfo, &info);
}
if (succeeded) {
ReconfigurationCallbackInfo *orgInfo =
(ReconfigurationCallbackInfo *) CFSetGetValue(gCallbackInfo, &info);
retval = CGDisplayRemoveReconfigurationCallback(ReconfigurationCallback,
orgInfo);
CFSetRemoveValue(gCallbackInfo, orgInfo);
delete orgInfo;
} else {
retval = CGDisplayRemoveReconfigurationCallback(proc, userInfo);
}
nsAutoreleasePool localPool;
NSLog(@"CGDisplayRemoveReconfigurationCallback(): proc %p, userInfo %p, returning %i",
proc, userInfo, retval);
PrintStackTrace();
return retval;
}
extern "C" CGLError CGLUpdateContext(CGLContextObj ctx);
static CGLError Hooked_CGLUpdateContext(CGLContextObj ctx)
{
CGLError retval = CGLUpdateContext(ctx);
nsAutoreleasePool localPool;
bool log = true;
char *ownerName = nil;
void **addresses = (void **) calloc(2, sizeof(void *));
if (addresses) {
int count = backtrace(addresses, 2);
if (count == 2) {
ownerName = GetOwnerName(addresses[1]);
}
free(addresses);
}
if (ownerName && !strcmp(ownerName, "AppKit")) {
log = false;
}
if (log) {
NSLog(@"CGLUpdateContext(): ctx %p, retain count %u, returning %i",
ctx, CGLGetContextRetainCount(ctx), retval);
PrintStackTrace();
}
return retval;
}
#pragma mark -
struct interpose_substitution {
const void* replacement;
const void* original;
};
#define INTERPOSE_FUNCTION(function) \
{ reinterpret_cast<const void*>(Hooked_##function), \
reinterpret_cast<const void*>(function) }
__attribute__((used)) static const interpose_substitution substitutions[]
__attribute__((section("__DATA, __interpose"))) = {
INTERPOSE_FUNCTION(pthread_once),
INTERPOSE_FUNCTION(NSPushAutoreleasePool),
INTERPOSE_FUNCTION(CGDisplayRegisterReconfigurationCallback),
INTERPOSE_FUNCTION(CGDisplayRemoveReconfigurationCallback),
INTERPOSE_FUNCTION(CGLUpdateContext),
};
// What follows are definitions of the Symbolication interfaces we use to get
// stack traces. The Symbolication framework is an undocumented, private
// framework available on OS X 10.5 and up. It's used by Apple utilities
// such as dtrace. http://www.cocoadev.com/index.pl?StackTraces has basic
// information on how to use the Symbolication framework.
@interface VMUAddressRange : NSObject <NSCoding>
{
}
@end
@interface VMUSymbol : VMUAddressRange <NSCopying>
{
}
- (NSString *)name;
- (NSString *)description;
- (id)text;
@end
@interface VMUSymbolOwner : NSObject <NSCopying>
{
}
- (NSString *)name;
@end
// We must override the debugMapExtractorWithMachOHeader method: Otherwise
// the Symbolication framework can take a minute or more to initialize!!
// We don't need the information in the "debug maps" (Dwarf or dsym debugging
// information) to get simple stack traces.
@interface NSObject (VMUDebugMapExtractorMethodSwizzling)
+ (id)VMUDebugMapExtractor_debugMapExtractorWithMachOHeader:(id)machHeader;
@end
@implementation NSObject (VMUDebugMapExtractorMethodSwizzling)
+ (id)VMUDebugMapExtractor_debugMapExtractorWithMachOHeader:(id)machHeader
{
return nil;
}
@end
@interface VMUSymbolicator : NSObject
{
}
+ (VMUSymbolicator *)symbolicatorForPid:(int)pid;
- (VMUSymbol *)symbolForAddress:(unsigned long long)address;
- (VMUSymbolOwner *)symbolOwnerForAddress:(unsigned long long)address;
@end
@interface VMUSymbolicator (PerformanceOptimization)
- (id)symbolOwnerNameForAddress:(unsigned long long)fp8;
@end
char *GetOwnerName(void *address)
{
static char holder[1024] = {0};
if (!loadSymbolication()) {
holder[0] = 0;
return holder;
}
VMUSymbolicator *symbolicator = [gSymbolicatorClass symbolicatorForPid:getpid()];
if (!symbolicator) {
holder[0] = 0;
return holder;
}
VMUSymbol *symbol =
[symbolicator symbolForAddress:(unsigned long long)address];
NSString *ownerName = nil;
if ([symbolicator respondsToSelector:@selector(symbolOwnerNameForAddress:)]) {
ownerName =
[symbolicator symbolOwnerNameForAddress:(unsigned long long)address];
} else {
VMUSymbolOwner *owner =
[symbolicator symbolOwnerForAddress:(unsigned long long)address];
ownerName = [owner name];
}
if (ownerName) {
strcpy(holder, [ownerName UTF8String]);
return holder;
}
holder[0] = 0;
return holder;
}
char *GetAddressName(void *address)
{
static char holder[1024] = {0};
if (!loadSymbolication()) {
holder[0] = 0;
return holder;
}
VMUSymbolicator *symbolicator = [gSymbolicatorClass symbolicatorForPid:getpid()];
if (!symbolicator) {
holder[0] = 0;
return holder;
}
VMUSymbol *symbol =
[symbolicator symbolForAddress:(unsigned long long)address];
if (symbol && [symbol name]) {
strcpy(holder, [[symbol name] UTF8String]);
return holder;
}
holder[0] = 0;
return holder;
}
void PrintAddress(void *address)
{
if (!loadSymbolication()) {
return;
}
VMUSymbolicator *symbolicator = [gSymbolicatorClass symbolicatorForPid:getpid()];
if (!symbolicator) {
return;
}
VMUSymbol *symbol =
[symbolicator symbolForAddress:(unsigned long long)address];
NSString *ownerName = nil;
if ([symbolicator respondsToSelector:@selector(symbolOwnerNameForAddress:)]) {
ownerName =
[symbolicator symbolOwnerNameForAddress:(unsigned long long)address];
} else {
VMUSymbolOwner *owner =
[symbolicator symbolOwnerForAddress:(unsigned long long)address];
ownerName = [owner name];
}
NSLog(@" (%@) %@, %p", ownerName, [symbol name], address);
}
void PrintStackTrace(NSArray *addresses)
{
if (!loadSymbolication()) {
return;
}
VMUSymbolicator *symbolicator = [gSymbolicatorClass symbolicatorForPid:getpid()];
if (!symbolicator) {
return;
}
if (!addresses) {
addresses = [NSThread callStackReturnAddresses];
}
NSUInteger count = [addresses count];
for (NSUInteger i = 0; i < count; ++i) {
NSNumber *item = (NSNumber *) [addresses objectAtIndex:i];
VMUSymbol *symbol =
[symbolicator symbolForAddress:[item unsignedLongLongValue]];
NSString *ownerName = nil;
if ([symbolicator respondsToSelector:@selector(symbolOwnerNameForAddress:)]) {
ownerName =
[symbolicator symbolOwnerNameForAddress:[item unsignedLongLongValue]];
} else {
VMUSymbolOwner *owner =
[symbolicator symbolOwnerForAddress:[item unsignedLongLongValue]];
ownerName = [owner name];
}
NSLog(@" (%@) %@, %p",
ownerName, [symbol name], (void *)[item unsignedLongLongValue]);
}
}
BOOL SwizzleMethods(Class aClass, SEL orgMethod, SEL posedMethod, BOOL classMethods)
{
Method original = nil;
Method posed = nil;
if (classMethods) {
original = class_getClassMethod(aClass, orgMethod);
posed = class_getClassMethod(aClass, posedMethod);
} else {
original = class_getInstanceMethod(aClass, orgMethod);
posed = class_getInstanceMethod(aClass, posedMethod);
}
if (!original || !posed)
return NO;
method_exchangeImplementations(original, posed);
return YES;
}