blob: 2e167f4be2b464f342a442df7b6157d1f04d5f53 [file] [log] [blame]
Michael J. Spencer92e1deb2011-01-20 06:39:06 +00001//===-- llvm-objdump.cpp - Object file dumping utility for llvm -----------===//
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 program is a utility that works like binutils "objdump", that is, it
11// dumps out a plethora of information about an object file depending on the
12// flags.
13//
14//===----------------------------------------------------------------------===//
15
Benjamin Kramer0b8b7712011-09-19 17:56:04 +000016#include "llvm-objdump.h"
Benjamin Kramer685a2502011-07-20 19:37:35 +000017#include "MCFunction.h"
Michael J. Spencer27781b72011-10-08 00:18:30 +000018#include "llvm/Object/Archive.h"
Michael J. Spencer22ff0f32011-10-18 19:32:17 +000019#include "llvm/Object/COFF.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000020#include "llvm/Object/ObjectFile.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000021#include "llvm/ADT/OwningPtr.h"
Michael J. Spencer1e8ba3f2011-10-17 17:13:22 +000022#include "llvm/ADT/StringExtras.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000023#include "llvm/ADT/Triple.h"
Benjamin Kramer739b65b2011-07-15 18:39:24 +000024#include "llvm/ADT/STLExtras.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000025#include "llvm/MC/MCAsmInfo.h"
Owen Andersonf1b74482011-10-27 21:46:31 +000026#include "llvm/MC/MCContext.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000027#include "llvm/MC/MCDisassembler.h"
28#include "llvm/MC/MCInst.h"
29#include "llvm/MC/MCInstPrinter.h"
Owen Andersonf1b74482011-10-27 21:46:31 +000030#include "llvm/MC/MCRegisterInfo.h"
James Molloyb9505852011-09-07 17:24:38 +000031#include "llvm/MC/MCSubtargetInfo.h"
Michael J. Spencer27781b72011-10-08 00:18:30 +000032#include "llvm/Support/Casting.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000033#include "llvm/Support/CommandLine.h"
34#include "llvm/Support/Debug.h"
Michael J. Spencer27781b72011-10-08 00:18:30 +000035#include "llvm/Support/FileSystem.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000036#include "llvm/Support/Format.h"
Benjamin Kramer853b0fd2011-07-25 23:04:36 +000037#include "llvm/Support/GraphWriter.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000038#include "llvm/Support/Host.h"
39#include "llvm/Support/ManagedStatic.h"
40#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000041#include "llvm/Support/MemoryObject.h"
42#include "llvm/Support/PrettyStackTrace.h"
43#include "llvm/Support/Signals.h"
44#include "llvm/Support/SourceMgr.h"
Evan Cheng3e74d6f2011-08-24 18:08:43 +000045#include "llvm/Support/TargetRegistry.h"
46#include "llvm/Support/TargetSelect.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000047#include "llvm/Support/raw_ostream.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000048#include "llvm/Support/system_error.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000049#include <algorithm>
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000050#include <cstring>
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000051using namespace llvm;
52using namespace object;
53
Benjamin Kramer0b8b7712011-09-19 17:56:04 +000054static cl::list<std::string>
55InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000056
Benjamin Kramer0b8b7712011-09-19 17:56:04 +000057static cl::opt<bool>
58Disassemble("disassemble",
59 cl::desc("Display assembler mnemonics for the machine instructions"));
60static cl::alias
61Disassembled("d", cl::desc("Alias for --disassemble"),
62 cl::aliasopt(Disassemble));
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000063
Benjamin Kramer0b8b7712011-09-19 17:56:04 +000064static cl::opt<bool>
Michael J. Spencer27781b72011-10-08 00:18:30 +000065Relocations("r", cl::desc("Display the relocation entries in the file"));
66
67static cl::opt<bool>
Michael J. Spencer1e8ba3f2011-10-17 17:13:22 +000068SectionContents("s", cl::desc("Display the content of each section"));
69
70static cl::opt<bool>
Michael J. Spencer22ff0f32011-10-18 19:32:17 +000071SymbolTable("t", cl::desc("Display the symbol table"));
72
73static cl::opt<bool>
Benjamin Kramer0b8b7712011-09-19 17:56:04 +000074MachO("macho", cl::desc("Use MachO specific object file parser"));
75static cl::alias
76MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachO));
Benjamin Kramer685a2502011-07-20 19:37:35 +000077
Benjamin Kramer0b8b7712011-09-19 17:56:04 +000078cl::opt<std::string>
79llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
80 "see -version for available targets"));
81
82cl::opt<std::string>
83llvm::ArchName("arch", cl::desc("Target arch to disassemble for, "
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000084 "see -version for available targets"));
85
Nick Lewycky023bb152011-10-10 21:21:34 +000086static cl::opt<bool>
87SectionHeaders("section-headers", cl::desc("Display summaries of the headers "
88 "for each section."));
89static cl::alias
90SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
91 cl::aliasopt(SectionHeaders));
92static cl::alias
93SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
94 cl::aliasopt(SectionHeaders));
95
Benjamin Kramer0b8b7712011-09-19 17:56:04 +000096static StringRef ToolName;
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000097
Benjamin Kramer0b8b7712011-09-19 17:56:04 +000098static bool error(error_code ec) {
99 if (!ec) return false;
Michael J. Spencer25b15772011-06-25 17:55:23 +0000100
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000101 outs() << ToolName << ": error reading file: " << ec.message() << ".\n";
102 outs().flush();
103 return true;
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000104}
105
106static const Target *GetTarget(const ObjectFile *Obj = NULL) {
107 // Figure out the target triple.
108 llvm::Triple TT("unknown-unknown-unknown");
Michael J. Spencerd11699d2011-01-20 07:22:04 +0000109 if (TripleName.empty()) {
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000110 if (Obj)
111 TT.setArch(Triple::ArchType(Obj->getArch()));
Michael J. Spencerd11699d2011-01-20 07:22:04 +0000112 } else
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000113 TT.setTriple(Triple::normalize(TripleName));
114
115 if (!ArchName.empty())
116 TT.setArchName(ArchName);
117
118 TripleName = TT.str();
119
120 // Get the target specific parser.
121 std::string Error;
122 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
123 if (TheTarget)
124 return TheTarget;
125
126 errs() << ToolName << ": error: unable to get target for '" << TripleName
127 << "', see --version and --triple.\n";
128 return 0;
129}
130
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000131void llvm::DumpBytes(StringRef bytes) {
132 static const char hex_rep[] = "0123456789abcdef";
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000133 // FIXME: The real way to do this is to figure out the longest instruction
134 // and align to that size before printing. I'll fix this when I get
135 // around to outputting relocations.
136 // 15 is the longest x86 instruction
137 // 3 is for the hex rep of a byte + a space.
138 // 1 is for the null terminator.
139 enum { OutputSize = (15 * 3) + 1 };
140 char output[OutputSize];
141
142 assert(bytes.size() <= 15
143 && "DumpBytes only supports instructions of up to 15 bytes");
144 memset(output, ' ', sizeof(output));
145 unsigned index = 0;
146 for (StringRef::iterator i = bytes.begin(),
147 e = bytes.end(); i != e; ++i) {
148 output[index] = hex_rep[(*i & 0xF0) >> 4];
149 output[index + 1] = hex_rep[*i & 0xF];
150 index += 3;
151 }
152
153 output[sizeof(output) - 1] = 0;
154 outs() << output;
155}
156
Michael J. Spencer942eb002011-10-13 22:17:18 +0000157static bool RelocAddressLess(RelocationRef a, RelocationRef b) {
158 uint64_t a_addr, b_addr;
159 if (error(a.getAddress(a_addr))) return false;
160 if (error(b.getAddress(b_addr))) return false;
161 return a_addr < b_addr;
162}
163
Owen Andersonf1b74482011-10-27 21:46:31 +0000164// OperandInfoCallback - Callback from the MCDisassembler to perform
165// relocation resolution for operands while disassembling.
166int OperandInfoCallback(void *ObjectFile, uint64_t PC, uint64_t Offset,
167 uint64_t Size, int TagType, void *TagBuf) {
168 LLVMOpInfo1 *OpInfo = static_cast<LLVMOpInfo1*>(TagBuf);
169 OpInfo->AddSymbol.Present = 0;
170 OpInfo->SubtractSymbol.Present = 0;
171 OpInfo->VariantKind = LLVMDisassembler_VariantKind_None;
172
173 return 0;
174}
175
176// SymbolLookupCallback - Callback from the MCDisassembler to convert
177// offsets to symbolic references while disassembling.
178const char* SymbolLookupCallback(void *ObjectFile, uint64_t ReferenceValue,
179 uint64_t *ReferenceType, uint64_t PC,
180 const char **ReferenceName) {
181 *ReferenceType = LLVMDisassembler_ReferenceType_InOut_None;
182 return 0;
183}
184
Michael J. Spencer942eb002011-10-13 22:17:18 +0000185static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
Michael J. Spencer27781b72011-10-08 00:18:30 +0000186 const Target *TheTarget = GetTarget(Obj);
Owen Andersonf1b74482011-10-27 21:46:31 +0000187
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000188 if (!TheTarget) {
189 // GetTarget prints out stuff.
190 return;
191 }
192
Michael J. Spencer25b15772011-06-25 17:55:23 +0000193 error_code ec;
Michael J. Spencer4344b1e2011-10-07 19:25:32 +0000194 for (section_iterator i = Obj->begin_sections(),
Michael J. Spencer27781b72011-10-08 00:18:30 +0000195 e = Obj->end_sections();
196 i != e; i.increment(ec)) {
Michael J. Spencer25b15772011-06-25 17:55:23 +0000197 if (error(ec)) break;
198 bool text;
199 if (error(i->isText(text))) break;
200 if (!text) continue;
201
Michael J. Spencer942eb002011-10-13 22:17:18 +0000202 uint64_t SectionAddr;
203 if (error(i->getAddress(SectionAddr))) break;
204
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000205 // Make a list of all the symbols in this section.
206 std::vector<std::pair<uint64_t, StringRef> > Symbols;
Michael J. Spencer4344b1e2011-10-07 19:25:32 +0000207 for (symbol_iterator si = Obj->begin_symbols(),
Michael J. Spencer27781b72011-10-08 00:18:30 +0000208 se = Obj->end_symbols();
209 si != se; si.increment(ec)) {
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000210 bool contains;
211 if (!error(i->containsSymbol(*si, contains)) && contains) {
212 uint64_t Address;
Benjamin Kramerac241fe2011-09-14 01:22:52 +0000213 if (error(si->getOffset(Address))) break;
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000214 StringRef Name;
215 if (error(si->getName(Name))) break;
216 Symbols.push_back(std::make_pair(Address, Name));
217 }
218 }
219
220 // Sort the symbols by address, just in case they didn't come in that way.
221 array_pod_sort(Symbols.begin(), Symbols.end());
222
Michael J. Spencer942eb002011-10-13 22:17:18 +0000223 // Make a list of all the relocations for this section.
224 std::vector<RelocationRef> Rels;
225 if (InlineRelocs) {
226 for (relocation_iterator ri = i->begin_relocations(),
227 re = i->end_relocations();
228 ri != re; ri.increment(ec)) {
229 if (error(ec)) break;
230 Rels.push_back(*ri);
231 }
232 }
233
234 // Sort relocations by address.
235 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
236
Michael J. Spencer25b15772011-06-25 17:55:23 +0000237 StringRef name;
238 if (error(i->getName(name))) break;
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000239 outs() << "Disassembly of section " << name << ':';
240
241 // If the section has no symbols just insert a dummy one and disassemble
242 // the whole section.
243 if (Symbols.empty())
244 Symbols.push_back(std::make_pair(0, name));
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000245
246 // Set up disassembler.
Evan Cheng1abf2cb2011-07-14 23:50:31 +0000247 OwningPtr<const MCAsmInfo> AsmInfo(TheTarget->createMCAsmInfo(TripleName));
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000248
249 if (!AsmInfo) {
250 errs() << "error: no assembly info for target " << TripleName << "\n";
251 return;
252 }
253
Owen Andersonf1b74482011-10-27 21:46:31 +0000254 OwningPtr<const MCRegisterInfo>
255 RegInfo(TheTarget->createMCRegInfo(TripleName));
256
257 if (!RegInfo) {
258 errs() << "error: no register info for target " << TripleName << "\n";
259 return;
260 }
261
Michael J. Spencer27781b72011-10-08 00:18:30 +0000262 OwningPtr<const MCSubtargetInfo> STI(
263 TheTarget->createMCSubtargetInfo(TripleName, "", ""));
James Molloyb9505852011-09-07 17:24:38 +0000264
265 if (!STI) {
266 errs() << "error: no subtarget info for target " << TripleName << "\n";
267 return;
268 }
269
Owen Andersonf1b74482011-10-27 21:46:31 +0000270 MCContext Context(*AsmInfo, *RegInfo, 0);
271 OwningPtr<MCDisassembler> DisAsm(
Michael J. Spencer27781b72011-10-08 00:18:30 +0000272 TheTarget->createMCDisassembler(*STI));
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000273 if (!DisAsm) {
274 errs() << "error: no disassembler for target " << TripleName << "\n";
275 return;
276 }
277
Owen Andersonf1b74482011-10-27 21:46:31 +0000278 // Setup the disassembler for symbolic decoding.
279 DisAsm->setupForSymbolicDisassembly(OperandInfoCallback,
280 SymbolLookupCallback,
281 const_cast<ObjectFile*>(Obj),
282 &Context);
283
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000284 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
285 OwningPtr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
James Molloyb9505852011-09-07 17:24:38 +0000286 AsmPrinterVariant, *AsmInfo, *STI));
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000287 if (!IP) {
Michael J. Spencer27781b72011-10-08 00:18:30 +0000288 errs() << "error: no instruction printer for target " << TripleName
289 << '\n';
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000290 return;
291 }
292
Michael J. Spencer25b15772011-06-25 17:55:23 +0000293 StringRef Bytes;
294 if (error(i->getContents(Bytes))) break;
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000295 StringRefMemoryObject memoryObject(Bytes);
296 uint64_t Size;
297 uint64_t Index;
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000298 uint64_t SectSize;
299 if (error(i->getSize(SectSize))) break;
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000300
Michael J. Spencer942eb002011-10-13 22:17:18 +0000301 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
302 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000303 // Disassemble symbol by symbol.
304 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
305 uint64_t Start = Symbols[si].first;
Michael J. Spencer178dbd42011-10-13 20:37:08 +0000306 uint64_t End;
307 // The end is either the size of the section or the beginning of the next
308 // symbol.
309 if (si == se - 1)
310 End = SectSize;
311 // Make sure this symbol takes up space.
312 else if (Symbols[si + 1].first != Start)
313 End = Symbols[si + 1].first - 1;
314 else
315 // This symbol has the same address as the next symbol. Skip it.
316 continue;
317
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000318 outs() << '\n' << Symbols[si].second << ":\n";
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000319
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000320#ifndef NDEBUG
321 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
322#else
323 raw_ostream &DebugOut = nulls();
324#endif
325
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000326 for (Index = Start; Index < End; Index += Size) {
327 MCInst Inst;
Owen Anderson98c5dda2011-09-15 23:38:46 +0000328
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000329 if (DisAsm->getInstruction(Inst, Size, memoryObject, Index,
330 DebugOut, nulls())) {
Owen Andersonf1b74482011-10-27 21:46:31 +0000331 outs() << format("%8x:\t", SectionAddr + Index);
Benjamin Kramer0b8b7712011-09-19 17:56:04 +0000332 DumpBytes(StringRef(Bytes.data() + Index, Size));
333 IP->printInst(&Inst, outs(), "");
334 outs() << "\n";
335 } else {
336 errs() << ToolName << ": warning: invalid instruction encoding\n";
337 if (Size == 0)
338 Size = 1; // skip illegible bytes
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000339 }
Michael J. Spencer942eb002011-10-13 22:17:18 +0000340
341 // Print relocation for instruction.
342 while (rel_cur != rel_end) {
Owen Anderson0685e942011-10-25 20:35:53 +0000343 bool hidden = false;
Michael J. Spencer942eb002011-10-13 22:17:18 +0000344 uint64_t addr;
345 SmallString<16> name;
346 SmallString<32> val;
Owen Anderson0685e942011-10-25 20:35:53 +0000347
348 // If this relocation is hidden, skip it.
349 if (error(rel_cur->getHidden(hidden))) goto skip_print_rel;
350 if (hidden) goto skip_print_rel;
351
Michael J. Spencer942eb002011-10-13 22:17:18 +0000352 if (error(rel_cur->getAddress(addr))) goto skip_print_rel;
353 // Stop when rel_cur's address is past the current instruction.
Owen Anderson34749ce2011-10-25 20:15:39 +0000354 if (addr >= Index + Size) break;
Michael J. Spencer942eb002011-10-13 22:17:18 +0000355 if (error(rel_cur->getTypeName(name))) goto skip_print_rel;
356 if (error(rel_cur->getValueString(val))) goto skip_print_rel;
357
Owen Andersonf1b74482011-10-27 21:46:31 +0000358 outs() << format("\t\t\t%8x: ", SectionAddr + addr) << name << "\t"
Michael J. Spencer942eb002011-10-13 22:17:18 +0000359 << val << "\n";
360
361 skip_print_rel:
362 ++rel_cur;
363 }
Benjamin Kramer685a2502011-07-20 19:37:35 +0000364 }
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000365 }
366 }
367}
368
Michael J. Spencer27781b72011-10-08 00:18:30 +0000369static void PrintRelocations(const ObjectFile *o) {
370 error_code ec;
371 for (section_iterator si = o->begin_sections(), se = o->end_sections();
372 si != se; si.increment(ec)){
373 if (error(ec)) return;
374 if (si->begin_relocations() == si->end_relocations())
375 continue;
376 StringRef secname;
377 if (error(si->getName(secname))) continue;
378 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
379 for (relocation_iterator ri = si->begin_relocations(),
380 re = si->end_relocations();
381 ri != re; ri.increment(ec)) {
382 if (error(ec)) return;
383
Owen Anderson0685e942011-10-25 20:35:53 +0000384 bool hidden;
Michael J. Spencer27781b72011-10-08 00:18:30 +0000385 uint64_t address;
386 SmallString<32> relocname;
387 SmallString<32> valuestr;
Owen Anderson0685e942011-10-25 20:35:53 +0000388 if (error(ri->getHidden(hidden))) continue;
389 if (hidden) continue;
Michael J. Spencer27781b72011-10-08 00:18:30 +0000390 if (error(ri->getTypeName(relocname))) continue;
391 if (error(ri->getAddress(address))) continue;
392 if (error(ri->getValueString(valuestr))) continue;
393 outs() << address << " " << relocname << " " << valuestr << "\n";
394 }
395 outs() << "\n";
396 }
397}
398
Nick Lewycky023bb152011-10-10 21:21:34 +0000399static void PrintSectionHeaders(const ObjectFile *o) {
400 outs() << "Sections:\n"
401 "Idx Name Size Address Type\n";
402 error_code ec;
403 unsigned i = 0;
404 for (section_iterator si = o->begin_sections(), se = o->end_sections();
405 si != se; si.increment(ec)) {
406 if (error(ec)) return;
407 StringRef Name;
408 if (error(si->getName(Name))) return;
409 uint64_t Address;
410 if (error(si->getAddress(Address))) return;
411 uint64_t Size;
412 if (error(si->getSize(Size))) return;
413 bool Text, Data, BSS;
414 if (error(si->isText(Text))) return;
415 if (error(si->isData(Data))) return;
416 if (error(si->isBSS(BSS))) return;
417 std::string Type = (std::string(Text ? "TEXT " : "") +
Michael J. Spencer14a5f462011-10-13 20:37:20 +0000418 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
NAKAMURA Takumif048c3f2011-10-11 12:51:50 +0000419 outs() << format("%3d %-13s %09"PRIx64" %017"PRIx64" %s\n", i, Name.str().c_str(), Size,
Nick Lewycky023bb152011-10-10 21:21:34 +0000420 Address, Type.c_str());
421 ++i;
422 }
423}
424
Michael J. Spencer1e8ba3f2011-10-17 17:13:22 +0000425static void PrintSectionContents(const ObjectFile *o) {
426 error_code ec;
427 for (section_iterator si = o->begin_sections(),
428 se = o->end_sections();
429 si != se; si.increment(ec)) {
430 if (error(ec)) return;
431 StringRef Name;
432 StringRef Contents;
433 uint64_t BaseAddr;
434 if (error(si->getName(Name))) continue;
435 if (error(si->getContents(Contents))) continue;
436 if (error(si->getAddress(BaseAddr))) continue;
437
438 outs() << "Contents of section " << Name << ":\n";
439
440 // Dump out the content as hex and printable ascii characters.
441 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
Owen Andersonf1b74482011-10-27 21:46:31 +0000442 outs() << format(" %04x ", BaseAddr + addr);
Michael J. Spencer1e8ba3f2011-10-17 17:13:22 +0000443 // Dump line of hex.
444 for (std::size_t i = 0; i < 16; ++i) {
445 if (i != 0 && i % 4 == 0)
446 outs() << ' ';
447 if (addr + i < end)
448 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
449 << hexdigit(Contents[addr + i] & 0xF, true);
450 else
451 outs() << " ";
452 }
453 // Print ascii.
454 outs() << " ";
455 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
456 if (std::isprint(Contents[addr + i] & 0xFF))
457 outs() << Contents[addr + i];
458 else
459 outs() << ".";
460 }
461 outs() << "\n";
462 }
463 }
464}
465
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000466static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
467 const coff_file_header *header;
468 if (error(coff->getHeader(header))) return;
469 int aux_count = 0;
470 const coff_symbol *symbol = 0;
471 for (int i = 0, e = header->NumberOfSymbols; i != e; ++i) {
472 if (aux_count--) {
473 // Figure out which type of aux this is.
474 if (symbol->StorageClass == COFF::IMAGE_SYM_CLASS_STATIC
475 && symbol->Value == 0) { // Section definition.
476 const coff_aux_section_definition *asd;
477 if (error(coff->getAuxSymbol<coff_aux_section_definition>(i, asd)))
478 return;
479 outs() << "AUX "
480 << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
481 , unsigned(asd->Length)
482 , unsigned(asd->NumberOfRelocations)
483 , unsigned(asd->NumberOfLinenumbers)
484 , unsigned(asd->CheckSum))
485 << format("assoc %d comdat %d\n"
486 , unsigned(asd->Number)
487 , unsigned(asd->Selection));
488 } else {
489 outs() << "AUX Unknown\n";
490 }
491 } else {
492 StringRef name;
493 if (error(coff->getSymbol(i, symbol))) return;
494 if (error(coff->getSymbolName(symbol, name))) return;
495 outs() << "[" << format("%2d", i) << "]"
496 << "(sec " << format("%2d", int(symbol->SectionNumber)) << ")"
497 << "(fl 0x00)" // Flag bits, which COFF doesn't have.
498 << "(ty " << format("%3x", unsigned(symbol->Type)) << ")"
499 << "(scl " << format("%3x", unsigned(symbol->StorageClass)) << ") "
500 << "(nx " << unsigned(symbol->NumberOfAuxSymbols) << ") "
501 << "0x" << format("%08x", unsigned(symbol->Value)) << " "
502 << name << "\n";
503 aux_count = symbol->NumberOfAuxSymbols;
504 }
505 }
506}
507
508static void PrintSymbolTable(const ObjectFile *o) {
509 outs() << "SYMBOL TABLE:\n";
510
511 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o))
512 PrintCOFFSymbolTable(coff);
513 else {
514 error_code ec;
515 for (symbol_iterator si = o->begin_symbols(),
516 se = o->end_symbols(); si != se; si.increment(ec)) {
517 if (error(ec)) return;
518 StringRef Name;
519 uint64_t Offset;
520 bool Global;
521 SymbolRef::Type Type;
522 bool Weak;
523 bool Absolute;
524 uint64_t Size;
525 section_iterator Section = o->end_sections();
526 if (error(si->getName(Name))) continue;
527 if (error(si->getOffset(Offset))) continue;
528 if (error(si->isGlobal(Global))) continue;
529 if (error(si->getType(Type))) continue;
530 if (error(si->isWeak(Weak))) continue;
531 if (error(si->isAbsolute(Absolute))) continue;
532 if (error(si->getSize(Size))) continue;
533 if (error(si->getSection(Section))) continue;
534
535 if (Offset == UnknownAddressOrSize)
536 Offset = 0;
537 char GlobLoc = ' ';
538 if (Type != SymbolRef::ST_External)
539 GlobLoc = Global ? 'g' : 'l';
540 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
541 ? 'd' : ' ';
542 char FileFunc = ' ';
543 if (Type == SymbolRef::ST_File)
544 FileFunc = 'f';
545 else if (Type == SymbolRef::ST_Function)
546 FileFunc = 'F';
547
Owen Andersonf1b74482011-10-27 21:46:31 +0000548 outs() << format("%08x", Offset) << " "
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000549 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
550 << (Weak ? 'w' : ' ') // Weak?
551 << ' ' // Constructor. Not supported yet.
552 << ' ' // Warning. Not supported yet.
553 << ' ' // Indirect reference to another symbol.
554 << Debug // Debugging (d) or dynamic (D) symbol.
555 << FileFunc // Name of function (F), file (f) or object (O).
556 << ' ';
557 if (Absolute)
558 outs() << "*ABS*";
559 else if (Section == o->end_sections())
560 outs() << "*UND*";
561 else {
562 StringRef SectionName;
563 if (error(Section->getName(SectionName)))
564 SectionName = "";
565 outs() << SectionName;
566 }
567 outs() << '\t'
Owen Andersonf1b74482011-10-27 21:46:31 +0000568 << format("%08x ", Size)
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000569 << Name
570 << '\n';
571 }
572 }
573}
574
Michael J. Spencer27781b72011-10-08 00:18:30 +0000575static void DumpObject(const ObjectFile *o) {
Michael J. Spencer1e8ba3f2011-10-17 17:13:22 +0000576 outs() << '\n';
577 outs() << o->getFileName()
578 << ":\tfile format " << o->getFileFormatName() << "\n\n";
579
Michael J. Spencer27781b72011-10-08 00:18:30 +0000580 if (Disassemble)
Michael J. Spencer942eb002011-10-13 22:17:18 +0000581 DisassembleObject(o, Relocations);
582 if (Relocations && !Disassemble)
Michael J. Spencer27781b72011-10-08 00:18:30 +0000583 PrintRelocations(o);
Nick Lewycky023bb152011-10-10 21:21:34 +0000584 if (SectionHeaders)
585 PrintSectionHeaders(o);
Michael J. Spencer1e8ba3f2011-10-17 17:13:22 +0000586 if (SectionContents)
587 PrintSectionContents(o);
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000588 if (SymbolTable)
589 PrintSymbolTable(o);
Michael J. Spencer27781b72011-10-08 00:18:30 +0000590}
591
592/// @brief Dump each object file in \a a;
593static void DumpArchive(const Archive *a) {
594 for (Archive::child_iterator i = a->begin_children(),
595 e = a->end_children(); i != e; ++i) {
596 OwningPtr<Binary> child;
597 if (error_code ec = i->getAsBinary(child)) {
598 errs() << ToolName << ": '" << a->getFileName() << "': " << ec.message()
599 << ".\n";
600 continue;
601 }
602 if (ObjectFile *o = dyn_cast<ObjectFile>(child.get()))
603 DumpObject(o);
604 else
605 errs() << ToolName << ": '" << a->getFileName() << "': "
606 << "Unrecognized file type.\n";
607 }
608}
609
610/// @brief Open file and figure out how to dump it.
611static void DumpInput(StringRef file) {
612 // If file isn't stdin, check that it exists.
613 if (file != "-" && !sys::fs::exists(file)) {
614 errs() << ToolName << ": '" << file << "': " << "No such file\n";
615 return;
616 }
617
618 if (MachO && Disassemble) {
619 DisassembleInputMachO(file);
620 return;
621 }
622
623 // Attempt to open the binary.
624 OwningPtr<Binary> binary;
625 if (error_code ec = createBinary(file, binary)) {
626 errs() << ToolName << ": '" << file << "': " << ec.message() << ".\n";
627 return;
628 }
629
630 if (Archive *a = dyn_cast<Archive>(binary.get())) {
631 DumpArchive(a);
632 } else if (ObjectFile *o = dyn_cast<ObjectFile>(binary.get())) {
633 DumpObject(o);
634 } else {
635 errs() << ToolName << ": '" << file << "': " << "Unrecognized file type.\n";
636 }
637}
638
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000639int main(int argc, char **argv) {
640 // Print a stack trace if we signal out.
641 sys::PrintStackTraceOnErrorSignal();
642 PrettyStackTraceProgram X(argc, argv);
643 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
644
645 // Initialize targets and assembly printers/parsers.
646 llvm::InitializeAllTargetInfos();
Evan Chenge78085a2011-07-22 21:58:54 +0000647 llvm::InitializeAllTargetMCs();
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000648 llvm::InitializeAllAsmParsers();
649 llvm::InitializeAllDisassemblers();
650
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000651 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
652 TripleName = Triple::normalize(TripleName);
653
654 ToolName = argv[0];
655
656 // Defaults to a.out if no filenames specified.
657 if (InputFilenames.size() == 0)
658 InputFilenames.push_back("a.out");
659
Michael J. Spencer22ff0f32011-10-18 19:32:17 +0000660 if (!Disassemble
661 && !Relocations
662 && !SectionHeaders
663 && !SectionContents
664 && !SymbolTable) {
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000665 cl::PrintHelpMessage();
666 return 2;
667 }
668
Michael J. Spencer27781b72011-10-08 00:18:30 +0000669 std::for_each(InputFilenames.begin(), InputFilenames.end(),
670 DumpInput);
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000671
672 return 0;
673}