-
Notifications
You must be signed in to change notification settings - Fork 6
/
machoview.cpp
3399 lines (3088 loc) · 123 KB
/
machoview.cpp
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
#include <algorithm>
#include <cstdint>
#include <sstream>
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>
#include <tuple>
#ifndef _MSC_VER
#include <cxxabi.h>
#endif
#include "machoview.h"
#include "fatmachoview.h"
#include "universalview.h"
#include "lowlevelilinstruction.h"
#include "rapidjsonwrapper.h"
enum {
N_STAB = 0xe0,
N_PEXT = 0x10,
N_TYPE = 0x0e,
N_EXT = 0x01
};
using namespace BinaryNinja;
using namespace std;
static MachoViewType* g_machoViewType = nullptr;
static string CommandToString(uint32_t lcCommand)
{
switch(lcCommand)
{
case LC_REQ_DYLD: return "LC_REQ_DYLD";
case LC_SEGMENT: return "LC_SEGMENT";
case LC_SYMTAB: return "LC_SYMTAB";
case LC_SYMSEG: return "LC_SYMSEG";
case LC_THREAD: return "LC_THREAD";
case LC_UNIXTHREAD: return "LC_UNIXTHREAD";
case LC_LOADFVMLIB: return "LC_LOADFVMLIB";
case LC_IDFVMLIB: return "LC_IDFVMLIB";
case LC_IDENT: return "LC_IDENT";
case LC_FVMFILE: return "LC_FVMFILE";
case LC_PREPAGE: return "LC_PREPAGE";
case LC_DYSYMTAB: return "LC_DYSYMTAB";
case LC_LOAD_DYLIB: return "LC_LOAD_DYLIB";
case LC_ID_DYLIB: return "LC_ID_DYLIB";
case LC_LOAD_DYLINKER: return "LC_LOAD_DYLINKER";
case LC_ID_DYLINKER: return "LC_ID_DYLINKER";
case LC_PREBOUND_DYLIB: return "LC_PREBOUND_DYLIB";
case LC_ROUTINES: return "LC_ROUTINES";
case LC_SUB_FRAMEWORK: return "LC_SUB_FRAMEWORK";
case LC_SUB_UMBRELLA: return "LC_SUB_UMBRELLA";
case LC_SUB_CLIENT: return "LC_SUB_CLIENT";
case LC_SUB_LIBRARY: return "LC_SUB_LIBRARY";
case LC_TWOLEVEL_HINTS: return "LC_TWOLEVEL_HINTS";
case LC_PREBIND_CKSUM: return "LC_PREBIND_CKSUM";
case LC_LOAD_WEAK_DYLIB: return "LC_LOAD_WEAK_DYLIB";
case LC_SEGMENT_64: return "LC_SEGMENT_64";
case LC_ROUTINES_64: return "LC_ROUTINES_64";
case LC_UUID: return "LC_UUID";
case LC_RPATH: return "LC_RPATH";
case LC_CODE_SIGNATURE: return "LC_CODE_SIGNATURE";
case LC_SEGMENT_SPLIT_INFO: return "LC_SEGMENT_SPLIT_INFO";
case LC_REEXPORT_DYLIB: return "LC_REEXPORT_DYLIB";
case LC_LAZY_LOAD_DYLIB: return "LC_LAZY_LOAD_DYLIB";
case LC_ENCRYPTION_INFO: return "LC_ENCRYPTION_INFO";
case LC_DYLD_INFO: return "LC_DYLD_INFO";
case LC_DYLD_INFO_ONLY: return "LC_DYLD_INFO_ONLY";
case LC_LOAD_UPWARD_DYLIB: return "LC_LOAD_UPWARD_DYLIB";
case LC_VERSION_MIN_MACOSX: return "LC_VERSION_MIN_MACOSX";
case LC_VERSION_MIN_IPHONEOS: return "LC_VERSION_MIN_IPHONEOS";
case LC_FUNCTION_STARTS: return "LC_FUNCTION_STARTS";
case LC_DYLD_ENVIRONMENT: return "LC_DYLD_ENVIRONMENT";
case LC_MAIN: return "LC_MAIN";
case LC_DATA_IN_CODE: return "LC_DATA_IN_CODE";
case LC_SOURCE_VERSION: return "LC_SOURCE_VERSION";
case LC_DYLIB_CODE_SIGN_DRS: return "LC_DYLIB_CODE_SIGN_DRS";
case _LC_ENCRYPTION_INFO_64: return "LC_ENCRYPTION_INFO_64";
case _LC_LINKER_OPTION: return "LC_LINKER_OPTION";
case _LC_LINKER_OPTIMIZATION_HINT: return "LC_LINKER_OPTIMIZATION_HINT";
case _LC_VERSION_MIN_TVOS: return "LC_VERSION_MIN_TVOS";
case LC_VERSION_MIN_WATCHOS: return "LC_VERSION_MIN_WATCHOS";
case LC_NOTE: return "LC_NOTE";
case LC_BUILD_VERSION: return "LC_BUILD_VERSION";
case LC_DYLD_EXPORTS_TRIE: return "LC_DYLD_EXPORTS_TRIE";
case LC_DYLD_CHAINED_FIXUPS: return "LC_DYLD_CHAINED_FIXUPS";
default:
{
stringstream ss;
ss << "0x" << std::hex << lcCommand;
return ss.str();
}
}
}
static string BuildPlatformToString(uint32_t platform)
{
switch (platform)
{
case MACHO_PLATFORM_MACOS: return "macos";
case MACHO_PLATFORM_IOS: return "ios";
case MACHO_PLATFORM_TVOS: return "tvos";
case MACHO_PLATFORM_WATCHOS: return "watchos";
case MACHO_PLATFORM_BRIDGEOS: return "bridgeos";
default:
{
stringstream ss;
ss << "0x" << std::hex << platform;
return ss.str();
}
}
}
static string BuildToolToString(uint32_t tool)
{
switch (tool)
{
case MACHO_TOOL_CLANG: return "clang";
case MACHO_TOOL_SWIFT: return "swift";
case MACHO_TOOL_LD: return "ld";
default:
{
stringstream ss;
ss << "0x" << std::hex << tool;
return ss.str();
}
}
}
static string BuildToolVersionToString(uint32_t version)
{
uint32_t major = (version >> 16) & 0xffff;
uint32_t minor = (version >> 8) & 0xff;
uint32_t update = version & 0xff;
stringstream ss;
ss << major << "." << minor;
if (update)
ss << "." << update;
return ss.str();
}
void BinaryNinja::InitMachoViewType()
{
static MachoViewType type;
BinaryViewType::Register(&type);
g_machoViewType = &type;
}
static int64_t readSLEB128(DataBuffer& buffer, size_t length, size_t &offset)
{
uint8_t cur;
int64_t value = 0;
size_t shift = 0;
while (offset < length)
{
cur = buffer[offset++];
value |= (cur & 0x7f) << shift;
shift += 7;
if ((cur & 0x80) == 0)
break;
}
value = (value << (64 - shift)) >> (64 - shift);
return value;
}
static uint64_t readLEB128(DataBuffer& p, size_t end, size_t &offset)
{
uint64_t result = 0;
int bit = 0;
do {
if (offset >= end)
return -1;
uint64_t slice = p[offset] & 0x7f;
if (bit > 63)
return -1;
else {
result |= (slice << bit);
bit += 7;
}
} while (p[offset++] & 0x80);
return result;
}
uint64_t readValidULEB128(DataBuffer& buffer, size_t& cursor)
{
uint64_t value = readLEB128(buffer, buffer.GetLength(), cursor);
if ((int64_t)value == -1)
throw ReadException();
return value;
}
MachoView::MachoView(const string& typeName, BinaryView* data, bool parseOnly): BinaryView(typeName, data->GetFile(), data),
m_universalImageOffset(0), m_parseOnly(parseOnly)
{
CreateLogger("BinaryView");
m_logger = CreateLogger("BinaryView.MachoView");
m_backedByDatabase = data->GetFile()->IsBackedByDatabase(typeName);
Ref<BinaryViewType> universalViewType = BinaryViewType::GetByName("Universal");
bool isUniversal = (universalViewType && universalViewType->IsTypeValidForData(data));
Ref<Settings> viewSettings = Settings::Instance();
m_extractMangledTypes = viewSettings->Get<bool>("analysis.extractTypesFromMangledNames", data);
m_simplifyTemplates = viewSettings->Get<bool>("analysis.types.templateSimplifier", data);
Ref<Settings> settings = data->GetLoadSettings(typeName);
if (settings && settings->Contains("loader.macho.universalImageOffset"))
{
settings->SetResourceId(typeName);
m_universalImageOffset = settings->Get<uint64_t>("loader.macho.universalImageOffset", data);
}
else if (isUniversal)
{
Ref<Settings> loadSettings = universalViewType->GetLoadSettingsForData(data);
if (loadSettings && loadSettings->Contains("loader.universal.architectures"))
{
string json = loadSettings->Get<string>("loader.universal.architectures");
rapidjson::Document jsonArchitectures;
jsonArchitectures.Parse(json.data(), json.size());
if (!json.size() || jsonArchitectures.HasParseError())
throw MachoFormatException("Mach-O view could not be created! Json parse error.");
if (!jsonArchitectures.IsArray() || jsonArchitectures.Empty())
throw MachoFormatException("Mach-O view could not be created! Json data error.");
// Select the object file based on architecture preference.
// Note: This code is duplicated in options.cpp
vector<string> architectures;
for (const auto& entry : jsonArchitectures.GetArray())
architectures.push_back(entry["architecture"].GetString());
auto archPref = Settings::Instance()->Get<vector<string>>("files.universal.architecturePreference");
int archIndex = 0;
if (auto result = find_first_of(archPref.begin(), archPref.end(), architectures.begin(), architectures.end()); result != archPref.end())
archIndex = std::find(architectures.begin(), architectures.end(), *result) - architectures.begin();
const auto& archEntry = jsonArchitectures[archIndex];
loadSettings = Settings::Instance(GetUniqueIdentifierString());
loadSettings->SetResourceId(typeName);
loadSettings->DeserializeSchema(archEntry["loadSchema"].GetString());
data->SetLoadSettings(typeName, loadSettings);
if (!m_file->IsBackedByDatabase(typeName))
{
auto defaultSettings = loadSettings->SerializeSettings(nullptr, SettingsDefaultScope);
loadSettings->DeserializeSettings(defaultSettings, data, SettingsResourceScope);
}
m_universalImageOffset = loadSettings->Get<uint64_t>("loader.macho.universalImageOffset", data);
// NOTE: this silences the 'Updated load schema detected' warning. There is some chicken/egg stuff here.
loadSettings->UpdateProperty("loader.macho.universalImageOffset", "default", m_universalImageOffset);
}
}
m_header = HeaderForAddress(data, 0, true);
}
MachOHeader MachoView::HeaderForAddress(BinaryView* data, uint64_t address, bool isMainHeader, std::string identifierPrefix)
{
MachOHeader header{};
header.isMainHeader = isMainHeader;
header.identifierPrefix = identifierPrefix;
header.stringList = new DataBuffer();
std::string errorMsg;
if (isMainHeader) {
header.loadCommandOffset = g_machoViewType->ParseHeaders(data, m_universalImageOffset + address, header.ident, &m_arch, &m_plat, errorMsg);
if (!header.loadCommandOffset)
throw MachoFormatException(errorMsg);
}
else
{
// address is a Raw file offset
BinaryReader subReader(data);
subReader.Seek(address);
header.ident.magic = subReader.Read32();
BNEndianness endianness;
if (header.ident.magic == MH_MAGIC || header.ident.magic == MH_MAGIC_64)
endianness = LittleEndian;
else if (header.ident.magic == MH_CIGAM || header.ident.magic == MH_CIGAM_64)
endianness = BigEndian;
else
{
throw ReadException();
}
subReader.SetEndianness(endianness);
header.ident.cputype = subReader.Read32();
header.ident.cpusubtype = subReader.Read32();
header.ident.filetype = subReader.Read32();
header.ident.ncmds = subReader.Read32();
header.ident.sizeofcmds = subReader.Read32();
header.ident.flags = subReader.Read32();
if ((header.ident.cputype & MachOABIMask) == MachOABI64) // address size == 8
{
header.ident.reserved = subReader.Read32();
}
header.loadCommandOffset = subReader.GetOffset();
}
if (isMainHeader)
{
if (header.ident.magic == MH_MAGIC || header.ident.magic == MH_MAGIC_64)
{
m_endian = LittleEndian;
m_logger->LogDebug("Recognized Little Endian Mach-O");
}
else // (header.ident.magic == MH_CIGAM || header.ident.magic == MH_CIGAM_64)
{
m_endian = BigEndian;
m_logger->LogDebug("Recognized Big Endian Mach-O");
}
}
BinaryReader reader(data);
reader.SetEndianness(m_endian);
reader.SetVirtualBase(m_universalImageOffset);
reader.Seek(header.loadCommandOffset);
if (isMainHeader)
{
m_objectFile = header.ident.filetype == MH_OBJECT;
m_dylibFile = header.ident.filetype == MH_DYLIB;
m_relocatable = ((header.ident.flags & MH_PIE) > 0) || m_objectFile || m_dylibFile;
m_archId = header.ident.cputype;
m_addressSize = (header.ident.cputype & MachOABIMask) == MachOABI64 ? 8 : 4;
}
bool first = true;
// Parse segment commands
try
{
m_logger->LogDebug("ident.ncmds: %d\n", header.ident.ncmds);
for (size_t i = 0; i < header.ident.ncmds; i++)
{
load_command load;
segment_command_64 segment64;
section_64 sect;
memset(§, 0, sizeof(sect));
size_t curOffset = reader.GetOffset();
load.cmd = reader.Read32();
load.cmdsize = reader.Read32();
size_t nextOffset = curOffset + load.cmdsize;
m_logger->LogDebug("Segment cmd: %08x - cmdsize: %08x - ", load.cmd, load.cmdsize);
if (load.cmdsize < sizeof(load_command))
throw MachoFormatException("unable to read header");
switch (load.cmd)
{
case LC_MAIN:
{
uint64_t entryPoint = reader.Read64();
m_logger->LogDebug("LC_MAIN entryPoint: %#016" PRIx64, entryPoint);
header.entryPoints.push_back({entryPoint, true});
(void)reader.Read64(); // Stack start
break;
}
case LC_SEGMENT: //map the 32bit version to 64 bits
m_logger->LogDebug("LC_SEGMENT\n");
segment64.cmd = LC_SEGMENT_64;
reader.Read(&segment64.segname, 16);
segment64.vmaddr = reader.Read32();
segment64.vmsize = reader.Read32();
segment64.fileoff = reader.Read32() + m_universalImageOffset;
segment64.filesize = reader.Read32();
segment64.maxprot = reader.Read32();
segment64.initprot = reader.Read32();
segment64.nsects = reader.Read32();
segment64.flags = reader.Read32();
if (first)
{
if (!((header.ident.flags & MH_SPLIT_SEGS) || header.ident.cputype == MACHO_CPU_TYPE_X86_64)
|| (segment64.flags & MACHO_VM_PROT_WRITE))
{
header.relocationBase = segment64.vmaddr;
first = false;
}
}
m_logger->LogDebug("\tName: %s\n" \
"\tCmd: %#08" PRIx32 "\n" \
"\tvmaddr: %#016" PRIx64 "\n" \
"\tvmsize: %#016" PRIx64 "\n" \
"\tfileoff: %#016" PRIx64 "\n" \
"\tfilesize: %#016" PRIx64 "\n" \
"\tmaxprot: %#08" PRIx32 "\n" \
"\tinitprot: %#08" PRIx32 "\n" \
"\tnsects: %#08" PRIx32 "\n" \
"\tflags: %#08" PRIx32 "\n",
(char*)&segment64.segname,
segment64.cmd,
segment64.vmaddr,
segment64.vmsize,
segment64.fileoff,
segment64.filesize,
segment64.maxprot,
segment64.initprot,
segment64.nsects,
segment64.flags);
for (size_t j = 0; j < segment64.nsects; j++)
{
reader.Read(§.sectname, 16);
reader.Read(§.segname, 16);
sect.addr = reader.Read32();
sect.size = reader.Read32();
sect.offset = reader.Read32();
sect.align = reader.Read32();
sect.reloff = reader.Read32();
sect.nreloc = reader.Read32();
sect.flags = reader.Read32();
sect.reserved1 = reader.Read32();
sect.reserved2 = reader.Read32();
// if the segment isn't mapped into virtual memory don't add the corresponding sections.
if (segment64.vmsize > 0)
{
header.sections.push_back(sect);
m_allSections.push_back(sect);
}
else
m_logger->LogInfo("Omitting section %16s at %#" PRIx64 " corresponding to segment %16s which is not mapped into memory", (char*)§.sectname, sect.addr, (char*)§.segname);
m_logger->LogDebug("\t\tSegName: %16s\n" \
"\t\tSectName: %16s\n" \
"\t\tAddr: %#" PRIx64 "\n" \
"\t\tSize: %#" PRIx64 "\n" \
"\t\tOffset: %#" PRIx32 "\n" \
"\t\tAlign: %#" PRIx32 "\n" \
"\t\tReloff: %#" PRIx32 "\n" \
"\t\tNReloc: %#" PRIx32 "\n" \
"\t\tFlags: %#" PRIx32 "\n" \
"\t\tReserved1:%#" PRIx32 "\n" \
"\t\tReserved2:%#" PRIx32 "\n" \
"\t\t------------------------\n",
(char*)§.segname,
(char*)§.sectname,
sect.addr,
sect.size,
sect.offset,
sect.align,
sect.reloff,
sect.nreloc,
sect.flags,
sect.reserved1,
sect.reserved2);
if (!strncmp(sect.sectname, "__mod_init_func", 15))
header.moduleInitSections.push_back(sect);
if ((sect.flags & (S_ATTR_SELF_MODIFYING_CODE | S_SYMBOL_STUBS)) == (S_ATTR_SELF_MODIFYING_CODE | S_SYMBOL_STUBS))
header.symbolStubSections.push_back(sect);
if ((sect.flags & S_NON_LAZY_SYMBOL_POINTERS) == S_NON_LAZY_SYMBOL_POINTERS)
header.symbolPointerSections.push_back(sect);
if ((sect.flags & S_LAZY_SYMBOL_POINTERS) == S_LAZY_SYMBOL_POINTERS)
header.symbolPointerSections.push_back(sect);
}
header.segments.push_back(segment64);
m_allSegments.push_back(segment64);
break;
case LC_SEGMENT_64:
m_logger->LogDebug("LC_SEGMENT_64\n");
segment64.cmd = LC_SEGMENT_64;
reader.Read(&segment64.segname, 16);
segment64.vmaddr = reader.Read64();
segment64.vmsize = reader.Read64();
segment64.fileoff = reader.Read64() + m_universalImageOffset;
segment64.filesize = reader.Read64();
segment64.maxprot = reader.Read32();
segment64.initprot = reader.Read32();
segment64.nsects = reader.Read32();
segment64.flags = reader.Read32();
if (first)
{
if (!((header.ident.flags & MH_SPLIT_SEGS) || header.ident.cputype == MACHO_CPU_TYPE_X86_64)
|| (segment64.flags & MACHO_VM_PROT_WRITE))
{
header.relocationBase = segment64.vmaddr;
first = false;
}
}
m_logger->LogDebug(
"\tName: %s\n" \
"\tCmd: %#08" PRIx32 "\n" \
"\tvmaddr: %#016" PRIx64 "\n" \
"\tvmsize: %#016" PRIx64 "\n" \
"\tfileoff: %#016" PRIx64 "\n" \
"\tfilesize: %#016" PRIx64 "\n" \
"\tmaxprot: %#08" PRIx32 "\n" \
"\tinitprot: %#08" PRIx32 "\n" \
"\tnsects: %#08" PRIx32 "\n" \
"\tflags: %#08" PRIx32 "\n",
(char*)&segment64.segname,
segment64.cmd,
segment64.vmaddr,
segment64.vmsize,
segment64.fileoff,
segment64.filesize,
segment64.maxprot,
segment64.initprot,
segment64.nsects,
segment64.flags);
m_logger->LogDebug("\t\t------------------------\n");
for (size_t j = 0; j < segment64.nsects; j++)
{
reader.Read(§.sectname, 16);
reader.Read(§.segname, 16);
sect.addr = reader.Read64();
sect.size = reader.Read64();
sect.offset = reader.Read32();
sect.align = reader.Read32();
sect.reloff = reader.Read32();
sect.nreloc = reader.Read32();
sect.flags = reader.Read32();
sect.reserved1 = reader.Read32();
sect.reserved2 = reader.Read32();
sect.reserved3 = reader.Read32();
// if the segment isn't mapped into virtual memory don't add the corresponding sections.
if (segment64.vmsize > 0)
{
header.sections.push_back(sect);
m_allSections.push_back(sect);
}
else
m_logger->LogInfo("Omitting section %16s at %#" PRIx64 " corresponding to segment %16s which is not mapped into memory", (char*)§.sectname, sect.addr, (char*)§.segname);
m_logger->LogDebug(
"\t\tSegName: %16s\n" \
"\t\tSectName: %16s\n" \
"\t\tAddr: %#" PRIx64 "\n" \
"\t\tSize: %#" PRIx64 "\n" \
"\t\tOffset: %#" PRIx32 "\n" \
"\t\tAlign: %#" PRIx32 "\n" \
"\t\tReloff: %#" PRIx32 "\n" \
"\t\tNReloc: %#" PRIx32 "\n" \
"\t\tFlags: %#" PRIx32 "\n" \
"\t\tReserved1:%#" PRIx32 "\n" \
"\t\tReserved2:%#" PRIx32 "\n" \
"\t\tReserved3:%#" PRIx32 "\n" \
"\t\t------------------------\n",
(char*)§.segname,
(char*)§.sectname,
sect.addr,
sect.size,
sect.offset,
sect.align,
sect.reloff,
sect.nreloc,
sect.flags,
sect.reserved1,
sect.reserved2,
sect.reserved3);
if (!strncmp(sect.sectname, "__mod_init_func", 15))
header.moduleInitSections.push_back(sect);
if ((sect.flags & (S_ATTR_SELF_MODIFYING_CODE | S_SYMBOL_STUBS)) == (S_ATTR_SELF_MODIFYING_CODE | S_SYMBOL_STUBS))
header.symbolStubSections.push_back(sect);
if ((sect.flags & S_NON_LAZY_SYMBOL_POINTERS) == S_NON_LAZY_SYMBOL_POINTERS)
header.symbolPointerSections.push_back(sect);
if ((sect.flags & S_LAZY_SYMBOL_POINTERS) == S_LAZY_SYMBOL_POINTERS)
header.symbolPointerSections.push_back(sect);
}
header.segments.push_back(segment64);
m_allSegments.push_back(segment64);
break;
case LC_ROUTINES: //map the 32bit version to 64bits
m_logger->LogDebug("LC_REOUTINES\n");
header.routines64.cmd = LC_ROUTINES_64;
header.routines64.init_address = reader.Read32();
header.routines64.init_module = reader.Read32();
header.routines64.reserved1 = reader.Read32();
header.routines64.reserved2 = reader.Read32();
header.routines64.reserved3 = reader.Read32();
header.routines64.reserved4 = reader.Read32();
header.routines64.reserved5 = reader.Read32();
header.routines64.reserved6 = reader.Read32();
header.routinesPresent = true;
m_logger->LogDebug("\tinit_address: %016" PRIx64 "\n\tinit_module: %08" PRIx64 "\n",
header.routines64.init_address, header.routines64.init_module);
break;
case LC_ROUTINES_64:
m_logger->LogDebug("LC_REOUTINES_64\n");
header.routines64.cmd = LC_ROUTINES_64;
header.routines64.init_address = reader.Read64();
header.routines64.init_module = reader.Read64();
header.routines64.reserved1 = reader.Read64();
header.routines64.reserved2 = reader.Read64();
header.routines64.reserved3 = reader.Read64();
header.routines64.reserved4 = reader.Read64();
header.routines64.reserved5 = reader.Read64();
header.routines64.reserved6 = reader.Read64();
header.routinesPresent = true;
m_logger->LogDebug("\tinit_address: %016" PRIx64 "\n\tinit_module: %08" PRIx64 "\n",
header.routines64.init_address, header.routines64.init_module);
break;
case LC_FUNCTION_STARTS:
m_logger->LogDebug("LC_FUNCTION_STARTS\n");
header.functionStarts.funcoff = reader.Read32();
header.functionStarts.funcsize = reader.Read32();
header.functionStartsPresent = true;
m_logger->LogDebug("\tFunction Starts:\n\toffset: %#08" PRIx32 "\n\tsize: %#08" PRIx32 "\n",
header.functionStarts.funcoff, header.functionStarts.funcsize);
break;
case LC_SYMTAB:
m_logger->LogDebug("LC_SYMTAB\n");
header.symtab.symoff = reader.Read32();
header.symtab.nsyms = reader.Read32();
header.symtab.stroff = reader.Read32();
header.symtab.strsize = reader.Read32();
reader.Seek(header.symtab.stroff);
header.stringList->Append(reader.Read(header.symtab.strsize));
header.stringListSize = header.symtab.strsize;
m_logger->LogDebug("\tstrsize: %08x\n" \
"\tstroff: %08x\n" \
"\tnsyms: %08x\n",
header.symtab.strsize,
header.symtab.stroff,
header.symtab.nsyms);
break;
case LC_DYSYMTAB:
m_logger->LogDebug("LC_DYSYMTAB\n");
header.dysymtab.ilocalsym = reader.Read32();
header.dysymtab.nlocalsym = reader.Read32();
header.dysymtab.iextdefsym = reader.Read32();
header.dysymtab.nextdefsym = reader.Read32();
header.dysymtab.iundefsym = reader.Read32();
header.dysymtab.nundefsym = reader.Read32();
header.dysymtab.tocoff = reader.Read32();
header.dysymtab.ntoc = reader.Read32();
header.dysymtab.modtaboff = reader.Read32();
header.dysymtab.nmodtab = reader.Read32();
header.dysymtab.extrefsymoff = reader.Read32();
header.dysymtab.nextrefsyms = reader.Read32();
header.dysymtab.indirectsymoff = reader.Read32();
header.dysymtab.nindirectsyms = reader.Read32();
header.dysymtab.extreloff = reader.Read32();
header.dysymtab.nextrel = reader.Read32();
header.dysymtab.locreloff = reader.Read32();
header.dysymtab.nlocrel = reader.Read32();
m_logger->LogDebug("\theader.dysymtab.ilocalsym 0x%08x\n"\
"\theader.dysymtab.nlocalsym 0x%08x\n"\
"\theader.dysymtab.iextdefsym 0x%08x\n"\
"\theader.dysymtab.nextdefsym 0x%08x\n"\
"\theader.dysymtab.iundefsym 0x%08x\n"\
"\theader.dysymtab.nundefsym 0x%08x\n"\
"\theader.dysymtab.tocoff 0x%08x\n"\
"\theader.dysymtab.ntoc 0x%08x\n"\
"\theader.dysymtab.modtaboff 0x%08x\n"\
"\theader.dysymtab.nmodtab 0x%08x\n"\
"\theader.dysymtab.extrefsymoff 0x%08x\n"\
"\theader.dysymtab.nextrefsyms 0x%08x\n"\
"\theader.dysymtab.indirectsymoff 0x%08x\n"\
"\theader.dysymtab.nindirectsyms 0x%08x\n"\
"\theader.dysymtab.extreloff 0x%08x\n"\
"\theader.dysymtab.nextrel 0x%08x\n"\
"\theader.dysymtab.locreloff 0x%08x\n"\
"\theader.dysymtab.nlocrel 0x%08x\n",
header.dysymtab.ilocalsym,
header.dysymtab.nlocalsym,
header.dysymtab.iextdefsym,
header.dysymtab.nextdefsym,
header.dysymtab.iundefsym,
header.dysymtab.nundefsym,
header.dysymtab.tocoff,
header.dysymtab.ntoc,
header.dysymtab.modtaboff,
header.dysymtab.nmodtab,
header.dysymtab.extrefsymoff,
header.dysymtab.nextrefsyms,
header.dysymtab.indirectsymoff,
header.dysymtab.nindirectsyms,
header.dysymtab.extreloff,
header.dysymtab.nextrel,
header.dysymtab.locreloff,
header.dysymtab.nlocrel);
header.dysymPresent = true;
break;
case LC_DYLD_CHAINED_FIXUPS:
m_logger->LogDebug("LC_DYLD_CHAINED_FIXUPS\n");
header.chainedFixups.dataoff = reader.Read32();
header.chainedFixups.datasize = reader.Read32();
header.chainedFixupsPresent = true;
break;
case LC_DYLD_INFO:
case LC_DYLD_INFO_ONLY:
m_logger->LogDebug("LC_DYLD_INFO\n");
header.dyldInfo.rebase_off = reader.Read32();
header.dyldInfo.rebase_size = reader.Read32();
header.dyldInfo.bind_off = reader.Read32();
header.dyldInfo.bind_size = reader.Read32();
header.dyldInfo.weak_bind_off = reader.Read32();
header.dyldInfo.weak_bind_size = reader.Read32();
header.dyldInfo.lazy_bind_off = reader.Read32();
header.dyldInfo.lazy_bind_size = reader.Read32();
header.dyldInfo.export_off = reader.Read32();
header.dyldInfo.export_size = reader.Read32();
header.exportTrie.dataoff = header.dyldInfo.export_off;
header.exportTrie.datasize = header.dyldInfo.export_size;
header.exportTriePresent = true;
header.dyldInfoPresent = true;
break;
case LC_DYLD_EXPORTS_TRIE:
m_logger->LogDebug("LC_DYLD_EXPORTS_TRIE\n");
header.exportTrie.dataoff = reader.Read32();
header.exportTrie.datasize = reader.Read32();
header.exportTriePresent = true;
break;
case LC_THREAD:
case LC_UNIXTHREAD:
while (reader.GetOffset() < nextOffset)
{
thread_command thread;
thread.flavor = reader.Read32();
thread.count = reader.Read32();
m_logger->LogDebug("LC_THREAD\\LC_UNIXTHREAD\n");
switch (m_archId)
{
case MachOx64:
m_logger->LogDebug("x86_64 Thread state\n");
if (thread.flavor != X86_THREAD_STATE64)
{
reader.SeekRelative(thread.count * sizeof(uint32_t));
break;
}
//This wont be big endian so we can just read the whole thing
reader.Read(&thread.statex64, sizeof(thread.statex64));
header.entryPoints.push_back({thread.statex64.rip, false});
break;
case MachOx86:
m_logger->LogDebug("x86 Thread state\n");
if (thread.flavor != X86_THREAD_STATE32)
{
reader.SeekRelative(thread.count * sizeof(uint32_t));
break;
}
//This wont be big endian so we can just read the whole thing
reader.Read(&thread.statex86, sizeof(thread.statex86));
header.entryPoints.push_back({thread.statex86.eip, false});
break;
case MachOArm:
m_logger->LogDebug("Arm Thread state\n");
if (thread.flavor != _ARM_THREAD_STATE)
{
reader.SeekRelative(thread.count * sizeof(uint32_t));
break;
}
//This wont be big endian so we can just read the whole thing
reader.Read(&thread.statearmv7, sizeof(thread.statearmv7));
header.entryPoints.push_back({thread.statearmv7.r15, false});
break;
case MachOAarch64:
case MachOAarch6432:
m_logger->LogDebug("Aarch64 Thread state\n");
if (thread.flavor != _ARM_THREAD_STATE64)
{
reader.SeekRelative(thread.count * sizeof(uint32_t));
break;
}
reader.Read(&thread.stateaarch64, sizeof(thread.stateaarch64));
header.entryPoints.push_back({thread.stateaarch64.pc, false});
break;
case MachOPPC:
m_logger->LogDebug("PPC Thread state\n");
if (thread.flavor != PPC_THREAD_STATE)
{
reader.SeekRelative(thread.count * sizeof(uint32_t));
break;
}
//Read individual entries for endian reasons
header.entryPoints.push_back({reader.Read32(), false});
(void)reader.Read32();
(void)reader.Read32();
//Read the rest of the structure
(void)reader.Read(&thread.stateppc.r1, sizeof(thread.stateppc) - (3 * 4));
break;
case MachOPPC64:
m_logger->LogDebug("PPC64 Thread state\n");
if (thread.flavor != PPC_THREAD_STATE64)
{
reader.SeekRelative(thread.count * sizeof(uint32_t));
break;
}
header.entryPoints.push_back({reader.Read64(), false});
(void)reader.Read64();
(void)reader.Read64(); // Stack start
(void)reader.Read(&thread.stateppc64.r1, sizeof(thread.stateppc64) - (3 * 8));
break;
default:
m_logger->LogError("Unknown archid: %x", m_archId);
}
}
break;
case LC_LOAD_DYLIB:
{
uint32_t offset = reader.Read32();
if (offset < nextOffset)
{
reader.Seek(curOffset + offset);
string libname = reader.ReadCString();
header.dylibs.push_back(libname);
}
}
break;
case LC_BUILD_VERSION:
{
m_logger->LogDebug("LC_BUILD_VERSION:");
header.buildVersion.platform = reader.Read32();
header.buildVersion.minos = reader.Read32();
header.buildVersion.sdk = reader.Read32();
header.buildVersion.ntools = reader.Read32();
m_logger->LogDebug("Platform: %s", BuildPlatformToString(header.buildVersion.platform).c_str());
m_logger->LogDebug("MinOS: %s", BuildToolVersionToString(header.buildVersion.minos).c_str());
m_logger->LogDebug("SDK: %s", BuildToolVersionToString(header.buildVersion.sdk).c_str());
for (uint32_t i = 0; (i < header.buildVersion.ntools) && (i < 10); i++)
{
uint32_t tool = reader.Read32();
uint32_t version = reader.Read32();
header.buildToolVersions.push_back({tool, version});
m_logger->LogDebug("Build Tool: %s: %s", BuildToolToString(tool).c_str(), BuildToolVersionToString(version).c_str());
}
break;
}
case LC_FILESET_ENTRY:
{
if (isMainHeader)
{
uint64_t vmAddr = reader.Read64();
uint64_t fAddr = reader.Read64();
uint64_t strOff = reader.Read32() + curOffset;
reader.Seek(strOff);
auto identPrefix = reader.ReadCString(load.cmdsize - strOff);
MachOHeader subHeader = HeaderForAddress(data, fAddr, false, identPrefix);
subHeader.textBase = vmAddr;
m_subHeaders[vmAddr] = subHeader;
}
else {
throw ReadException();
}
break;
}
default:
m_logger->LogDebug("Unhandled command: %s : %" PRIu32 "\n", CommandToString(load.cmd).c_str(), load.cmdsize);
break;
}
if (reader.GetOffset() != nextOffset)
{
m_logger->LogDebug("Didn't parse load command: %s fully %" PRIx64 ":%" PRIxPTR, CommandToString(load.cmd).c_str(), reader.GetOffset(), nextOffset);
}
reader.Seek(nextOffset);
}
}
catch (ReadException&)
{
throw MachoFormatException("Mach-O section headers invalid");
}
return header;
}
void MachoView::RebaseThreadStarts(BinaryReader& virtualReader, vector<uint32_t>& threadStarts, uint64_t stepMultiplier)
{
std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now();
// create a dummy relocation to handle tagged pointers
BNRelocationInfo reloc;
memset(&reloc, 0, sizeof(BNRelocationInfo));
reloc.type = StandardRelocationType;
reloc.size = 8;
reloc.nativeType = BINARYNINJA_MANUAL_RELOCATION;
size_t numReg = 0;
size_t numAuth = 0;
uint64_t imageBase = GetStart();
for (auto threadStart : threadStarts)
{
if (threadStart == 0xffffffff)
break;
m_logger->LogDebug("Rebasing thread chain start: 0x%x", threadStart);
try
{
uint64_t curAddr = imageBase + threadStart;
virtualReader.Seek(curAddr);
while (true)
{
if (!IsOffsetBackedByFile(virtualReader.GetOffset()))
{
m_logger->LogError("Chained address: 0x%" PRIx64 " in thread start: 0x%x not backed by file!", virtualReader.GetOffset(), threadStart);
break;
}
// read tagged pointer
uint64_t val = virtualReader.Read64();
bool isAuthenticated = (val & (1ULL << 63)) != 0;
bool isRebase = (val & (1ULL << 62)) == 0;
if (isRebase)
{
// calculate new target value
uint64_t tgtVal;
if (isAuthenticated)
{
numAuth++;
tgtVal = (val & 0xFFFFFFFF) + imageBase;
}
else
{
numReg++;
uint64_t top8Bits = val & 0x0007F80000000000ULL;
uint64_t bottom43Bits = val & 0x000007FFFFFFFFFFULL;
tgtVal = (top8Bits << 13) | (((int64_t)(bottom43Bits << 21) >> 21) & 0x00FFFFFFFFFFFFFF);
tgtVal += m_imageBaseAdjustment;
}
reloc.address = curAddr;
DefineRelocation(m_arch, reloc, tgtVal, reloc.address);
}
// seek to next tagged pointer
val &= ~(1ULL << 62); // handle bind bit
uint64_t delta = (val & 0x3FF8000000000000) >> 51;
delta *= stepMultiplier;
if (!delta)
break;
curAddr += delta;
virtualReader.Seek(curAddr);
}
}
catch (ReadException&)
{
m_logger->LogError("Failed rebasing thread start at: 0x%x", threadStart);
}
}
std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now();
double t = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count() / 1000.0;
m_logger->LogInfo("Rebasing thread starts took %.3f seconds. Updated %" PRIuPTR " pointers (authenticated: %" PRIuPTR ", regular: %" PRIuPTR ").", t, numAuth + numReg, numAuth, numReg);
}
bool MachoView::IsValidFunctionStart(uint64_t addr)
{
uint8_t opcode[BN_MAX_INSTRUCTION_LENGTH];
size_t opLen = Read(opcode, addr, m_arch->GetMaxInstructionLength());
if (!opLen)
return false;
Ref<LowLevelILFunction> ilFunc = new LowLevelILFunction(m_arch, nullptr);
ilFunc->SetCurrentAddress(m_arch, addr);
m_arch->GetInstructionLowLevelIL(opcode, addr, opLen, *ilFunc);
for (size_t i = 0; i < ilFunc->GetInstructionCount(); i++)
{
const auto& instr = ilFunc->GetInstruction(i);
if (instr.operation == LLIL_UNDEF)
return false;
}
return true;
}
void MachoView::ParseFunctionStarts(Platform* platform, uint64_t textBase, function_starts_command functionStarts)
{
BinaryReader reader(GetParentView());
reader.SetEndianness(m_endian);
reader.SetVirtualBase(m_universalImageOffset);
try
{
if (m_header.ident.filetype == MH_DSYM)
{
m_logger->LogDebug("Skipping LC_FUNCTION_STARTS parsing");
return;
}
reader.Seek(functionStarts.funcoff);
DataBuffer buffer = reader.Read(functionStarts.funcsize);
size_t i = 0;
uint64_t curfunc = textBase;
uint64_t curOffset = 0;
while (i < functionStarts.funcsize)
{
curOffset = readLEB128(buffer, functionStarts.funcsize, i);
if (curOffset == 0)
continue;
curfunc += curOffset;
uint64_t target = curfunc;
if (!IsValidFunctionStart(target))
{
m_logger->LogWarn("Possible error processing LC_FUNCTION_STARTS! Not adding function at: 0x%" PRIx64 "\n", target);