-
Notifications
You must be signed in to change notification settings - Fork 104
/
hook.mm
1194 lines (1044 loc) · 34.1 KB
/
hook.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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// The MIT License (MIT)
//
// Copyright (c) 2018 Steven Michaud
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// Template for a hook 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, including
// ones that make use of Apple's CoreSymbolication framework (which though
// undocumented is heavily used by Apple utilities such as atos, ReportCrash,
// crashreporterd and dtrace). Particularly useful are LogWithFormat() and
// PrintStackTrace().
//
// Once the hook library is built, use it as follows:
//
// A) From a Terminal prompt:
// 1) HC_INSERT_LIBRARY=/full/path/to/hook.dylib /path/to/application
//
// B) From gdb:
// 1) set HC_INSERT_LIBRARY /full/path/to/hook.dylib
// 2) run
//
// C) From lldb:
// 1) env HC_INSERT_LIBRARY=/full/path/to/hook.dylib
// 2) run
#include <asl.h>
#include <dlfcn.h>
#include <fcntl.h>
#include <pthread.h>
#include <libproc.h>
#include <stdarg.h>
#include <time.h>
#import <Cocoa/Cocoa.h>
#import <Carbon/Carbon.h>
#import <objc/Object.h>
extern "C" {
#include <mach-o/getsect.h>
}
#include <mach-o/dyld.h>
#include <mach-o/dyld_images.h>
#include <mach-o/nlist.h>
#include <mach/vm_map.h>
#include <libgen.h>
#include <execinfo.h>
pthread_t gMainThreadID = 0;
bool IsMainThread()
{
return (!gMainThreadID || (gMainThreadID == pthread_self()));
}
void CreateGlobalSymbolicator();
bool sGlobalInitDone = false;
void basic_init()
{
if (!sGlobalInitDone) {
gMainThreadID = pthread_self();
CreateGlobalSymbolicator();
sGlobalInitDone = true;
}
}
bool sCFInitialized = false;
void (*__CFInitialize_caller)() = NULL;
static void Hooked___CFInitialize()
{
__CFInitialize_caller();
if (!sCFInitialized) {
basic_init();
}
sCFInitialized = true;
}
bool CanUseCF()
{
return sCFInitialized;
}
#define MAC_OS_X_VERSION_10_9_HEX 0x00000A90
#define MAC_OS_X_VERSION_10_10_HEX 0x00000AA0
#define MAC_OS_X_VERSION_10_11_HEX 0x00000AB0
#define MAC_OS_X_VERSION_10_12_HEX 0x00000AC0
#define MAC_OS_X_VERSION_10_13_HEX 0x00000AD0
#define MAC_OS_X_VERSION_10_14_HEX 0x00000AE0
char gOSVersionString[PATH_MAX] = {0};
int32_t OSX_Version()
{
if (!CanUseCF()) {
return 0;
}
static int32_t version = -1;
if (version != -1) {
return version;
}
CFURLRef url =
CFURLCreateWithString(kCFAllocatorDefault,
CFSTR("file:///System/Library/CoreServices/SystemVersion.plist"),
NULL);
CFReadStreamRef stream =
CFReadStreamCreateWithFile(kCFAllocatorDefault, url);
CFReadStreamOpen(stream);
CFDictionaryRef sysVersionPlist = (CFDictionaryRef)
CFPropertyListCreateWithStream(kCFAllocatorDefault,
stream, 0, kCFPropertyListImmutable,
NULL, NULL);
CFReadStreamClose(stream);
CFRelease(stream);
CFRelease(url);
CFStringRef versionString = (CFStringRef)
CFDictionaryGetValue(sysVersionPlist, CFSTR("ProductVersion"));
CFStringGetCString(versionString, gOSVersionString,
sizeof(gOSVersionString), kCFStringEncodingUTF8);
CFArrayRef versions =
CFStringCreateArrayBySeparatingStrings(kCFAllocatorDefault,
versionString, CFSTR("."));
CFIndex count = CFArrayGetCount(versions);
version = 0;
for (int i = 0; i < count; ++i) {
CFStringRef component = (CFStringRef) CFArrayGetValueAtIndex(versions, i);
int value = CFStringGetIntValue(component);
version += (value << ((2 - i) * 4));
}
CFRelease(sysVersionPlist);
CFRelease(versions);
return version;
}
bool OSX_Mavericks()
{
return ((OSX_Version() & 0xFFF0) == MAC_OS_X_VERSION_10_9_HEX);
}
bool OSX_Yosemite()
{
return ((OSX_Version() & 0xFFF0) == MAC_OS_X_VERSION_10_10_HEX);
}
bool OSX_ElCapitan()
{
return ((OSX_Version() & 0xFFF0) == MAC_OS_X_VERSION_10_11_HEX);
}
bool macOS_Sierra()
{
return ((OSX_Version() & 0xFFF0) == MAC_OS_X_VERSION_10_12_HEX);
}
bool macOS_HighSierra()
{
return ((OSX_Version() & 0xFFF0) == MAC_OS_X_VERSION_10_13_HEX);
}
bool macOS_Mojave()
{
return ((OSX_Version() & 0xFFF0) == MAC_OS_X_VERSION_10_14_HEX);
}
class nsAutoreleasePool {
public:
nsAutoreleasePool()
{
mLocalPool = [[NSAutoreleasePool alloc] init];
}
~nsAutoreleasePool()
{
[mLocalPool release];
}
private:
NSAutoreleasePool *mLocalPool;
};
typedef struct _CSTypeRef {
unsigned long type;
void *contents;
} CSTypeRef;
static CSTypeRef initializer = {0};
const char *GetOwnerName(void *address, CSTypeRef owner = initializer);
const char *GetAddressString(void *address, CSTypeRef owner = initializer);
void PrintAddress(void *address, CSTypeRef symbolicator = initializer);
void PrintStackTrace();
BOOL SwizzleMethods(Class aClass, SEL orgMethod, SEL posedMethod, BOOL classMethods);
char gProcPath[PROC_PIDPATHINFO_MAXSIZE] = {0};
static void MaybeGetProcPath()
{
if (gProcPath[0]) {
return;
}
proc_pidpath(getpid(), gProcPath, sizeof(gProcPath) - 1);
}
static void GetThreadName(char *name, size_t size)
{
pthread_getname_np(pthread_self(), name, size);
}
// Though Macs haven't included a serial port for ages, macOS and OSX still
// support them. Many kinds of VM software allow you to add a serial port to
// their virtual machines. When you do this, /dev/tty.serial1 and
// /dev/cu.serial1 appear on reboot. In VMware Fusion, everything written to
// such a serial port shows up in a file on the virtual machine's host.
//
// Note that macOS/OSX supports serial ports in user-mode and the kernel, but
// not in both at the same time. You can make the kernel send output from
// kprintf() to a serial port by doing 'nvram boot-args="debug=0x8"', then
// rebooting. But this makes the kernel "capture" the serial port -- it's no
// longer available to user-mode code, and drivers for it no longer show up in
// the /dev directory.
bool g_serial1_checked = false;
int g_serial1 = -1;
FILE *g_serial1_FILE = NULL;
static void LogWithFormatV(bool decorate, const char *format, va_list args)
{
MaybeGetProcPath();
if (!format || !format[0]) {
return;
}
char *message;
if (CanUseCF()) {
CFStringRef formatCFSTR =
CFStringCreateWithCString(kCFAllocatorDefault, format,
kCFStringEncodingUTF8);
CFStringRef messageCFSTR =
CFStringCreateWithFormatAndArguments(kCFAllocatorDefault, NULL,
formatCFSTR, args);
CFRelease(formatCFSTR);
int length =
CFStringGetMaximumSizeForEncoding(CFStringGetLength(messageCFSTR),
kCFStringEncodingUTF8);
message = (char *) calloc(length + 1, 1);
CFStringGetCString(messageCFSTR, message, length, kCFStringEncodingUTF8);
CFRelease(messageCFSTR);
} else {
vasprintf(&message, format, args);
}
char *finished = (char *) calloc(strlen(message) + 1024, 1);
char timestamp[30] = {0};
if (CanUseCF()) {
const time_t currentTime = time(NULL);
ctime_r(¤tTime, timestamp);
timestamp[strlen(timestamp) - 1] = 0;
}
if (decorate) {
char threadName[PROC_PIDPATHINFO_MAXSIZE] = {0};
GetThreadName(threadName, sizeof(threadName) - 1);
if (CanUseCF()) {
sprintf(finished, "(%s) %s[%u] %s[%p] %s\n",
timestamp, gProcPath, getpid(), threadName, pthread_self(), message);
} else {
sprintf(finished, "%s[%u] %s[%p] %s\n",
gProcPath, getpid(), threadName, pthread_self(), message);
}
} else {
sprintf(finished, "%s\n", message);
}
free(message);
char stdout_path[PATH_MAX] = {0};
fcntl(STDOUT_FILENO, F_GETPATH, stdout_path);
if (!strcmp("/dev/console", stdout_path) ||
!strcmp("/dev/null", stdout_path))
{
if (CanUseCF()) {
aslclient asl = asl_open(NULL, "com.apple.console", ASL_OPT_NO_REMOTE);
aslmsg msg = asl_new(ASL_TYPE_MSG);
asl_set(msg, ASL_KEY_LEVEL, "3"); // kCFLogLevelError
asl_set(msg, ASL_KEY_MSG, finished);
asl_send(asl, msg);
asl_free(msg);
asl_close(asl);
} else {
if (!g_serial1_checked) {
g_serial1_checked = true;
g_serial1 =
open("/dev/tty.serial1", O_WRONLY | O_NONBLOCK | O_NOCTTY);
if (g_serial1 >= 0) {
g_serial1_FILE = fdopen(g_serial1, "w");
}
}
if (g_serial1_FILE) {
fputs(finished, g_serial1_FILE);
}
}
} else {
fputs(finished, stdout);
}
#ifdef DEBUG_STDOUT
struct stat stdout_stat;
fstat(STDOUT_FILENO, &stdout_stat);
char *stdout_info = (char *) calloc(4096, 1);
sprintf(stdout_info, "stdout: pid \'%i\', path \"%s\", st_dev \'%i\', st_mode \'0x%x\', st_nlink \'%i\', st_ino \'%lli\', st_uid \'%i\', st_gid \'%i\', st_rdev \'%i\', st_size \'%lli\', st_blocks \'%lli\', st_blksize \'%i\', st_flags \'0x%x\', st_gen \'%i\'\n",
getpid(), stdout_path, stdout_stat.st_dev, stdout_stat.st_mode, stdout_stat.st_nlink,
stdout_stat.st_ino, stdout_stat.st_uid, stdout_stat.st_gid, stdout_stat.st_rdev,
stdout_stat.st_size, stdout_stat.st_blocks, stdout_stat.st_blksize,
stdout_stat.st_flags, stdout_stat.st_gen);
if (CanUseCF()) {
aslclient asl = asl_open(NULL, "com.apple.console", ASL_OPT_NO_REMOTE);
aslmsg msg = asl_new(ASL_TYPE_MSG);
asl_set(msg, ASL_KEY_LEVEL, "3"); // kCFLogLevelError
asl_set(msg, ASL_KEY_MSG, stdout_info);
asl_send(asl, msg);
asl_free(msg);
asl_close(asl);
} else {
if (!g_serial1_checked) {
g_serial1_checked = true;
g_serial1 =
open("/dev/tty.serial1", O_WRONLY | O_NONBLOCK | O_NOCTTY);
if (g_serial1 >= 0) {
g_serial1_FILE = fdopen(g_serial1, "w");
}
}
if (g_serial1_FILE) {
fputs(stdout_info, g_serial1_FILE);
}
}
free(stdout_info);
#endif
free(finished);
}
static void LogWithFormat(bool decorate, const char *format, ...)
{
va_list args;
va_start(args, format);
LogWithFormatV(decorate, format, args);
va_end(args);
}
extern "C" void hooklib_LogWithFormatV(bool decorate, const char *format, va_list args)
{
LogWithFormatV(decorate, format, args);
}
extern "C" void hooklib_PrintStackTrace()
{
PrintStackTrace();
}
const struct dyld_all_image_infos *(*_dyld_get_all_image_infos)() = NULL;
bool s_dyld_get_all_image_infos_initialized = false;
// Bit in mach_header.flags that indicates whether or not the (dylib) module
// is in the shared cache.
#define MH_SHAREDCACHE 0x80000000
// Helper method for GetModuleHeaderAndSlide() below.
static
#ifdef __LP64__
uintptr_t GetImageSlide(const struct mach_header_64 *mh)
#else
uintptr_t GetImageSlide(const struct mach_header *mh)
#endif
{
if (!mh) {
return 0;
}
uintptr_t retval = 0;
if (_dyld_get_all_image_infos && ((mh->flags & MH_SHAREDCACHE) != 0)) {
const struct dyld_all_image_infos *info = _dyld_get_all_image_infos();
if (info) {
retval = info->sharedCacheSlide;
}
return retval;
}
uint32_t numCommands = mh->ncmds;
#ifdef __LP64__
const struct segment_command_64 *aCommand = (struct segment_command_64 *)
((uintptr_t)mh + sizeof(struct mach_header_64));
#else
const struct segment_command *aCommand = (struct segment_command *)
((uintptr_t)mh + sizeof(struct mach_header));
#endif
for (uint32_t i = 0; i < numCommands; ++i) {
#ifdef __LP64__
if (aCommand->cmd != LC_SEGMENT_64)
#else
if (aCommand->cmd != LC_SEGMENT)
#endif
{
break;
}
if (!aCommand->fileoff && aCommand->filesize) {
retval = (uintptr_t) mh - aCommand->vmaddr;
break;
}
aCommand =
#ifdef __LP64__
(struct segment_command_64 *)
#else
(struct segment_command *)
#endif
((uintptr_t)aCommand + aCommand->cmdsize);
}
return retval;
}
// Helper method for module_dysym() below.
static
void GetModuleHeaderAndSlide(const char *moduleName,
#ifdef __LP64__
const struct mach_header_64 **pMh,
#else
const struct mach_header **pMh,
#endif
intptr_t *pVmaddrSlide)
{
if (pMh) {
*pMh = NULL;
}
if (pVmaddrSlide) {
*pVmaddrSlide = 0;
}
if (!moduleName) {
return;
}
char basename_local[PATH_MAX];
strncpy(basename_local, basename((char *)moduleName),
sizeof(basename_local));
// If moduleName's base name is "dyld", we take it to mean the copy of dyld
// that's present in every Mach executable.
if (_dyld_get_all_image_infos && (strcmp(basename_local, "dyld") == 0)) {
const struct dyld_all_image_infos *info = _dyld_get_all_image_infos();
if (!info || !info->dyldImageLoadAddress) {
return;
}
if (pMh) {
*pMh =
#ifdef __LP64__
(const struct mach_header_64 *)
#endif
info->dyldImageLoadAddress;
}
if (pVmaddrSlide) {
*pVmaddrSlide = GetImageSlide(
#ifdef __LP64__
(const struct mach_header_64 *)
#endif
info->dyldImageLoadAddress);
}
return;
}
bool moduleNameIsBasename = (strcmp(basename_local, moduleName) == 0);
char moduleName_local[PATH_MAX] = {0};
if (moduleNameIsBasename) {
strncpy(moduleName_local, moduleName, sizeof(moduleName_local));
} else {
// Get the canonical path for moduleName (which may be a symlink or
// otherwise non-canonical).
int fd = open(moduleName, O_RDONLY);
if (fd > 0) {
if (fcntl(fd, F_GETPATH, moduleName_local) == -1) {
strncpy(moduleName_local, moduleName, sizeof(moduleName_local));
}
close(fd);
} else {
strncpy(moduleName_local, moduleName, sizeof(moduleName_local));
}
}
for (uint32_t i = 0; i < _dyld_image_count(); ++i) {
const char *name = _dyld_get_image_name(i);
bool match = false;
if (moduleNameIsBasename) {
match = (strstr(basename((char *)name), moduleName_local) != NULL);
} else {
match = (strstr(name, moduleName_local) != NULL);
}
if (match) {
if (pMh) {
*pMh =
#ifdef __LP64__
(const struct mach_header_64 *)
#endif
_dyld_get_image_header(i);
}
if (pVmaddrSlide) {
*pVmaddrSlide = _dyld_get_image_vmaddr_slide(i);
}
break;
}
}
}
// Helper method for module_dysym() below.
static const
#ifdef __LP64__
struct segment_command_64 *
GetSegment(const struct mach_header_64* mh,
#else
struct segment_command *
GetSegment(const struct mach_header* mh,
#endif
const char *segname,
uint32_t *numFollowingCommands)
{
if (numFollowingCommands) {
*numFollowingCommands = 0;
}
uint32_t numCommands = mh->ncmds;
#ifdef __LP64__
const struct segment_command_64 *aCommand = (struct segment_command_64 *)
((uintptr_t)mh + sizeof(struct mach_header_64));
#else
const struct segment_command *aCommand = (struct segment_command *)
((uintptr_t)mh + sizeof(struct mach_header));
#endif
for (uint32_t i = 1; i <= numCommands; ++i) {
#ifdef __LP64__
if (aCommand->cmd != LC_SEGMENT_64)
#else
if (aCommand->cmd != LC_SEGMENT)
#endif
{
break;
}
if (strcmp(segname, aCommand->segname) == 0) {
if (numFollowingCommands) {
*numFollowingCommands = numCommands-i;
}
return aCommand;
}
aCommand =
#ifdef __LP64__
(struct segment_command_64 *)
#else
(struct segment_command *)
#endif
((uintptr_t)aCommand + aCommand->cmdsize);
}
return NULL;
}
// A variant of dlsym() that can find non-exported (non-public) symbols.
// Unlike with dlsym() and friends, 'symbol' should be specified exactly as it
// appears in the symbol table (and the output of programs like 'nm'). In
// other words, 'symbol' should (most of the time) be prefixed by an "extra"
// underscore. The reason is that some symbols (especially non-public ones)
// don't have any underscore prefix, even in the symbol table.
extern "C" void *module_dlsym(const char *module_name, const char *symbol)
{
if (!s_dyld_get_all_image_infos_initialized) {
s_dyld_get_all_image_infos_initialized = true;
_dyld_get_all_image_infos = (const struct dyld_all_image_infos *(*)())
module_dlsym("/usr/lib/system/libdyld.dylib", "__dyld_get_all_image_infos");
}
#ifdef __LP64__
const struct mach_header_64 *mh = NULL;
#else
const struct mach_header *mh = NULL;
#endif
intptr_t vmaddr_slide = 0;
GetModuleHeaderAndSlide(module_name, &mh, &vmaddr_slide);
if (!mh) {
return NULL;
}
uint32_t numFollowingCommands = 0;
#ifdef __LP64__
const struct segment_command_64 *linkeditSegment =
#else
const struct segment_command *linkeditSegment =
#endif
GetSegment(mh, "__LINKEDIT", &numFollowingCommands);
if (!linkeditSegment) {
return NULL;
}
uintptr_t fileoffIncrement =
linkeditSegment->vmaddr - linkeditSegment->fileoff;
struct symtab_command *symtab = (struct symtab_command *)
((uintptr_t)linkeditSegment + linkeditSegment->cmdsize);
for (uint32_t i = 1;; ++i) {
if (symtab->cmd == LC_SYMTAB) {
break;
}
if (i == numFollowingCommands) {
return NULL;
}
symtab = (struct symtab_command *)
((uintptr_t)symtab + symtab->cmdsize);
}
uintptr_t symbolTableOffset =
symtab->symoff + fileoffIncrement + vmaddr_slide;
uintptr_t stringTableOffset =
symtab->stroff + fileoffIncrement + vmaddr_slide;
struct dysymtab_command *dysymtab = (struct dysymtab_command *)
((uintptr_t)symtab + symtab->cmdsize);
if (dysymtab->cmd != LC_DYSYMTAB) {
return NULL;
}
void *retval = NULL;
for (int i = 1; i <= 2; ++i) {
uint32_t index;
uint32_t count;
if (i == 1) {
index = dysymtab->ilocalsym;
count = index + dysymtab->nlocalsym;
} else {
index = dysymtab->iextdefsym;
count = index + dysymtab->nextdefsym;
}
for (uint32_t j = index; j < count; ++j) {
#ifdef __LP64__
struct nlist_64 *symbolTableItem = (struct nlist_64 *)
(symbolTableOffset + j * sizeof(struct nlist_64));
#else
struct nlist *symbolTableItem = (struct nlist *)
(symbolTableOffset + j * sizeof(struct nlist));
#endif
uint8_t type = symbolTableItem->n_type;
if ((type & N_STAB) || ((type & N_TYPE) != N_SECT)) {
continue;
}
uint8_t sect = symbolTableItem->n_sect;
if (!sect) {
continue;
}
const char *stringTableItem = (char *)
(stringTableOffset + symbolTableItem->n_un.n_strx);
if (strcmp(symbol, stringTableItem)) {
continue;
}
retval = (void *) (symbolTableItem->n_value + vmaddr_slide);
break;
}
}
return retval;
}
// dladdr() is normally used from libdyld.dylib. But this isn't safe before
// our execution environment is fully initialized. So instead we use it from
// the copy of dyld loaded in every Mach executable, which has no external
// dependencies.
int (*dyld_dladdr_caller)(const void *addr, Dl_info *info) = NULL;
int dyld_dladdr(const void *addr, Dl_info *info)
{
if (!dyld_dladdr_caller) {
dyld_dladdr_caller = (int (*)(const void*, Dl_info *))
module_dlsym("dyld", "_dladdr");
if (!dyld_dladdr_caller) {
return 0;
}
}
return dyld_dladdr_caller(addr, info);
}
// Call this from a hook to get the filename of the module from which the hook
// was called -- which of course is also the module from which the original
// method was called.
const char *GetCallerOwnerName()
{
static char holder[1024] = {0};
const char *ownerName = "";
Dl_info addressInfo = {0};
void **addresses = (void **) calloc(3, sizeof(void *));
if (addresses) {
int count = backtrace(addresses, 3);
if (count == 3) {
if (dyld_dladdr(addresses[2], &addressInfo)) {
ownerName = basename((char *)addressInfo.dli_fname);
}
}
free(addresses);
}
strncpy(holder, ownerName, sizeof(holder));
return holder;
}
// Reset a patch hook after it's been unset (as it was called). Not always
// required -- most patch hooks don't get unset when called. But using it
// when not required does no harm. Note that, as of HookCase version 2.1, we
// changed which interrupt is used here -- from 0x22 to 0x32.
void reset_hook(void *hook)
{
__asm__ ("int %0" :: "N" (0x32));
}
class loadHandler
{
public:
loadHandler();
~loadHandler();
};
loadHandler::loadHandler()
{
basic_init();
#if (0)
LogWithFormat(true, "Hook.mm: loadHandler()");
PrintStackTrace();
#endif
}
loadHandler::~loadHandler()
{
if (g_serial1_FILE) {
fclose(g_serial1_FILE);
}
if (g_serial1) {
close(g_serial1);
}
}
loadHandler handler = loadHandler();
static BOOL gMethodsSwizzled = NO;
static void InitSwizzling()
{
if (!gMethodsSwizzled) {
#if (0)
LogWithFormat(true, "Hook.mm: InitSwizzling()");
PrintStackTrace();
#endif
gMethodsSwizzled = YES;
// Swizzle methods here
#if (0)
Class ExampleClass = ::NSClassFromString(@"Example");
SwizzleMethods(ExampleClass, @selector(doSomethingWith:),
@selector(Example_doSomethingWith:), NO);
#endif
}
}
extern "C" void *NSPushAutoreleasePool();
static void *Hooked_NSPushAutoreleasePool()
{
void *retval = NSPushAutoreleasePool();
if (IsMainThread()) {
InitSwizzling();
}
return retval;
}
#if (0)
// If the PATCH_FUNCTION macro is used below, this will be set to the correct
// value by the the HookCase extension.
int (*patch_example_caller)(char *arg) = NULL;
static int Hooked_patch_example(char *arg)
{
int retval = patch_example_caller(arg);
LogWithFormat(true, "Hook.mm: example(): arg \"%s\", returning \'%i\'", arg, retval);
PrintStackTrace();
// Not always required, but using it when not required does no harm.
reset_hook(reinterpret_cast<void*>(Hooked_example));
return retval;
}
// An example of setting a patch hook at a function's numerical address. The
// hook function's name must start with "sub_" and finish with its address (in
// the module where it's located) in hexadecimal (base 16) notation. To hook
// a function whose actual name (in the symbol table) follows this convention,
// set the HC_NO_NUMERICAL_ADDRS environment variable.
int (*sub_123abc_caller)(char *arg) = NULL;
static int Hooked_sub_123abc(char *arg)
{
int retval = sub_123abc_caller(arg);
LogWithFormat(true, "Hook.mm: sub_123abc(): arg \"%s\", returning \'%i\'", arg, retval);
PrintStackTrace();
// Not always required, but using it when not required does no harm.
reset_hook(reinterpret_cast<void*>(Hooked_sub_123abc));
return retval;
}
extern "C" int interpose_example(char *arg);
static int Hooked_interpose_example(char *arg)
{
int retval = interpose_example(arg);
LogWithFormat(true, "Hook.mm: example(): arg \"%s\", returning \'%i\'", arg, retval);
PrintStackTrace();
return retval;
}
@interface NSObject (ExampleMethodSwizzling)
- (id)Example_doSomethingWith:(id)whatever;
@end
@implementation NSObject (ExampleMethodSwizzling)
- (id)Example_doSomethingWith:(id)whatever
{
id retval = [self Example_doSomethingWith:whatever];
if ([self isKindOfClass:ExampleClass]) {
LogWithFormat(true, "Hook.mm: [Example doSomethingWith:]: self %@, whatever %@, returning %@",
self, whatever, retval);
}
return retval;
}
@end
#endif // #if (0)
// Put other hooked methods and swizzled classes here
#pragma mark -
typedef struct _hook_desc {
const void *hook_function;
union {
// For interpose hooks
const void *orig_function;
// For patch hooks
const void *caller_func_ptr;
};
const char *orig_function_name;
const char *orig_module_name;
} hook_desc;
#define PATCH_FUNCTION(function, module) \
{ reinterpret_cast<const void*>(Hooked_##function), \
reinterpret_cast<const void*>(&function##_caller), \
"_" #function, \
#module }
#define INTERPOSE_FUNCTION(function) \
{ reinterpret_cast<const void*>(Hooked_##function), \
reinterpret_cast<const void*>(function), \
"_" #function, \
"" }
__attribute__((used)) static const hook_desc user_hooks[]
__attribute__((section("__DATA, __hook"))) =
{
INTERPOSE_FUNCTION(NSPushAutoreleasePool),
PATCH_FUNCTION(__CFInitialize, /System/Library/Frameworks/CoreFoundation.framework/CoreFoundation),
};
// What follows are declarations of the CoreSymbolication APIs that we use to
// get stack traces. This is an undocumented, private framework available on
// OS X 10.6 and up. It's used by Apple utilities like atos and ReportCrash.
// Defined above
#if (0)
typedef struct _CSTypeRef {
unsigned long type;
void *contents;
} CSTypeRef;
#endif
typedef struct _CSRange {
unsigned long long location;
unsigned long long length;
} CSRange;
// Defined above
typedef CSTypeRef CSSymbolicatorRef;
typedef CSTypeRef CSSymbolOwnerRef;
typedef CSTypeRef CSSymbolRef;
typedef CSTypeRef CSSourceInfoRef;
typedef unsigned long long CSArchitecture;
#define kCSNow LONG_MAX
extern "C" {
CSSymbolicatorRef CSSymbolicatorCreateWithTaskFlagsAndNotification(task_t task,
uint32_t flags,
uint32_t notification);
CSSymbolicatorRef CSSymbolicatorCreateWithPid(pid_t pid);
CSSymbolicatorRef CSSymbolicatorCreateWithPidFlagsAndNotification(pid_t pid,
uint32_t flags,
uint32_t notification);
CSArchitecture CSSymbolicatorGetArchitecture(CSSymbolicatorRef symbolicator);
CSSymbolOwnerRef CSSymbolicatorGetSymbolOwnerWithAddressAtTime(CSSymbolicatorRef symbolicator,
unsigned long long address,
long time);
const char *CSSymbolOwnerGetName(CSSymbolOwnerRef owner);
unsigned long long CSSymbolOwnerGetBaseAddress(CSSymbolOwnerRef owner);
CSSymbolRef CSSymbolOwnerGetSymbolWithAddress(CSSymbolOwnerRef owner,
unsigned long long address);
CSSourceInfoRef CSSymbolOwnerGetSourceInfoWithAddress(CSSymbolOwnerRef owner,
unsigned long long address);
const char *CSSymbolGetName(CSSymbolRef symbol);
CSRange CSSymbolGetRange(CSSymbolRef symbol);
const char *CSSourceInfoGetFilename(CSSourceInfoRef info);
uint32_t CSSourceInfoGetLineNumber(CSSourceInfoRef info);
CSTypeRef CSRetain(CSTypeRef);
void CSRelease(CSTypeRef);
bool CSIsNull(CSTypeRef);
void CSShow(CSTypeRef);
const char *CSArchitectureGetFamilyName(CSArchitecture);
} // extern "C"
CSSymbolicatorRef gSymbolicator = {0};
void CreateGlobalSymbolicator()
{
if (CSIsNull(gSymbolicator)) {
// 0x40e0000 is the value returned by
// uint32_t CSSymbolicatorGetFlagsForNListOnlyData(void). We don't use
// this method directly because it doesn't exist on OS X 10.6. Unless
// we limit ourselves to NList data, it will take too long to get a
// stack trace where Dwarf debugging info is available (about 15 seconds
// with Firefox).
gSymbolicator =
CSSymbolicatorCreateWithTaskFlagsAndNotification(mach_task_self(), 0x40e0000, 0);
}
}
// Does nothing (and returns 'false') if *symbolicator is already non-null.
// Otherwise tries to set it appropriately. Returns 'true' if the returned
// *symbolicator will need to be released after use (because it isn't the
// global symbolicator).
bool GetSymbolicator(CSSymbolicatorRef *symbolicator)
{
bool retval = false;
if (CSIsNull(*symbolicator)) {
if (!CSIsNull(gSymbolicator)) {
*symbolicator = gSymbolicator;
} else {
// 0x40e0000 is the value returned by
// uint32_t CSSymbolicatorGetFlagsForNListOnlyData(void). We don't use
// this method directly because it doesn't exist on OS X 10.6. Unless
// we limit ourselves to NList data, it will take too long to get a
// stack trace where Dwarf debugging info is available (about 15 seconds
// with Firefox). This means we won't be able to get a CSSourceInfoRef,
// or line number information. Oh well.
*symbolicator =
CSSymbolicatorCreateWithTaskFlagsAndNotification(mach_task_self(), 0x40e0000, 0);
if (!CSIsNull(*symbolicator)) {
retval = true;
}
}
}
return retval;
}