-
Notifications
You must be signed in to change notification settings - Fork 123
/
MachODump.cpp
6131 lines (5774 loc) · 226 KB
/
MachODump.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
//===-- MachODump.cpp - Object file dumping utility for llvm --------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file implements the MachO-specific dumper for llvm-mctoll.
//
//===----------------------------------------------------------------------===//
// NOLINTBEGIN
#include "llvm-c/Disassembler.h"
#include "llvm-mctoll.h"
#include "Raiser/ModuleRaiser.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/Triple.h"
#include "llvm/BinaryFormat/MachO.h"
#include "llvm/Config/config.h"
#include "llvm/DebugInfo/DIContext.h"
#include "llvm/DebugInfo/DWARF/DWARFContext.h"
#include "llvm/Demangle/Demangle.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCDisassembler/MCDisassembler.h"
#include "llvm/MC/MCInst.h"
#include "llvm/MC/MCInstPrinter.h"
#include "llvm/MC/MCInstrDesc.h"
#include "llvm/MC/MCInstrInfo.h"
#include "llvm/MC/MCRegisterInfo.h"
#include "llvm/MC/MCSubtargetInfo.h"
#include "llvm/MC/MCTargetOptions.h"
#include "llvm/MC/TargetRegistry.h"
#include "llvm/Object/MachO.h"
#include "llvm/Object/MachOUniversal.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/Endian.h"
#include "llvm/Support/Format.h"
#include "llvm/Support/FormattedStream.h"
#include "llvm/Support/GraphWriter.h"
#include "llvm/Support/LEB128.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/ToolOutputFile.h"
#include <algorithm>
#include <cstring>
#include <system_error>
#ifdef HAVE_LIBXAR
extern "C" {
#include <xar/xar.h>
}
#endif
using namespace llvm;
using namespace llvm::mctoll;
using namespace object;
extern std::string MCPU;
extern std::vector<std::string> MAttrs;
static std::string DisSymName;
static bool PrintImmHex;
static bool UseDbg;
static std::string DSYMFile;
static bool FullLeadingAddr;
static bool NoLeadingHeaders;
// static bool ArchiveMemberOffsets;
static bool NonVerbose;
static bool NoSymbolicOperands;
static std::vector<std::string> ArchFlags;
bool ArchAll = false;
static std::string ThumbTripleName;
static const Target *GetTarget(const MachOObjectFile *MachOObj,
const char **McpuDefault,
const Target **ThumbTarget) {
// Figure out the target triple.
llvm::Triple TT(TripleName);
if (TripleName.empty()) {
TT = MachOObj->getArchTriple(McpuDefault);
TripleName = TT.str();
}
if (TT.getArch() == Triple::arm) {
// We've inferred a 32-bit ARM target from the object file. All MachO CPUs
// that support ARM are also capable of Thumb mode.
llvm::Triple ThumbTriple = TT;
std::string ThumbName = (Twine("thumb") + TT.getArchName().substr(3)).str();
ThumbTriple.setArchName(ThumbName);
ThumbTripleName = ThumbTriple.str();
}
// Get the target specific parser.
std::string Error;
const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
if (TheTarget && ThumbTripleName.empty())
return TheTarget;
*ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
if (*ThumbTarget)
return TheTarget;
errs() << "llvm-mctoll: error: unable to get target for '";
if (!TheTarget)
errs() << TripleName;
else
errs() << ThumbTripleName;
errs() << "', see --version and --triple.\n";
return nullptr;
}
struct SymbolSorter {
bool operator()(const SymbolRef &A, const SymbolRef &B) {
Expected<SymbolRef::Type> ATypeOrErr = A.getType();
if (!ATypeOrErr)
reportError(ATypeOrErr.takeError(), A.getObject()->getFileName());
SymbolRef::Type AType = *ATypeOrErr;
Expected<SymbolRef::Type> BTypeOrErr = B.getType();
if (!BTypeOrErr)
reportError(BTypeOrErr.takeError(), B.getObject()->getFileName());
SymbolRef::Type BType = *BTypeOrErr;
auto ASymOrErr = A.getValue();
if (!ASymOrErr)
reportError(ASymOrErr.takeError(), A.getObject()->getFileName());
auto BSymOrErr = B.getValue();
if (!BSymOrErr)
reportError(BSymOrErr.takeError(), B.getObject()->getFileName());
uint64_t AAddr = (AType != SymbolRef::ST_Function) ? 0 : *ASymOrErr;
uint64_t BAddr = (BType != SymbolRef::ST_Function) ? 0 : *BSymOrErr;
return AAddr < BAddr;
}
};
// Types for the storted data in code table that is built before disassembly
// and the predicate function to sort them.
typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
typedef std::vector<DiceTableEntry> DiceTable;
typedef DiceTable::iterator dice_table_iterator;
// This is used to search for a data in code table entry for the PC being
// disassembled. The j parameter has the PC in j.first. A single data in code
// table entry can cover many bytes for each of its Kind's. So if the offset,
// aka the i.first value, of the data in code table entry plus its Length
// covers the PC being searched for this will return true. If not it will
// return false.
static bool compareDiceTableEntries(const DiceTableEntry &i,
const DiceTableEntry &j) {
uint16_t Length;
i.second.getLength(Length);
return j.first >= i.first && j.first < i.first + Length;
}
static uint64_t DumpDataInCode(const uint8_t *bytes, uint64_t Length,
unsigned short Kind) {
uint32_t Value, Size = 1;
switch (Kind) {
default:
case MachO::DICE_KIND_DATA:
if (Length >= 4) {
dumpBytes(makeArrayRef(bytes, 4), outs());
Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
outs() << "\t.long " << Value;
Size = 4;
} else if (Length >= 2) {
dumpBytes(makeArrayRef(bytes, 2), outs());
Value = bytes[1] << 8 | bytes[0];
outs() << "\t.short " << Value;
Size = 2;
} else {
dumpBytes(makeArrayRef(bytes, 2), outs());
Value = bytes[0];
outs() << "\t.byte " << Value;
Size = 1;
}
if (Kind == MachO::DICE_KIND_DATA)
outs() << "\t@ KIND_DATA\n";
else
outs() << "\t@ data in code kind = " << Kind << "\n";
break;
case MachO::DICE_KIND_JUMP_TABLE8:
dumpBytes(makeArrayRef(bytes, 1), outs());
Value = bytes[0];
outs() << "\t.byte " << format("%3u", Value) << "\t@ KIND_JUMP_TABLE8\n";
Size = 1;
break;
case MachO::DICE_KIND_JUMP_TABLE16:
dumpBytes(makeArrayRef(bytes, 2), outs());
Value = bytes[1] << 8 | bytes[0];
outs() << "\t.short " << format("%5u", Value & 0xffff)
<< "\t@ KIND_JUMP_TABLE16\n";
Size = 2;
break;
case MachO::DICE_KIND_JUMP_TABLE32:
case MachO::DICE_KIND_ABS_JUMP_TABLE32:
dumpBytes(makeArrayRef(bytes, 4), outs());
Value = bytes[3] << 24 | bytes[2] << 16 | bytes[1] << 8 | bytes[0];
outs() << "\t.long " << Value;
if (Kind == MachO::DICE_KIND_JUMP_TABLE32)
outs() << "\t@ KIND_JUMP_TABLE32\n";
else
outs() << "\t@ KIND_ABS_JUMP_TABLE32\n";
Size = 4;
break;
}
return Size;
}
static void getSectionsAndSymbols(MachOObjectFile *MachOObj,
std::vector<SectionRef> &Sections,
std::vector<SymbolRef> &Symbols,
SmallVectorImpl<uint64_t> &FoundFns,
uint64_t &BaseSegmentAddress) {
const StringRef FileName = MachOObj->getFileName();
for (const SymbolRef &Symbol : MachOObj->symbols()) {
StringRef SymName = unwrapOrError(Symbol.getName(), FileName);
if (!SymName.startswith("ltmp"))
Symbols.push_back(Symbol);
}
for (const SectionRef &Section : MachOObj->sections()) {
StringRef SecName;
if (auto NameOrErr = Section.getName())
SecName = *NameOrErr;
else
consumeError(NameOrErr.takeError());
Sections.push_back(Section);
}
bool BaseSegmentAddressSet = false;
for (const auto &Command : MachOObj->load_commands()) {
if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
// We found a function starts segment, parse the addresses for later
// consumption.
MachO::linkedit_data_command LLC =
MachOObj->getLinkeditDataLoadCommand(Command);
MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
} else if (Command.C.cmd == MachO::LC_SEGMENT) {
MachO::segment_command SLC = MachOObj->getSegmentLoadCommand(Command);
StringRef SegName = SLC.segname;
if (!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
BaseSegmentAddressSet = true;
BaseSegmentAddress = SLC.vmaddr;
}
}
}
}
typedef DenseMap<uint64_t, StringRef> SymbolAddressMap;
static void CreateSymbolAddressMap(MachOObjectFile *O,
SymbolAddressMap *AddrMap) {
// Create a map of symbol addresses to symbol names.
const StringRef FileName = O->getFileName();
for (const SymbolRef &Symbol : O->symbols()) {
SymbolRef::Type ST = unwrapOrError(Symbol.getType(), FileName);
if (ST == SymbolRef::ST_Function || ST == SymbolRef::ST_Data ||
ST == SymbolRef::ST_Other) {
auto SymOrErr = Symbol.getValue();
if (!SymOrErr)
reportError(SymOrErr.takeError(), Symbol.getObject()->getFileName());
uint64_t Address = *SymOrErr;
StringRef SymName = unwrapOrError(Symbol.getName(), FileName);
if (!SymName.startswith(".objc"))
(*AddrMap)[Address] = SymName;
}
}
}
// GuessSymbolName is passed the address of what might be a symbol and a
// pointer to the SymbolAddressMap. It returns the name of a symbol
// with that address or nullptr if no symbol is found with that address.
static const char *GuessSymbolName(uint64_t value, SymbolAddressMap *AddrMap) {
const char *SymbolName = nullptr;
// A DenseMap can't lookup up some values.
if (value != 0xffffffffffffffffULL && value != 0xfffffffffffffffeULL) {
StringRef name = AddrMap->lookup(value);
if (!name.empty())
SymbolName = name.data();
}
return SymbolName;
}
static void DumpCstringChar(const char c) {
char p[2];
p[0] = c;
p[1] = '\0';
outs().write_escaped(p);
}
static void DumpCstringSection(MachOObjectFile *O, const char *sect,
uint32_t sect_size, uint64_t sect_addr,
bool print_addresses) {
for (uint32_t i = 0; i < sect_size; i++) {
if (print_addresses) {
if (O->is64Bit())
outs() << format("%016" PRIx64, sect_addr + i) << " ";
else
outs() << format("%08" PRIx64, sect_addr + i) << " ";
}
for (; i < sect_size && sect[i] != '\0'; i++)
DumpCstringChar(sect[i]);
if (i < sect_size && sect[i] == '\0')
outs() << "\n";
}
}
static void DumpLiteral4(uint32_t l, float f) {
outs() << format("0x%08" PRIx32, l);
if ((l & 0x7f800000) != 0x7f800000)
outs() << format(" (%.16e)\n", f);
else {
if (l == 0x7f800000)
outs() << " (+Infinity)\n";
else if (l == 0xff800000)
outs() << " (-Infinity)\n";
else if ((l & 0x00400000) == 0x00400000)
outs() << " (non-signaling Not-a-Number)\n";
else
outs() << " (signaling Not-a-Number)\n";
}
}
static void DumpLiteral4Section(MachOObjectFile *O, const char *sect,
uint32_t sect_size, uint64_t sect_addr,
bool print_addresses) {
for (uint32_t i = 0; i < sect_size; i += sizeof(float)) {
if (print_addresses) {
if (O->is64Bit())
outs() << format("%016" PRIx64, sect_addr + i) << " ";
else
outs() << format("%08" PRIx64, sect_addr + i) << " ";
}
float f;
memcpy(&f, sect + i, sizeof(float));
if (O->isLittleEndian() != sys::IsLittleEndianHost)
sys::swapByteOrder(f);
uint32_t l;
memcpy(&l, sect + i, sizeof(uint32_t));
if (O->isLittleEndian() != sys::IsLittleEndianHost)
sys::swapByteOrder(l);
DumpLiteral4(l, f);
}
}
static void DumpLiteral8(MachOObjectFile *O, uint32_t l0, uint32_t l1,
double d) {
outs() << format("0x%08" PRIx32, l0) << " " << format("0x%08" PRIx32, l1);
uint32_t Hi, Lo;
Hi = (O->isLittleEndian()) ? l1 : l0;
Lo = (O->isLittleEndian()) ? l0 : l1;
// Hi is the high word, so this is equivalent to if(isfinite(d))
if ((Hi & 0x7ff00000) != 0x7ff00000)
outs() << format(" (%.16e)\n", d);
else {
if (Hi == 0x7ff00000 && Lo == 0)
outs() << " (+Infinity)\n";
else if (Hi == 0xfff00000 && Lo == 0)
outs() << " (-Infinity)\n";
else if ((Hi & 0x00080000) == 0x00080000)
outs() << " (non-signaling Not-a-Number)\n";
else
outs() << " (signaling Not-a-Number)\n";
}
}
static void DumpLiteral8Section(MachOObjectFile *O, const char *sect,
uint32_t sect_size, uint64_t sect_addr,
bool print_addresses) {
for (uint32_t i = 0; i < sect_size; i += sizeof(double)) {
if (print_addresses) {
if (O->is64Bit())
outs() << format("%016" PRIx64, sect_addr + i) << " ";
else
outs() << format("%08" PRIx64, sect_addr + i) << " ";
}
double d;
memcpy(&d, sect + i, sizeof(double));
if (O->isLittleEndian() != sys::IsLittleEndianHost)
sys::swapByteOrder(d);
uint32_t l0, l1;
memcpy(&l0, sect + i, sizeof(uint32_t));
memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
if (O->isLittleEndian() != sys::IsLittleEndianHost) {
sys::swapByteOrder(l0);
sys::swapByteOrder(l1);
}
DumpLiteral8(O, l0, l1, d);
}
}
static void DumpLiteral16(uint32_t l0, uint32_t l1, uint32_t l2, uint32_t l3) {
outs() << format("0x%08" PRIx32, l0) << " ";
outs() << format("0x%08" PRIx32, l1) << " ";
outs() << format("0x%08" PRIx32, l2) << " ";
outs() << format("0x%08" PRIx32, l3) << "\n";
}
static void DumpLiteral16Section(MachOObjectFile *O, const char *sect,
uint32_t sect_size, uint64_t sect_addr,
bool print_addresses) {
for (uint32_t i = 0; i < sect_size; i += 16) {
if (print_addresses) {
if (O->is64Bit())
outs() << format("%016" PRIx64, sect_addr + i) << " ";
else
outs() << format("%08" PRIx64, sect_addr + i) << " ";
}
uint32_t l0, l1, l2, l3;
memcpy(&l0, sect + i, sizeof(uint32_t));
memcpy(&l1, sect + i + sizeof(uint32_t), sizeof(uint32_t));
memcpy(&l2, sect + i + 2 * sizeof(uint32_t), sizeof(uint32_t));
memcpy(&l3, sect + i + 3 * sizeof(uint32_t), sizeof(uint32_t));
if (O->isLittleEndian() != sys::IsLittleEndianHost) {
sys::swapByteOrder(l0);
sys::swapByteOrder(l1);
sys::swapByteOrder(l2);
sys::swapByteOrder(l3);
}
DumpLiteral16(l0, l1, l2, l3);
}
}
static void DumpLiteralPointerSection(MachOObjectFile *O,
const SectionRef &Section,
const char *sect, uint32_t sect_size,
uint64_t sect_addr,
bool print_addresses) {
// Collect the literal sections in this Mach-O file.
std::vector<SectionRef> LiteralSections;
for (const SectionRef &Section : O->sections()) {
DataRefImpl Ref = Section.getRawDataRefImpl();
uint32_t section_type;
if (O->is64Bit()) {
const MachO::section_64 Sec = O->getSection64(Ref);
section_type = Sec.flags & MachO::SECTION_TYPE;
} else {
const MachO::section Sec = O->getSection(Ref);
section_type = Sec.flags & MachO::SECTION_TYPE;
}
if (section_type == MachO::S_CSTRING_LITERALS ||
section_type == MachO::S_4BYTE_LITERALS ||
section_type == MachO::S_8BYTE_LITERALS ||
section_type == MachO::S_16BYTE_LITERALS)
LiteralSections.push_back(Section);
}
// Set the size of the literal pointer.
uint32_t lp_size = O->is64Bit() ? 8 : 4;
// Collect the external relocation symbols for the literal pointers.
std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
for (const RelocationRef &Reloc : Section.relocations()) {
DataRefImpl Rel;
MachO::any_relocation_info RE;
bool isExtern = false;
Rel = Reloc.getRawDataRefImpl();
RE = O->getRelocation(Rel);
isExtern = O->getPlainRelocationExternal(RE);
if (isExtern) {
uint64_t RelocOffset = Reloc.getOffset();
symbol_iterator RelocSym = Reloc.getSymbol();
Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
}
}
array_pod_sort(Relocs.begin(), Relocs.end());
// Dump each literal pointer.
for (uint32_t i = 0; i < sect_size; i += lp_size) {
if (print_addresses) {
if (O->is64Bit())
outs() << format("%016" PRIx64, sect_addr + i) << " ";
else
outs() << format("%08" PRIx64, sect_addr + i) << " ";
}
uint64_t lp;
if (O->is64Bit()) {
memcpy(&lp, sect + i, sizeof(uint64_t));
if (O->isLittleEndian() != sys::IsLittleEndianHost)
sys::swapByteOrder(lp);
} else {
uint32_t li;
memcpy(&li, sect + i, sizeof(uint32_t));
if (O->isLittleEndian() != sys::IsLittleEndianHost)
sys::swapByteOrder(li);
lp = li;
}
// First look for an external relocation entry for this literal pointer.
auto Reloc = find_if(Relocs, [&](const std::pair<uint64_t, SymbolRef> &P) {
return P.first == i;
});
if (Reloc != Relocs.end()) {
symbol_iterator RelocSym = Reloc->second;
StringRef SymName = unwrapOrError(RelocSym->getName(), O->getFileName());
outs() << "external relocation entry for symbol:" << SymName << "\n";
continue;
}
// For local references see what the section the literal pointer points to.
auto Sect = find_if(LiteralSections, [&](const SectionRef &R) {
return lp >= R.getAddress() && lp < R.getAddress() + R.getSize();
});
if (Sect == LiteralSections.end()) {
outs() << format("0x%" PRIx64, lp) << " (not in a literal section)\n";
continue;
}
uint64_t SectAddress = Sect->getAddress();
uint64_t SectSize = Sect->getSize();
StringRef SectName;
if (auto NameOrErr = Section.getName())
SectName = *NameOrErr;
else
consumeError(NameOrErr.takeError());
DataRefImpl Ref = Sect->getRawDataRefImpl();
StringRef SegmentName = O->getSectionFinalSegmentName(Ref);
outs() << SegmentName << ":" << SectName << ":";
uint32_t section_type;
if (O->is64Bit()) {
const MachO::section_64 Sec = O->getSection64(Ref);
section_type = Sec.flags & MachO::SECTION_TYPE;
} else {
const MachO::section Sec = O->getSection(Ref);
section_type = Sec.flags & MachO::SECTION_TYPE;
}
StringRef BytesStr = unwrapOrError(Sect->getContents(), O->getFileName());
const char *Contents = reinterpret_cast<const char *>(BytesStr.data());
switch (section_type) {
case MachO::S_CSTRING_LITERALS:
for (uint64_t i = lp - SectAddress; i < SectSize && Contents[i] != '\0';
i++) {
DumpCstringChar(Contents[i]);
}
outs() << "\n";
break;
case MachO::S_4BYTE_LITERALS:
float f;
memcpy(&f, Contents + (lp - SectAddress), sizeof(float));
uint32_t l;
memcpy(&l, Contents + (lp - SectAddress), sizeof(uint32_t));
if (O->isLittleEndian() != sys::IsLittleEndianHost) {
sys::swapByteOrder(f);
sys::swapByteOrder(l);
}
DumpLiteral4(l, f);
break;
case MachO::S_8BYTE_LITERALS: {
double d;
memcpy(&d, Contents + (lp - SectAddress), sizeof(double));
uint32_t l0, l1;
memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
sizeof(uint32_t));
if (O->isLittleEndian() != sys::IsLittleEndianHost) {
sys::swapByteOrder(f);
sys::swapByteOrder(l0);
sys::swapByteOrder(l1);
}
DumpLiteral8(O, l0, l1, d);
break;
}
case MachO::S_16BYTE_LITERALS: {
uint32_t l0, l1, l2, l3;
memcpy(&l0, Contents + (lp - SectAddress), sizeof(uint32_t));
memcpy(&l1, Contents + (lp - SectAddress) + sizeof(uint32_t),
sizeof(uint32_t));
memcpy(&l2, Contents + (lp - SectAddress) + 2 * sizeof(uint32_t),
sizeof(uint32_t));
memcpy(&l3, Contents + (lp - SectAddress) + 3 * sizeof(uint32_t),
sizeof(uint32_t));
if (O->isLittleEndian() != sys::IsLittleEndianHost) {
sys::swapByteOrder(l0);
sys::swapByteOrder(l1);
sys::swapByteOrder(l2);
sys::swapByteOrder(l3);
}
DumpLiteral16(l0, l1, l2, l3);
break;
}
}
}
}
static void DumpInitTermPointerSection(MachOObjectFile *O, const char *sect,
uint32_t sect_size, uint64_t sect_addr,
SymbolAddressMap *AddrMap,
bool verbose) {
uint32_t stride;
stride = (O->is64Bit()) ? sizeof(uint64_t) : sizeof(uint32_t);
for (uint32_t i = 0; i < sect_size; i += stride) {
const char *SymbolName = nullptr;
if (O->is64Bit()) {
outs() << format("0x%016" PRIx64, sect_addr + i * stride) << " ";
uint64_t pointer_value;
memcpy(&pointer_value, sect + i, stride);
if (O->isLittleEndian() != sys::IsLittleEndianHost)
sys::swapByteOrder(pointer_value);
outs() << format("0x%016" PRIx64, pointer_value);
if (verbose)
SymbolName = GuessSymbolName(pointer_value, AddrMap);
} else {
outs() << format("0x%08" PRIx64, sect_addr + i * stride) << " ";
uint32_t pointer_value;
memcpy(&pointer_value, sect + i, stride);
if (O->isLittleEndian() != sys::IsLittleEndianHost)
sys::swapByteOrder(pointer_value);
outs() << format("0x%08" PRIx32, pointer_value);
if (verbose)
SymbolName = GuessSymbolName(pointer_value, AddrMap);
}
if (SymbolName)
outs() << " " << SymbolName;
outs() << "\n";
}
}
static void DumpRawSectionContents(MachOObjectFile *O, const char *sect,
uint32_t size, uint64_t addr) {
uint32_t cputype = O->getHeader().cputype;
if (cputype == MachO::CPU_TYPE_I386 || cputype == MachO::CPU_TYPE_X86_64) {
uint32_t j;
for (uint32_t i = 0; i < size; i += j, addr += j) {
if (O->is64Bit())
outs() << format("%016" PRIx64, addr) << "\t";
else
outs() << format("%08" PRIx64, addr) << "\t";
for (j = 0; j < 16 && i + j < size; j++) {
uint8_t byte_word = *(sect + i + j);
outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
}
outs() << "\n";
}
} else {
uint32_t j;
for (uint32_t i = 0; i < size; i += j, addr += j) {
if (O->is64Bit())
outs() << format("%016" PRIx64, addr) << "\t";
else
outs() << format("%08" PRIx64, addr) << "\t";
for (j = 0; j < 4 * sizeof(int32_t) && i + j < size;
j += sizeof(int32_t)) {
if (i + j + sizeof(int32_t) <= size) {
uint32_t long_word;
memcpy(&long_word, sect + i + j, sizeof(int32_t));
if (O->isLittleEndian() != sys::IsLittleEndianHost)
sys::swapByteOrder(long_word);
outs() << format("%08" PRIx32, long_word) << " ";
} else {
for (uint32_t k = 0; i + j + k < size; k++) {
uint8_t byte_word = *(sect + i + j + k);
outs() << format("%02" PRIx32, (uint32_t)byte_word) << " ";
}
}
}
outs() << "\n";
}
}
}
static void DisassembleMachO(StringRef Filename, MachOObjectFile *MachOOF,
StringRef DisSegName, StringRef DisSectName);
static void DumpProtocolSection(MachOObjectFile *O, const char *sect,
uint32_t size, uint32_t addr);
#ifdef HAVE_LIBXAR
static void DumpBitcodeSection(MachOObjectFile *O, const char *sect,
uint32_t size, bool verbose, bool PrintXarHeader,
bool PrintXarFileHeaders,
std::string XarMemberName);
#endif // defined(HAVE_LIBXAR)
static void DumpSectionContents(StringRef Filename, MachOObjectFile *O,
bool verbose) {
SymbolAddressMap AddrMap;
if (verbose)
CreateSymbolAddressMap(O, &AddrMap);
for (unsigned i = 0; i < FilterSections.size(); ++i) {
StringRef DumpSection = FilterSections[i];
std::pair<StringRef, StringRef> DumpSegSectName;
DumpSegSectName = DumpSection.split(',');
StringRef DumpSegName, DumpSectName;
if (DumpSegSectName.second.size()) {
DumpSegName = DumpSegSectName.first;
DumpSectName = DumpSegSectName.second;
} else {
DumpSegName = "";
DumpSectName = DumpSegSectName.first;
}
for (const SectionRef &Section : O->sections()) {
StringRef SectName;
if (auto NameOrErr = Section.getName())
SectName = *NameOrErr;
else
consumeError(NameOrErr.takeError());
DataRefImpl Ref = Section.getRawDataRefImpl();
StringRef SegName = O->getSectionFinalSegmentName(Ref);
if ((DumpSegName.empty() || SegName == DumpSegName) &&
(SectName == DumpSectName)) {
uint32_t section_flags;
if (O->is64Bit()) {
const MachO::section_64 Sec = O->getSection64(Ref);
section_flags = Sec.flags;
} else {
const MachO::section Sec = O->getSection(Ref);
section_flags = Sec.flags;
}
uint32_t section_type = section_flags & MachO::SECTION_TYPE;
StringRef BytesStr =
unwrapOrError(Section.getContents(), O->getFileName());
const char *sect = reinterpret_cast<const char *>(BytesStr.data());
uint32_t sect_size = BytesStr.size();
uint64_t sect_addr = Section.getAddress();
outs() << "Contents of (" << SegName << "," << SectName
<< ") section\n";
if (verbose) {
if ((section_flags & MachO::S_ATTR_PURE_INSTRUCTIONS) ||
(section_flags & MachO::S_ATTR_SOME_INSTRUCTIONS)) {
DisassembleMachO(Filename, O, SegName, SectName);
continue;
}
if (SegName == "__TEXT" && SectName == "__info_plist") {
outs() << sect;
continue;
}
if (SegName == "__OBJC" && SectName == "__protocol") {
DumpProtocolSection(O, sect, sect_size, sect_addr);
continue;
}
#ifdef HAVE_LIBXAR
if (SegName == "__LLVM" && SectName == "__bundle") {
DumpBitcodeSection(O, sect, sect_size, verbose, !NoSymbolicOperands,
true, "");
continue;
}
#endif // defined(HAVE_LIBXAR)
switch (section_type) {
case MachO::S_REGULAR:
DumpRawSectionContents(O, sect, sect_size, sect_addr);
break;
case MachO::S_ZEROFILL:
outs() << "zerofill section and has no contents in the file\n";
break;
case MachO::S_CSTRING_LITERALS:
DumpCstringSection(O, sect, sect_size, sect_addr, true);
break;
case MachO::S_4BYTE_LITERALS:
DumpLiteral4Section(O, sect, sect_size, sect_addr, true);
break;
case MachO::S_8BYTE_LITERALS:
DumpLiteral8Section(O, sect, sect_size, sect_addr, true);
break;
case MachO::S_16BYTE_LITERALS:
DumpLiteral16Section(O, sect, sect_size, sect_addr, true);
break;
case MachO::S_LITERAL_POINTERS:
DumpLiteralPointerSection(O, Section, sect, sect_size, sect_addr,
true);
break;
case MachO::S_MOD_INIT_FUNC_POINTERS:
case MachO::S_MOD_TERM_FUNC_POINTERS:
DumpInitTermPointerSection(O, sect, sect_size, sect_addr, &AddrMap,
verbose);
break;
default:
outs() << "Unknown section type ("
<< format("0x%08" PRIx32, section_type) << ")\n";
DumpRawSectionContents(O, sect, sect_size, sect_addr);
break;
}
} else {
if (section_type == MachO::S_ZEROFILL)
outs() << "zerofill section and has no contents in the file\n";
else
DumpRawSectionContents(O, sect, sect_size, sect_addr);
}
}
}
}
}
// checkMachOAndArchFlags() checks to see if the ObjectFile is a Mach-O file
// and if it is and there is a list of architecture flags is specified then
// check to make sure this Mach-O file is one of those architectures or all
// architectures were specified. If not then an error is generated and this
// routine returns false. Else it returns true.
static bool checkMachOAndArchFlags(ObjectFile *O, StringRef Filename) {
auto *MachO = dyn_cast<MachOObjectFile>(O);
if (!MachO || ArchAll || ArchFlags.empty())
return true;
MachO::mach_header H;
MachO::mach_header_64 H_64;
Triple T;
const char *McpuDefault, *ArchFlag;
if (MachO->is64Bit()) {
H_64 = MachO->MachOObjectFile::getHeader64();
T = MachOObjectFile::getArchTriple(H_64.cputype, H_64.cpusubtype,
&McpuDefault, &ArchFlag);
} else {
H = MachO->MachOObjectFile::getHeader();
T = MachOObjectFile::getArchTriple(H.cputype, H.cpusubtype, &McpuDefault,
&ArchFlag);
}
const std::string ArchFlagName(ArchFlag);
if (none_of(ArchFlags,
[&](const std::string &Name) { return Name == ArchFlagName; })) {
errs() << "llvm-mctoll: " + Filename + ": No architecture specified.\n";
return false;
}
return true;
}
// ProcessMachO() is passed a single opened Mach-O file, which may be an
// archive member and or in a slice of a universal file. It prints the
// the file name and header info and then processes it according to the
// command line options.
static void ProcessMachO(StringRef Name, MachOObjectFile *MachOOF,
StringRef ArchiveMemberName = StringRef(),
StringRef ArchitectureName = StringRef()) {
if (Disassemble || (FilterSections.size() != 0)) {
if (!NoLeadingHeaders) {
outs() << Name;
if (!ArchiveMemberName.empty())
outs() << '(' << ArchiveMemberName << ')';
if (!ArchitectureName.empty())
outs() << " (architecture " << ArchitectureName << ")";
outs() << ":\n";
}
}
// To use the reportError() form with an ArchiveName and FileName set
// these up based on what is passed for Name and ArchiveMemberName.
StringRef ArchiveName;
StringRef FileName;
if (!ArchiveMemberName.empty()) {
ArchiveName = Name;
FileName = ArchiveMemberName;
} else {
ArchiveName = StringRef();
FileName = Name;
}
// If we need the symbol table to do the operation then check it here to
// produce a good error message as to where the Mach-O file comes from in
// the error message.
if (Disassemble || FilterSections.size() != 0)
if (Error Err = MachOOF->checkSymbolTable())
reportError(std::move(Err), ArchiveName, FileName, ArchitectureName);
if (Disassemble) {
if (MachOOF->getHeader().filetype == MachO::MH_KEXT_BUNDLE &&
MachOOF->getHeader().cputype == MachO::CPU_TYPE_ARM64)
DisassembleMachO(FileName, MachOOF, "__TEXT_EXEC", "__text");
else
DisassembleMachO(FileName, MachOOF, "__TEXT", "__text");
}
if (FilterSections.size() != 0)
DumpSectionContents(FileName, MachOOF, !NonVerbose);
}
// ParseInputMachO() parses the named Mach-O file in Filename and handles the
// -arch flags selecting just those slices as specified by them and also parses
// archive files. Then for each individual Mach-O file ProcessMachO() is
// called to process the file based on the command line options.
void mctoll::parseInputMachO(StringRef Filename) {
// Check for -arch all and verifiy the -arch flags are valid.
for (unsigned i = 0; i < ArchFlags.size(); ++i) {
if (ArchFlags[i] == "all") {
ArchAll = true;
} else {
if (!MachOObjectFile::isValidArch(ArchFlags[i])) {
errs() << "llvm-mctoll: Unknown architecture named '" + ArchFlags[i] +
"'for the -arch option\n";
return;
}
}
}
// Attempt to open the binary.
Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(Filename);
if (!BinaryOrErr) {
if (auto E = isNotObjectErrorInvalidFileType(BinaryOrErr.takeError()))
reportError(std::move(E), Filename);
else
outs() << Filename << ": is not an object file\n";
return;
}
Binary &Bin = *BinaryOrErr.get().getBinary();
if (Archive *A = dyn_cast<Archive>(&Bin)) {
outs() << "Archive : " << Filename << "\n";
Error Err = Error::success();
for (auto &C : A->children(Err)) {
Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
if (!ChildOrErr) {
if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
reportError(std::move(E), Filename, C);
continue;
}
if (MachOObjectFile *O = dyn_cast<MachOObjectFile>(&*ChildOrErr.get())) {
if (!checkMachOAndArchFlags(O, Filename))
return;
ProcessMachO(Filename, O, O->getFileName());
}
}
if (Err)
reportError(std::move(Err), Filename);
return;
}
if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Bin)) {
// If we have a list of architecture flags specified dump only those.
if (!ArchAll && ArchFlags.size() != 0) {
// Look for a slice in the universal binary that matches each ArchFlag.
bool ArchFound;
for (unsigned i = 0; i < ArchFlags.size(); ++i) {
ArchFound = false;
for (MachOUniversalBinary::object_iterator I = UB->begin_objects(),
E = UB->end_objects();
I != E; ++I) {
if (ArchFlags[i] == I->getArchFlagName()) {
ArchFound = true;
Expected<std::unique_ptr<ObjectFile>> ObjOrErr =
I->getAsObjectFile();
std::string ArchitectureName = "";
if (ArchFlags.size() > 1)
ArchitectureName = I->getArchFlagName();
if (ObjOrErr) {
ObjectFile &O = *ObjOrErr.get();
if (MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(&O))
ProcessMachO(Filename, MachOOF, "", ArchitectureName);
} else if (auto E = isNotObjectErrorInvalidFileType(
ObjOrErr.takeError())) {
reportError(std::move(E), Filename, StringRef(),
ArchitectureName);
continue;
} else if (Expected<std::unique_ptr<Archive>> AOrErr =
I->getAsArchive()) {
std::unique_ptr<Archive> &A = *AOrErr;
outs() << "Archive : " << Filename;
if (!ArchitectureName.empty())
outs() << " (architecture " << ArchitectureName << ")";
outs() << "\n";
Error Err = Error::success();
for (auto &C : A->children(Err)) {
Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
if (!ChildOrErr) {
if (auto E = isNotObjectErrorInvalidFileType(
ChildOrErr.takeError()))
reportError(std::move(E), Filename, C, ArchitectureName);
continue;
}
if (MachOObjectFile *O =
dyn_cast<MachOObjectFile>(&*ChildOrErr.get()))
ProcessMachO(Filename, O, O->getFileName(), ArchitectureName);
}
if (Err)
reportError(std::move(Err), Filename);
} else {
consumeError(AOrErr.takeError());
error("Mach-O universal file: " + Filename + " for " +
"architecture " + StringRef(I->getArchFlagName()) +
" is not a Mach-O file or an archive file");
}
}
}
if (!ArchFound) {
errs() << "llvm-mctoll: file: " + Filename + " does not contain "
<< "architecture: " + ArchFlags[i] + "\n";
return;
}
}
return;