-
Notifications
You must be signed in to change notification settings - Fork 110
/
hook.mm
2131 lines (1878 loc) · 69.8 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) 2023 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>
#include <termios.h>
#include <xpc/xpc.h>
pthread_t gMainThreadID = 0;
bool IsMainThread()
{
return (!gMainThreadID || (gMainThreadID == pthread_self()));
}
bool sGlobalInitDone = false;
void basic_init()
{
if (!sGlobalInitDone) {
gMainThreadID = pthread_self();
sGlobalInitDone = true;
// Needed for LogWithFormat() to work properly both before and after the
// CoreFoundation framework is initialized.
tzset();
tzsetwall();
}
}
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
#define MAC_OS_X_VERSION_10_15_HEX 0x00000AF0
#define MAC_OS_X_VERSION_11_00_HEX 0x00000B00
#define MAC_OS_X_VERSION_12_00_HEX 0x00000C00
#define MAC_OS_X_VERSION_13_00_HEX 0x00000D00
#define MAC_OS_X_VERSION_14_00_HEX 0x00000E00
#define MAC_OS_X_VERSION_15_00_HEX 0x00000F00
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);
}
bool macOS_Catalina()
{
return ((OSX_Version() & 0xFFF0) == MAC_OS_X_VERSION_10_15_HEX);
}
bool macOS_BigSur()
{
return ((OSX_Version() & 0xFFF0) == MAC_OS_X_VERSION_11_00_HEX);
}
bool macOS_Monterey()
{
return ((OSX_Version() & 0xFFF0) == MAC_OS_X_VERSION_12_00_HEX);
}
bool macOS_Ventura()
{
return ((OSX_Version() & 0xFFF0) == MAC_OS_X_VERSION_13_00_HEX);
}
bool macOS_Sonoma()
{
return ((OSX_Version() & 0xFFF0) == MAC_OS_X_VERSION_14_00_HEX);
}
bool macOS_Sequoia()
{
return ((OSX_Version() & 0xFFF0) == MAC_OS_X_VERSION_15_00_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};
#define STACK_MAX 256
typedef uint64_t callstack_t[STACK_MAX];
const char *GetOwnerName(void *address, CSTypeRef owner = initializer);
const char *GetAddressString(void *address, CSTypeRef owner = initializer);
void PrintAddress(void *address, CSTypeRef symbolicator = initializer);
void PrintCallstack(callstack_t callstack);
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);
}
// It's sometimes useful to find out whether a hook is currently running
// (on the current thread), or if it's been re-entered (and how many times
// it's been re-entered). The following macro offers a safe, comprehensive
// way to do this.
#define GET_SET_IN_FUNCS(name) \
pthread_key_t s_in_##name; \
int32_t s_in_##name##_initialized = 0; \
bool get_in_##name() \
{ \
if (!s_in_##name##_initialized) { \
OSAtomicIncrement32(&s_in_##name##_initialized); \
pthread_key_create(&s_in_##name, NULL); \
} \
long value = (long) \
pthread_getspecific(s_in_##name); \
return (value > 0); \
} \
long get_in_##name##_count() \
{ \
if (!s_in_##name##_initialized) { \
OSAtomicIncrement32(&s_in_##name##_initialized); \
pthread_key_create(&s_in_##name, NULL); \
} \
return (long) pthread_getspecific(s_in_##name); \
} \
void set_in_##name(bool flag) \
{ \
if (!s_in_##name##_initialized) { \
OSAtomicIncrement32(&s_in_##name##_initialized); \
pthread_key_create(&s_in_##name, NULL); \
} \
long value = (long) \
pthread_getspecific(s_in_##name); \
if (flag) { \
++value; \
} else { \
--value; \
} \
pthread_setspecific(s_in_##name, (void *) value); \
}
GET_SET_IN_FUNCS(LogWithFormatV)
// 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;
// It's always been difficult to log output from hook libraries -- especially
// from secondary processes. STDOUT and STDERR are often redirected to
// /dev/null. And sometimes Apple even blocks system log output. As mentioned
// above, a hardware serial port can be used for output. But it's tricky to
// use if you're not running macOS in a VM. It's easier to create a virtual
// serial port inside macOS and use that for logging output. You can do this
// with https://github.com/steven-michaud/PySerialPortLogger. Install it and
// run 'serialportlogger'. Observe the name of its virtual serial port, make
// the definition of VIRTUAL_SERIAL_PORT match it, then uncomment it. If
// you're loading your hook library from the command line, it's also possible
// to redirect logging output (all of it) to your current Terminal session.
// Run the "tty" command in it to find its tty name.
//#define VIRTUAL_SERIAL_PORT "/dev/ttys003"
bool g_virtual_serial_checked = false;
int g_virtual_serial = -1;
FILE *g_virtual_serial_FILE = NULL;
// TTY pipes are *very* finicky. They don't like it when you write too much
// data all at once, or perform sequences of writes too quickly. Doing either
// will make fputs() return EAGAIN ("Resource temporarily unavailable"). To
// avoid this, we break our data into reasonable sized chunks, and do
// tcdrain() after each call to fputs(), to wait until each chunk of data has
// been written to the TTY. _PC_PIPE_BUF is the maximum number of bytes that
// can be written atomically to our TTY pipe. Note that breaking up a UTF-8
// string like this can make parts of it invalid. The software that implements
// our virtual serial port needs to suppress formatting errors to avoid
// trouble from this.
void tty_fputs(const char *s, FILE *stream)
{
if (!s || !stream) {
return;
}
long pipe_max = fpathconf(fileno(stream), _PC_PIPE_BUF);
if (pipe_max == -1) {
fputs(s, stream);
tcdrain(fileno(stream));
return;
}
char *block = (char *) malloc(pipe_max + 1);
if (!block) {
return;
}
size_t total_length = strlen(s);
size_t to_do = pipe_max;
if (to_do > total_length) {
to_do = total_length;
}
for (size_t done = 0; done < total_length; done += to_do) {
if (to_do > total_length - done) {
to_do = total_length - done;
}
bzero(block, pipe_max + 1);
strncpy(block, s + done, to_do);
int rv = fputs(block, stream);
tcdrain(fileno(stream));
if (rv == EOF) {
break;
}
}
free(block);
}
#ifdef DEBUG_VIRTUAL_SERIAL_PORT
static void LogWithFormat(bool decorate, const char *format, ...);
#endif
static void LogWithFormatV(bool decorate, const char *format, va_list args)
{
MaybeGetProcPath();
if (!format || !format[0]) {
return;
}
set_in_LogWithFormatV(true);
char *message;
long message_length;
if (CanUseCF()) {
CFStringRef formatCFSTR =
CFStringCreateWithCString(kCFAllocatorDefault, format,
kCFStringEncodingMacRoman);
CFStringRef messageCFSTR =
CFStringCreateWithFormatAndArguments(kCFAllocatorDefault, NULL,
formatCFSTR, args);
CFRelease(formatCFSTR);
message_length =
CFStringGetMaximumSizeForEncoding(CFStringGetLength(messageCFSTR),
kCFStringEncodingMacRoman);
message = (char *) calloc(message_length + 1, 1);
CFStringGetBytes(messageCFSTR, CFRangeMake(0, message_length),
kCFStringEncodingMacRoman, '?', true,
(unsigned char *) message, message_length, NULL);
CFRelease(messageCFSTR);
} else {
vasprintf(&message, format, args);
message_length = strlen(message);
}
char *finished = (char *) calloc(message_length + 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);
#ifdef VIRTUAL_SERIAL_PORT
if (!g_virtual_serial_checked) {
g_virtual_serial_checked = true;
g_virtual_serial =
open(VIRTUAL_SERIAL_PORT, O_WRONLY | O_NONBLOCK | O_NOCTTY);
if (g_virtual_serial >= 0) {
g_virtual_serial_FILE = fdopen(g_virtual_serial, "w");
}
#ifdef DEBUG_VIRTUAL_SERIAL_PORT
if (!g_virtual_serial_FILE) {
LogWithFormat(true, "Hook.mm: g_virtual_serial %i, g_virtual_serial_FILE %p, errno %i, stdout_path %s",
g_virtual_serial, g_virtual_serial_FILE, errno, stdout_path);
}
#endif
}
#endif
if (g_virtual_serial_FILE) {
tty_fputs(finished, g_virtual_serial_FILE);
} else {
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 (g_virtual_serial_FILE) {
fputs(finished, g_virtual_serial_FILE);
} else {
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);
set_in_LogWithFormatV(false);
}
static void LogWithFormat(bool decorate, const char *format, ...)
{
va_list args;
va_start(args, format);
LogWithFormatV(decorate, format, args);
va_end(args);
}
// The hook for __CFGetConverter() works around a bug or design flaw in the
// CoreFoundation framework's CFStringCreateWithFormatAndArguments() function,
// called from LogWithFormatV(): It always uses the string encoding associated
// with the "preferred language" setting (misleadingly called the "system
// encoding").
//
// For languages that use Latin scripts the "system encoding" is
// kCFStringEncodingMacRoman, which is appropriate for use in
// LogWithFormatV(): It can handle strings that combine characters from many
// different encodings (like Roman letters and Chinese characters). It's also
// the encoding used by macOS itself at the most basic level (the
// LC_C_LOCALE). But if your "preferred language" doesn't use a Latin script
// (for example Chinese or Japanese) the "system encoding" is one specifically
// associated with that language. It generally doesn't allow you to combine
// characters from different encoding systems in a single string. If you try,
// it replaces unrecognized characters with "?", or sometimes refuses to
// process it at all. This happens in CFStringCreateWithFormatAndArguments()
// when, for example, your "preferred language" is Russian, Greek,
// "Traditional Chinese" or "Simplified Chinese", and one of the arguments is
// a string that combines Roman letters and Chinese characters.
//
// Many CoreFoundation string functions allow you to specify the string
// encoding -- for example CFStringCreateWithCString() and CFStringGetBytes().
// CFStringCreateWithFormatAndArguments() really should, too. But for as long
// as it doesn't, we can use the following hook to force it to use
// kCFStringEncodingMacRoman when called from LogWithFormatV().
//
// This workaround isn't available for 32-bit hook libraries. This is because
// __CFGetConverter() uses the "fastcc" calling convention in 32-bit system
// libraries, which isn't supported by any compiler. It *is* supported in
// LLVM intermediate language, but frankly it's not worth the trouble to use
// that here.
//#define DEBUG_GET_CONVERTER 1
#ifdef DEBUG_GET_CONVERTER
GET_SET_IN_FUNCS(__CFGetConverter)
#endif
void *(*__CFGetConverter_caller)(uint32_t encoding) = NULL;
void *Hooked___CFGetConverter(uint32_t encoding)
{
#ifdef DEBUG_GET_CONVERTER
set_in___CFGetConverter(true);
#endif
if (get_in_LogWithFormatV()) {
encoding = kCFStringEncodingMacRoman;
}
void *retval = __CFGetConverter_caller(encoding);
#ifdef DEBUG_GET_CONVERTER
// The call to LogWithFormat() below can cause this function to be re-entered.
if (get_in___CFGetConverter_count() == 1) {
if (get_in_LogWithFormatV()) {
LogWithFormat(true, "Hook.mm: __CFGetConverter(): encoding %u, returning %p",
encoding, retval);
//PrintStackTrace();
}
}
#endif
#ifdef DEBUG_GET_CONVERTER
set_in___CFGetConverter(false);
#endif
return retval;
}
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 *get_all_image_infos()
{
static dyld_all_image_infos *retval = NULL;
if (!retval) {
task_dyld_info_data_t info;
mach_msg_type_number_t count = TASK_DYLD_INFO_COUNT;
if (task_info(mach_task_self(), TASK_DYLD_INFO,
(task_info_t) &info, &count) == KERN_SUCCESS)
{
retval = (dyld_all_image_infos *) info.all_image_info_addr;
}
}
return retval;
}
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);
#if __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ < 110000
} else {
strncpy(moduleName_local, moduleName, sizeof(moduleName_local));
}
#else // __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ < 110000
// On macOS 11 (Big Sur), open() generally doesn't work on moduleName,
// because it generally isn't in the file system (only in the dyld shared
// cache). As best I can tell, there's no general workaround for this
// design flaw. But because all (or almost all) frameworks have a
// 'Resources' soft link in the same directory where there used to be a
// soft link to the framework binary, we can hack together a workaround
// for frameworks.
} else {
char holder[PATH_MAX];
strncpy(holder, moduleName, sizeof(holder));
size_t fixed_to = 0;
bool done = false;
while (!done) {
char proxy_path[PATH_MAX];
strncpy(proxy_path, holder, sizeof(proxy_path));
const char *subpath_tag = ".framework/";
char *subpath_ptr =
strnstr(proxy_path + fixed_to,
subpath_tag, sizeof(proxy_path) - fixed_to);
if (subpath_ptr) {
subpath_ptr += strlen(subpath_tag);
char subpath[PATH_MAX];
strncpy(subpath, subpath_ptr, sizeof(subpath));
subpath_ptr[0] = 0;
const char *proxy_name = "Resources";
size_t proxy_name_len = strlen(proxy_name);
strncat(proxy_path, proxy_name,
sizeof(proxy_path) - strlen(proxy_path) - 1);
fd = open(proxy_path, O_RDONLY);
if (fd > 0) {
if (fcntl(fd, F_GETPATH, holder) != -1) {
fixed_to = strlen(holder) - proxy_name_len;
holder[fixed_to] = 0;
strncat(holder, subpath, sizeof(holder) - fixed_to);
const char *frameworks_tag = "Frameworks";
if (strncmp(holder + fixed_to, frameworks_tag,
strlen(frameworks_tag)) != 0)
{
strncpy(moduleName_local, holder, sizeof(moduleName_local));
done = true;
}
} else {
done = true;
}
close(fd);
} else {
done = true;
}
} else {
done = true;
}
}
if (!moduleName_local[0]) {
strncpy(moduleName_local, moduleName, sizeof(moduleName_local));
}
}
#endif // __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ < 110000
}
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");
if (!_dyld_get_all_image_infos) {
_dyld_get_all_image_infos = 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;