macho-dump: Add support for dumping string table data.
[oota-llvm.git] / tools / macho-dump / macho-dump.cpp
1 //===-- macho-dump.cpp - Mach Object Dumping Tool -------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This is a testing tool for use with the MC/Mach-O LLVM components.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Object/MachOObject.h"
15 #include "llvm/ADT/Twine.h"
16 #include "llvm/Support/CommandLine.h"
17 #include "llvm/Support/Format.h"
18 #include "llvm/Support/ManagedStatic.h"
19 #include "llvm/Support/MemoryBuffer.h"
20 #include "llvm/Support/raw_ostream.h"
21 using namespace llvm;
22 using namespace llvm::object;
23
24 static cl::opt<std::string>
25 InputFile(cl::Positional, cl::desc("<input file>"), cl::init("-"));
26
27 static cl::opt<bool>
28 ShowSectionData("dump-section-data", cl::desc("Dump the contents of sections"),
29                 cl::init(false));
30
31 ///
32
33 static const char *ProgramName;
34
35 static void Message(const char *Type, const Twine &Msg) {
36   errs() << ProgramName << ": " << Type << ": " << Msg << "\n";
37 }
38
39 static int Error(const Twine &Msg) {
40   Message("error", Msg);
41   return 1;
42 }
43
44 static void Warning(const Twine &Msg) {
45   Message("warning", Msg);
46 }
47
48 ///
49
50 static int DumpHeader(MachOObject &Obj) {
51   // Read the header.
52   const macho::Header &Hdr = Obj.getHeader();
53   outs() << "('cputype', " << Hdr.CPUType << ")\n";
54   outs() << "('cpusubtype', " << Hdr.CPUSubtype << ")\n";
55   outs() << "('filetype', " << Hdr.FileType << ")\n";
56   outs() << "('num_load_commands', " << Hdr.NumLoadCommands << ")\n";
57   outs() << "('load_commands_size', " << Hdr.SizeOfLoadCommands << ")\n";
58   outs() << "('flag', " << Hdr.Flags << ")\n";
59
60   // Print extended header if 64-bit.
61   if (Obj.is64Bit()) {
62     const macho::Header64Ext &Hdr64 = Obj.getHeader64Ext();
63     outs() << "('reserved', " << Hdr64.Reserved << ")\n";
64   }
65
66   return 0;
67 }
68
69 static void DumpSegmentCommandData(StringRef Name,
70                                    uint64_t VMAddr, uint64_t VMSize,
71                                    uint64_t FileOffset, uint64_t FileSize,
72                                    uint32_t MaxProt, uint32_t InitProt,
73                                    uint32_t NumSections, uint32_t Flags) {
74   outs() << "  ('segment_name', '";
75   outs().write_escaped(Name, /*UseHexEscapes=*/true) << "')\n";
76   outs() << "  ('vm_addr', " << VMAddr << ")\n";
77   outs() << "  ('vm_size', " << VMSize << ")\n";
78   outs() << "  ('file_offset', " << FileOffset << ")\n";
79   outs() << "  ('file_size', " << FileSize << ")\n";
80   outs() << "  ('maxprot', " << MaxProt << ")\n";
81   outs() << "  ('initprot', " << InitProt << ")\n";
82   outs() << "  ('num_sections', " << NumSections << ")\n";
83   outs() << "  ('flags', " << Flags << ")\n";
84 }
85
86 static int DumpSectionData(MachOObject &Obj, unsigned Index, StringRef Name,
87                            StringRef SegmentName, uint64_t Address,
88                            uint64_t Size, uint32_t Offset,
89                            uint32_t Align, uint32_t RelocationTableOffset,
90                            uint32_t NumRelocationTableEntries,
91                            uint32_t Flags, uint32_t Reserved1,
92                            uint32_t Reserved2, uint64_t Reserved3 = ~0ULL) {
93   outs() << "    # Section " << Index << "\n";
94   outs() << "   (('section_name', '";
95   outs().write_escaped(Name, /*UseHexEscapes=*/true) << "')\n";
96   outs() << "    ('segment_name', '";
97   outs().write_escaped(SegmentName, /*UseHexEscapes=*/true) << "')\n";
98   outs() << "    ('address', " << Address << ")\n";
99   outs() << "    ('size', " << Size << ")\n";
100   outs() << "    ('offset', " << Offset << ")\n";
101   outs() << "    ('alignment', " << Align << ")\n";
102   outs() << "    ('reloc_offset', " << RelocationTableOffset << ")\n";
103   outs() << "    ('num_reloc', " << NumRelocationTableEntries << ")\n";
104   outs() << "    ('flags', " << format("%#x", Flags) << ")\n";
105   outs() << "    ('reserved1', " << Reserved1 << ")\n";
106   outs() << "    ('reserved2', " << Reserved2 << ")\n";
107   if (Reserved3 != ~0ULL)
108     outs() << "    ('reserved3', " << Reserved3 << ")\n";
109   outs() << "   ),\n";
110
111   // Dump the relocation entries.
112   int Res = 0;
113   outs() << "  ('_relocations', [\n";
114   for (unsigned i = 0; i != NumRelocationTableEntries; ++i) {
115     InMemoryStruct<macho::RelocationEntry> RE;
116     Obj.ReadRelocationEntry(RelocationTableOffset, i, RE);
117     if (!RE) {
118       Res = Error("unable to read relocation table entry '" + Twine(i) + "'");
119       break;
120     }
121     
122     outs() << "    # Relocation " << i << "\n";
123     outs() << "    (('word-0', " << format("%#x", RE->Word0) << "),\n";
124     outs() << "     ('word-1', " << format("%#x", RE->Word1) << ")),\n";
125   }
126   outs() << "  ])\n";
127
128   return Res;
129 }
130
131 static int DumpSegmentCommand(MachOObject &Obj,
132                                const MachOObject::LoadCommandInfo &LCI) {
133   InMemoryStruct<macho::SegmentLoadCommand> SLC;
134   Obj.ReadSegmentLoadCommand(LCI, SLC);
135   if (!SLC)
136     return Error("unable to read segment load command");
137
138   DumpSegmentCommandData(StringRef(SLC->Name, 16), SLC->VMAddress,
139                          SLC->VMSize, SLC->FileOffset, SLC->FileSize,
140                          SLC->MaxVMProtection, SLC->InitialVMProtection,
141                          SLC->NumSections, SLC->Flags);
142
143   // Dump the sections.
144   int Res = 0;
145   outs() << "  ('sections', [\n";
146   for (unsigned i = 0; i != SLC->NumSections; ++i) {
147     InMemoryStruct<macho::Section> Sect;
148     Obj.ReadSection(LCI, i, Sect);
149     if (!SLC) {
150       Res = Error("unable to read section '" + Twine(i) + "'");
151       break;
152     }
153
154     if ((Res = DumpSectionData(Obj, i, StringRef(Sect->Name, 16),
155                                StringRef(Sect->SegmentName, 16), Sect->Address,
156                                Sect->Size, Sect->Offset, Sect->Align,
157                                Sect->RelocationTableOffset,
158                                Sect->NumRelocationTableEntries, Sect->Flags,
159                                Sect->Reserved1, Sect->Reserved2)))
160       break;
161   }
162   outs() << "  ])\n";
163
164   return Res;
165 }
166
167 static int DumpSegment64Command(MachOObject &Obj,
168                                const MachOObject::LoadCommandInfo &LCI) {
169   InMemoryStruct<macho::Segment64LoadCommand> SLC;
170   Obj.ReadSegment64LoadCommand(LCI, SLC);
171   if (!SLC)
172     return Error("unable to read segment load command");
173
174   DumpSegmentCommandData(StringRef(SLC->Name, 16), SLC->VMAddress,
175                          SLC->VMSize, SLC->FileOffset, SLC->FileSize,
176                          SLC->MaxVMProtection, SLC->InitialVMProtection,
177                          SLC->NumSections, SLC->Flags);
178
179   // Dump the sections.
180   int Res = 0;
181   outs() << "  ('sections', [\n";
182   for (unsigned i = 0; i != SLC->NumSections; ++i) {
183     InMemoryStruct<macho::Section64> Sect;
184     Obj.ReadSection64(LCI, i, Sect);
185     if (!SLC) {
186       Res = Error("unable to read section '" + Twine(i) + "'");
187       break;
188     }
189
190     if ((Res = DumpSectionData(Obj, i, StringRef(Sect->Name, 16),
191                                StringRef(Sect->SegmentName, 16), Sect->Address,
192                                Sect->Size, Sect->Offset, Sect->Align,
193                                Sect->RelocationTableOffset,
194                                Sect->NumRelocationTableEntries, Sect->Flags,
195                                Sect->Reserved1, Sect->Reserved2,
196                                Sect->Reserved3)))
197       break;
198   }
199   outs() << "  ])\n";
200
201   return 0;
202 }
203
204 static int DumpSymtabCommand(MachOObject &Obj,
205                              const MachOObject::LoadCommandInfo &LCI) {
206   InMemoryStruct<macho::SymtabLoadCommand> SLC;
207   Obj.ReadSymtabLoadCommand(LCI, SLC);
208   if (!SLC)
209     return Error("unable to read segment load command");
210
211   outs() << "  ('symoff', " << SLC->SymbolTableOffset << ")\n";
212   outs() << "  ('nsyms', " << SLC->NumSymbolTableEntries << ")\n";
213   outs() << "  ('stroff', " << SLC->StringTableOffset << ")\n";
214   outs() << "  ('strsize', " << SLC->StringTableSize << ")\n";
215
216   // Cache the string table data.
217   Obj.RegisterStringTable(*SLC);
218
219   // Dump the string data.
220   outs() << "  ('_string_data', '";
221   outs().write_escaped(Obj.getStringTableData(),
222                        /*UseHexEscapes=*/true) << "')\n";
223
224   return 0;
225 }
226
227 static int DumpDysymtabCommand(MachOObject &Obj,
228                              const MachOObject::LoadCommandInfo &LCI) {
229   InMemoryStruct<macho::DysymtabLoadCommand> DLC;
230   Obj.ReadDysymtabLoadCommand(LCI, DLC);
231   if (!DLC)
232     return Error("unable to read segment load command");
233
234   outs() << "  ('ilocalsym', " << DLC->LocalSymbolIndex << ")\n";
235   outs() << "  ('nlocalsym', " << DLC->NumLocalSymbols << ")\n";
236   outs() << "  ('iextdefsym', " << DLC->ExternalSymbolsIndex << ")\n";
237   outs() << "  ('nextdefsym', " << DLC->NumExternalSymbols << ")\n";
238   outs() << "  ('iundefsym', " << DLC->UndefinedSymbolsIndex << ")\n";
239   outs() << "  ('nundefsym', " << DLC->NumUndefinedSymbols << ")\n";
240   outs() << "  ('tocoff', " << DLC->TOCOffset << ")\n";
241   outs() << "  ('ntoc', " << DLC->NumTOCEntries << ")\n";
242   outs() << "  ('modtaboff', " << DLC->ModuleTableOffset << ")\n";
243   outs() << "  ('nmodtab', " << DLC->NumModuleTableEntries << ")\n";
244   outs() << "  ('extrefsymoff', " << DLC->ReferenceSymbolTableOffset << ")\n";
245   outs() << "  ('nextrefsyms', "
246          << DLC->NumReferencedSymbolTableEntries << ")\n";
247   outs() << "  ('indirectsymoff', " << DLC->IndirectSymbolTableOffset << ")\n";
248   outs() << "  ('nindirectsyms', "
249          << DLC->NumIndirectSymbolTableEntries << ")\n";
250   outs() << "  ('extreloff', " << DLC->ExternalRelocationTableOffset << ")\n";
251   outs() << "  ('nextrel', " << DLC->NumExternalRelocationTableEntries << ")\n";
252   outs() << "  ('locreloff', " << DLC->LocalRelocationTableOffset << ")\n";
253   outs() << "  ('nlocrel', " << DLC->NumLocalRelocationTableEntries << ")\n";
254
255   // Dump the indirect symbol table.
256   int Res = 0;
257   outs() << "  ('_indirect_symbols', [\n";
258   for (unsigned i = 0; i != DLC->NumIndirectSymbolTableEntries; ++i) {
259     InMemoryStruct<macho::IndirectSymbolTableEntry> ISTE;
260     Obj.ReadIndirectSymbolTableEntry(*DLC, i, ISTE);
261     if (!ISTE) {
262       Res = Error("unable to read segment load command");
263       break;
264     }
265
266     outs() << "    # Indirect Symbol " << i << "\n";
267     outs() << "    (('symbol_index', "
268            << format("%#x", ISTE->Index) << "),),\n";
269   }
270   outs() << "  ])\n";
271
272   return Res;
273 }
274
275 static int DumpLoadCommand(MachOObject &Obj, unsigned Index) {
276   const MachOObject::LoadCommandInfo &LCI = Obj.getLoadCommandInfo(Index);
277   int Res = 0;
278
279   outs() << "  # Load Command " << Index << "\n"
280          << " (('command', " << LCI.Command.Type << ")\n"
281          << "  ('size', " << LCI.Command.Size << ")\n";
282   switch (LCI.Command.Type) {
283   case macho::LCT_Segment:
284     Res = DumpSegmentCommand(Obj, LCI);
285     break;
286   case macho::LCT_Segment64:
287     Res = DumpSegment64Command(Obj, LCI);
288     break;
289   case macho::LCT_Symtab:
290     Res = DumpSymtabCommand(Obj, LCI);
291     break;
292   case macho::LCT_Dysymtab:
293     Res = DumpDysymtabCommand(Obj, LCI);
294     break;
295   default:
296     Warning("unknown load command: " + Twine(LCI.Command.Type));
297     break;
298   }
299   outs() << " ),\n";
300
301   return Res;
302 }
303
304 int main(int argc, char **argv) {
305   ProgramName = argv[0];
306   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
307
308   cl::ParseCommandLineOptions(argc, argv, "llvm Mach-O dumping tool\n");
309
310   // Load the input file.
311   std::string ErrorStr;
312   OwningPtr<MemoryBuffer> InputBuffer(
313     MemoryBuffer::getFileOrSTDIN(InputFile, &ErrorStr));
314   if (!InputBuffer)
315     return Error("unable to read input: '" + ErrorStr + "'");
316
317   // Construct the Mach-O wrapper object.
318   OwningPtr<MachOObject> InputObject(
319     MachOObject::LoadFromBuffer(InputBuffer.take(), &ErrorStr));
320   if (!InputObject)
321     return Error("unable to load object: '" + ErrorStr + "'");
322
323   if (int Res = DumpHeader(*InputObject))
324     return Res;
325
326   // Print the load commands.
327   int Res = 0;
328   outs() << "('load_commands', [\n";
329   for (unsigned i = 0; i != InputObject->getHeader().NumLoadCommands; ++i)
330     if ((Res = DumpLoadCommand(*InputObject, i)))
331       break;
332   outs() << "])\n";
333
334   return Res;
335 }