blob: 1cf92360054419a9c33af59003bc90e82d7b25a3 [file] [log] [blame]
Benjamin Kramer43a772e2011-09-19 17:56:04 +00001//===-- MachODump.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 file implements the MachO-specific dumper for llvm-objdump.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm-objdump.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000015#include "llvm/ADT/STLExtras.h"
Ahmed Bougachaaa790682013-05-24 01:07:04 +000016#include "llvm/ADT/StringExtras.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000017#include "llvm/ADT/Triple.h"
Benjamin Kramer699128e2011-09-21 01:13:19 +000018#include "llvm/DebugInfo/DIContext.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000019#include "llvm/MC/MCAsmInfo.h"
Lang Hamesa1bc0f52014-04-15 04:40:56 +000020#include "llvm/MC/MCContext.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000021#include "llvm/MC/MCDisassembler.h"
22#include "llvm/MC/MCInst.h"
23#include "llvm/MC/MCInstPrinter.h"
24#include "llvm/MC/MCInstrAnalysis.h"
25#include "llvm/MC/MCInstrDesc.h"
26#include "llvm/MC/MCInstrInfo.h"
Jim Grosbachfd93a592012-03-05 19:33:20 +000027#include "llvm/MC/MCRegisterInfo.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000028#include "llvm/MC/MCSubtargetInfo.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000029#include "llvm/Object/MachO.h"
Rafael Espindola9b709252013-04-13 01:45:40 +000030#include "llvm/Support/Casting.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000031#include "llvm/Support/CommandLine.h"
32#include "llvm/Support/Debug.h"
Tim Northover4bd286a2014-08-01 13:07:19 +000033#include "llvm/Support/Endian.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000034#include "llvm/Support/Format.h"
35#include "llvm/Support/GraphWriter.h"
Chandler Carruth4d88a1c2012-12-04 10:44:52 +000036#include "llvm/Support/MachO.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000037#include "llvm/Support/MemoryBuffer.h"
38#include "llvm/Support/TargetRegistry.h"
39#include "llvm/Support/TargetSelect.h"
40#include "llvm/Support/raw_ostream.h"
Benjamin Kramer43a772e2011-09-19 17:56:04 +000041#include <algorithm>
42#include <cstring>
Rafael Espindolaa6e9c3e2014-06-12 17:38:55 +000043#include <system_error>
Benjamin Kramer43a772e2011-09-19 17:56:04 +000044using namespace llvm;
45using namespace object;
46
47static cl::opt<bool>
Benjamin Kramer699128e2011-09-21 01:13:19 +000048 UseDbg("g", cl::desc("Print line information from debug info if available"));
49
50static cl::opt<std::string>
51 DSYMFile("dsym", cl::desc("Use .dSYM file for debug info"));
52
Kevin Enderbyec5ca032014-08-18 20:21:02 +000053static std::string ThumbTripleName;
54
55static const Target *GetTarget(const MachOObjectFile *MachOObj,
56 const char **McpuDefault,
57 const Target **ThumbTarget) {
Benjamin Kramer43a772e2011-09-19 17:56:04 +000058 // Figure out the target triple.
Cameron Zwarich88cc16a2012-02-03 06:35:22 +000059 if (TripleName.empty()) {
60 llvm::Triple TT("unknown-unknown-unknown");
Kevin Enderbyec5ca032014-08-18 20:21:02 +000061 llvm::Triple ThumbTriple = Triple();
62 TT = MachOObj->getArch(McpuDefault, &ThumbTriple);
Cameron Zwarich88cc16a2012-02-03 06:35:22 +000063 TripleName = TT.str();
Kevin Enderbyec5ca032014-08-18 20:21:02 +000064 ThumbTripleName = ThumbTriple.str();
Benjamin Kramer43a772e2011-09-19 17:56:04 +000065 }
66
Benjamin Kramer43a772e2011-09-19 17:56:04 +000067 // Get the target specific parser.
68 std::string Error;
69 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
Kevin Enderbyec5ca032014-08-18 20:21:02 +000070 if (TheTarget && ThumbTripleName.empty())
Benjamin Kramer43a772e2011-09-19 17:56:04 +000071 return TheTarget;
72
Kevin Enderbyec5ca032014-08-18 20:21:02 +000073 *ThumbTarget = TargetRegistry::lookupTarget(ThumbTripleName, Error);
74 if (*ThumbTarget)
75 return TheTarget;
76
77 errs() << "llvm-objdump: error: unable to get target for '";
78 if (!TheTarget)
79 errs() << TripleName;
80 else
81 errs() << ThumbTripleName;
82 errs() << "', see --version and --triple.\n";
Craig Toppere6cb63e2014-04-25 04:24:47 +000083 return nullptr;
Benjamin Kramer43a772e2011-09-19 17:56:04 +000084}
85
Owen Andersond9243c42011-10-17 21:37:35 +000086struct SymbolSorter {
87 bool operator()(const SymbolRef &A, const SymbolRef &B) {
88 SymbolRef::Type AType, BType;
89 A.getType(AType);
90 B.getType(BType);
91
92 uint64_t AAddr, BAddr;
93 if (AType != SymbolRef::ST_Function)
94 AAddr = 0;
95 else
96 A.getAddress(AAddr);
97 if (BType != SymbolRef::ST_Function)
98 BAddr = 0;
99 else
100 B.getAddress(BAddr);
101 return AAddr < BAddr;
102 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000103};
104
Kevin Enderby273ae012013-06-06 17:20:50 +0000105// Types for the storted data in code table that is built before disassembly
106// and the predicate function to sort them.
107typedef std::pair<uint64_t, DiceRef> DiceTableEntry;
108typedef std::vector<DiceTableEntry> DiceTable;
109typedef DiceTable::iterator dice_table_iterator;
110
111static bool
112compareDiceTableEntries(const DiceTableEntry i,
113 const DiceTableEntry j) {
114 return i.first == j.first;
115}
116
117static void DumpDataInCode(const char *bytes, uint64_t Size,
118 unsigned short Kind) {
119 uint64_t Value;
120
121 switch (Kind) {
Charles Davis8bdfafd2013-09-01 04:28:48 +0000122 case MachO::DICE_KIND_DATA:
Kevin Enderby273ae012013-06-06 17:20:50 +0000123 switch (Size) {
124 case 4:
125 Value = bytes[3] << 24 |
126 bytes[2] << 16 |
127 bytes[1] << 8 |
128 bytes[0];
129 outs() << "\t.long " << Value;
130 break;
131 case 2:
132 Value = bytes[1] << 8 |
133 bytes[0];
134 outs() << "\t.short " << Value;
135 break;
136 case 1:
137 Value = bytes[0];
138 outs() << "\t.byte " << Value;
139 break;
140 }
141 outs() << "\t@ KIND_DATA\n";
142 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000143 case MachO::DICE_KIND_JUMP_TABLE8:
Kevin Enderby273ae012013-06-06 17:20:50 +0000144 Value = bytes[0];
145 outs() << "\t.byte " << Value << "\t@ KIND_JUMP_TABLE8";
146 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000147 case MachO::DICE_KIND_JUMP_TABLE16:
Kevin Enderby273ae012013-06-06 17:20:50 +0000148 Value = bytes[1] << 8 |
149 bytes[0];
150 outs() << "\t.short " << Value << "\t@ KIND_JUMP_TABLE16";
151 break;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000152 case MachO::DICE_KIND_JUMP_TABLE32:
Kevin Enderby273ae012013-06-06 17:20:50 +0000153 Value = bytes[3] << 24 |
154 bytes[2] << 16 |
155 bytes[1] << 8 |
156 bytes[0];
157 outs() << "\t.long " << Value << "\t@ KIND_JUMP_TABLE32";
158 break;
159 default:
160 outs() << "\t@ data in code kind = " << Kind << "\n";
161 break;
162 }
163}
164
Alexey Samsonov464d2e42014-03-17 07:28:19 +0000165static void getSectionsAndSymbols(const MachO::mach_header Header,
166 MachOObjectFile *MachOObj,
167 std::vector<SectionRef> &Sections,
168 std::vector<SymbolRef> &Symbols,
169 SmallVectorImpl<uint64_t> &FoundFns,
170 uint64_t &BaseSegmentAddress) {
171 for (const SymbolRef &Symbol : MachOObj->symbols())
172 Symbols.push_back(Symbol);
Owen Andersond9243c42011-10-17 21:37:35 +0000173
Alexey Samsonov48803e52014-03-13 14:37:36 +0000174 for (const SectionRef &Section : MachOObj->sections()) {
Owen Andersond9243c42011-10-17 21:37:35 +0000175 StringRef SectName;
Alexey Samsonov48803e52014-03-13 14:37:36 +0000176 Section.getName(SectName);
177 Sections.push_back(Section);
Owen Andersond9243c42011-10-17 21:37:35 +0000178 }
179
Rafael Espindola56f976f2013-04-18 18:08:55 +0000180 MachOObjectFile::LoadCommandInfo Command =
Alexey Samsonov48803e52014-03-13 14:37:36 +0000181 MachOObj->getFirstLoadCommandInfo();
Kevin Enderby273ae012013-06-06 17:20:50 +0000182 bool BaseSegmentAddressSet = false;
Rafael Espindolafeef8c22013-04-19 11:36:47 +0000183 for (unsigned i = 0; ; ++i) {
Charles Davis8bdfafd2013-09-01 04:28:48 +0000184 if (Command.C.cmd == MachO::LC_FUNCTION_STARTS) {
Benjamin Kramer699128e2011-09-21 01:13:19 +0000185 // We found a function starts segment, parse the addresses for later
186 // consumption.
Charles Davis8bdfafd2013-09-01 04:28:48 +0000187 MachO::linkedit_data_command LLC =
Rafael Espindola56f976f2013-04-18 18:08:55 +0000188 MachOObj->getLinkeditDataLoadCommand(Command);
Benjamin Kramer699128e2011-09-21 01:13:19 +0000189
Charles Davis8bdfafd2013-09-01 04:28:48 +0000190 MachOObj->ReadULEB128s(LLC.dataoff, FoundFns);
Benjamin Kramer8a529dc2011-09-21 22:16:43 +0000191 }
Charles Davis8bdfafd2013-09-01 04:28:48 +0000192 else if (Command.C.cmd == MachO::LC_SEGMENT) {
193 MachO::segment_command SLC =
Kevin Enderby273ae012013-06-06 17:20:50 +0000194 MachOObj->getSegmentLoadCommand(Command);
Charles Davis8bdfafd2013-09-01 04:28:48 +0000195 StringRef SegName = SLC.segname;
Kevin Enderby273ae012013-06-06 17:20:50 +0000196 if(!BaseSegmentAddressSet && SegName != "__PAGEZERO") {
197 BaseSegmentAddressSet = true;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000198 BaseSegmentAddress = SLC.vmaddr;
Kevin Enderby273ae012013-06-06 17:20:50 +0000199 }
200 }
Rafael Espindolafeef8c22013-04-19 11:36:47 +0000201
Charles Davis8bdfafd2013-09-01 04:28:48 +0000202 if (i == Header.ncmds - 1)
Rafael Espindolafeef8c22013-04-19 11:36:47 +0000203 break;
204 else
205 Command = MachOObj->getNextLoadCommandInfo(Command);
Benjamin Kramer8a529dc2011-09-21 22:16:43 +0000206 }
Benjamin Kramer699128e2011-09-21 01:13:19 +0000207}
208
Rafael Espindola9b709252013-04-13 01:45:40 +0000209static void DisassembleInputMachO2(StringRef Filename,
Rafael Espindola56f976f2013-04-18 18:08:55 +0000210 MachOObjectFile *MachOOF);
Rafael Espindola9b709252013-04-13 01:45:40 +0000211
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000212void llvm::DisassembleInputMachO(StringRef Filename) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000213 ErrorOr<std::unique_ptr<MemoryBuffer>> Buff =
214 MemoryBuffer::getFileOrSTDIN(Filename);
215 if (std::error_code EC = Buff.getError()) {
216 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << "\n";
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000217 return;
218 }
219
Rafael Espindola437b0d52014-07-31 03:12:45 +0000220 std::unique_ptr<MachOObjectFile> MachOOF =
221 std::move(ObjectFile::createMachOObjectFile(Buff.get()).get());
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000222
Rafael Espindola56f976f2013-04-18 18:08:55 +0000223 DisassembleInputMachO2(Filename, MachOOF.get());
Rafael Espindola9b709252013-04-13 01:45:40 +0000224}
225
Rafael Espindola9b709252013-04-13 01:45:40 +0000226static void DisassembleInputMachO2(StringRef Filename,
Rafael Espindola56f976f2013-04-18 18:08:55 +0000227 MachOObjectFile *MachOOF) {
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000228 const char *McpuDefault = nullptr;
229 const Target *ThumbTarget = nullptr;
230 const Target *TheTarget = GetTarget(MachOOF, &McpuDefault, &ThumbTarget);
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000231 if (!TheTarget) {
232 // GetTarget prints out stuff.
233 return;
234 }
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000235 if (MCPU.empty() && McpuDefault)
236 MCPU = McpuDefault;
237
Ahmed Charles56440fd2014-03-06 05:51:42 +0000238 std::unique_ptr<const MCInstrInfo> InstrInfo(TheTarget->createMCInstrInfo());
239 std::unique_ptr<MCInstrAnalysis> InstrAnalysis(
240 TheTarget->createMCInstrAnalysis(InstrInfo.get()));
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000241 std::unique_ptr<const MCInstrInfo> ThumbInstrInfo;
242 std::unique_ptr<MCInstrAnalysis> ThumbInstrAnalysis;
243 if (ThumbTarget) {
244 ThumbInstrInfo.reset(ThumbTarget->createMCInstrInfo());
245 ThumbInstrAnalysis.reset(
246 ThumbTarget->createMCInstrAnalysis(ThumbInstrInfo.get()));
247 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000248
Kevin Enderbyc9595622014-08-06 23:24:41 +0000249 // Package up features to be passed to target/subtarget
250 std::string FeaturesStr;
251 if (MAttrs.size()) {
252 SubtargetFeatures Features;
253 for (unsigned i = 0; i != MAttrs.size(); ++i)
254 Features.AddFeature(MAttrs[i]);
255 FeaturesStr = Features.getString();
256 }
257
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000258 // Set up disassembler.
Ahmed Charles56440fd2014-03-06 05:51:42 +0000259 std::unique_ptr<const MCRegisterInfo> MRI(
260 TheTarget->createMCRegInfo(TripleName));
261 std::unique_ptr<const MCAsmInfo> AsmInfo(
Rafael Espindola227144c2013-05-13 01:16:13 +0000262 TheTarget->createMCAsmInfo(*MRI, TripleName));
Ahmed Charles56440fd2014-03-06 05:51:42 +0000263 std::unique_ptr<const MCSubtargetInfo> STI(
Kevin Enderbyc9595622014-08-06 23:24:41 +0000264 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
Craig Toppere6cb63e2014-04-25 04:24:47 +0000265 MCContext Ctx(AsmInfo.get(), MRI.get(), nullptr);
Ahmed Charles56440fd2014-03-06 05:51:42 +0000266 std::unique_ptr<const MCDisassembler> DisAsm(
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000267 TheTarget->createMCDisassembler(*STI, Ctx));
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000268 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
Ahmed Charles56440fd2014-03-06 05:51:42 +0000269 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
270 AsmPrinterVariant, *AsmInfo, *InstrInfo, *MRI, *STI));
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +0000271
272 if (!InstrAnalysis || !AsmInfo || !STI || !DisAsm || !IP) {
Michael J. Spencerc1363cf2011-10-07 19:25:47 +0000273 errs() << "error: couldn't initialize disassembler for target "
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +0000274 << TripleName << '\n';
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000275 return;
276 }
277
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000278 // Set up thumb disassembler.
279 std::unique_ptr<const MCRegisterInfo> ThumbMRI;
280 std::unique_ptr<const MCAsmInfo> ThumbAsmInfo;
281 std::unique_ptr<const MCSubtargetInfo> ThumbSTI;
282 std::unique_ptr<const MCDisassembler> ThumbDisAsm;
283 std::unique_ptr<MCInstPrinter> ThumbIP;
284 std::unique_ptr<MCContext> ThumbCtx;
285 if (ThumbTarget) {
286 ThumbMRI.reset(ThumbTarget->createMCRegInfo(ThumbTripleName));
287 ThumbAsmInfo.reset(
288 ThumbTarget->createMCAsmInfo(*ThumbMRI, ThumbTripleName));
289 ThumbSTI.reset(
290 ThumbTarget->createMCSubtargetInfo(ThumbTripleName, MCPU, FeaturesStr));
291 ThumbCtx.reset(new MCContext(ThumbAsmInfo.get(), ThumbMRI.get(), nullptr));
292 ThumbDisAsm.reset(ThumbTarget->createMCDisassembler(*ThumbSTI, *ThumbCtx));
293 int ThumbAsmPrinterVariant = ThumbAsmInfo->getAssemblerDialect();
294 ThumbIP.reset(ThumbTarget->createMCInstPrinter(
295 ThumbAsmPrinterVariant, *ThumbAsmInfo, *ThumbInstrInfo, *ThumbMRI,
296 *ThumbSTI));
297 }
298
299 if (ThumbTarget && (!ThumbInstrAnalysis || !ThumbAsmInfo || !ThumbSTI ||
300 !ThumbDisAsm || !ThumbIP)) {
301 errs() << "error: couldn't initialize disassembler for target "
302 << ThumbTripleName << '\n';
303 return;
304 }
305
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +0000306 outs() << '\n' << Filename << ":\n\n";
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000307
Charles Davis8bdfafd2013-09-01 04:28:48 +0000308 MachO::mach_header Header = MachOOF->getHeader();
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000309
Ahmed Bougachaaa790682013-05-24 01:07:04 +0000310 // FIXME: FoundFns isn't used anymore. Using symbols/LC_FUNCTION_STARTS to
311 // determine function locations will eventually go in MCObjectDisassembler.
312 // FIXME: Using the -cfg command line option, this code used to be able to
313 // annotate relocations with the referenced symbol's name, and if this was
314 // inside a __[cf]string section, the data it points to. This is now replaced
315 // by the upcoming MCSymbolizer, which needs the appropriate setup done above.
Owen Andersond9243c42011-10-17 21:37:35 +0000316 std::vector<SectionRef> Sections;
317 std::vector<SymbolRef> Symbols;
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000318 SmallVector<uint64_t, 8> FoundFns;
Kevin Enderby273ae012013-06-06 17:20:50 +0000319 uint64_t BaseSegmentAddress;
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000320
Kevin Enderby273ae012013-06-06 17:20:50 +0000321 getSectionsAndSymbols(Header, MachOOF, Sections, Symbols, FoundFns,
322 BaseSegmentAddress);
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000323
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000324 // Sort the symbols by address, just in case they didn't come in that way.
Owen Andersond9243c42011-10-17 21:37:35 +0000325 std::sort(Symbols.begin(), Symbols.end(), SymbolSorter());
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000326
Kevin Enderby273ae012013-06-06 17:20:50 +0000327 // Build a data in code table that is sorted on by the address of each entry.
328 uint64_t BaseAddress = 0;
Charles Davis8bdfafd2013-09-01 04:28:48 +0000329 if (Header.filetype == MachO::MH_OBJECT)
Kevin Enderby273ae012013-06-06 17:20:50 +0000330 Sections[0].getAddress(BaseAddress);
331 else
332 BaseAddress = BaseSegmentAddress;
333 DiceTable Dices;
Kevin Enderby273ae012013-06-06 17:20:50 +0000334 for (dice_iterator DI = MachOOF->begin_dices(), DE = MachOOF->end_dices();
Rafael Espindola5e812af2014-01-30 02:49:50 +0000335 DI != DE; ++DI) {
Kevin Enderby273ae012013-06-06 17:20:50 +0000336 uint32_t Offset;
337 DI->getOffset(Offset);
338 Dices.push_back(std::make_pair(BaseAddress + Offset, *DI));
339 }
340 array_pod_sort(Dices.begin(), Dices.end());
341
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000342#ifndef NDEBUG
343 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
344#else
345 raw_ostream &DebugOut = nulls();
346#endif
347
Ahmed Charles56440fd2014-03-06 05:51:42 +0000348 std::unique_ptr<DIContext> diContext;
Rafael Espindola9b709252013-04-13 01:45:40 +0000349 ObjectFile *DbgObj = MachOOF;
Benjamin Kramer699128e2011-09-21 01:13:19 +0000350 // Try to find debug info and set up the DIContext for it.
351 if (UseDbg) {
Benjamin Kramer699128e2011-09-21 01:13:19 +0000352 // A separate DSym file path was specified, parse it as a macho file,
353 // get the sections and supply it to the section name parsing machinery.
354 if (!DSYMFile.empty()) {
Rafael Espindolaadf21f22014-07-06 17:43:13 +0000355 ErrorOr<std::unique_ptr<MemoryBuffer>> Buf =
356 MemoryBuffer::getFileOrSTDIN(DSYMFile);
357 if (std::error_code EC = Buf.getError()) {
358 errs() << "llvm-objdump: " << Filename << ": " << EC.message() << '\n';
Benjamin Kramer699128e2011-09-21 01:13:19 +0000359 return;
360 }
Rafael Espindola437b0d52014-07-31 03:12:45 +0000361 DbgObj = ObjectFile::createMachOObjectFile(Buf.get()).get().release();
Benjamin Kramer699128e2011-09-21 01:13:19 +0000362 }
363
Eric Christopher7370b552012-11-12 21:40:38 +0000364 // Setup the DIContext
Rafael Espindolaa04bb5b2014-07-31 20:19:36 +0000365 diContext.reset(DIContext::getDWARFContext(*DbgObj));
Benjamin Kramer699128e2011-09-21 01:13:19 +0000366 }
367
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000368 for (unsigned SectIdx = 0; SectIdx != Sections.size(); SectIdx++) {
Ahmed Bougachaaa790682013-05-24 01:07:04 +0000369
370 bool SectIsText = false;
371 Sections[SectIdx].isText(SectIsText);
372 if (SectIsText == false)
373 continue;
374
Owen Andersond9243c42011-10-17 21:37:35 +0000375 StringRef SectName;
376 if (Sections[SectIdx].getName(SectName) ||
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000377 SectName != "__text")
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +0000378 continue; // Skip non-text sections
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000379
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000380 DataRefImpl DR = Sections[SectIdx].getRawDataRefImpl();
Ahmed Bougachaaa790682013-05-24 01:07:04 +0000381
Rafael Espindolab0f76a42013-04-05 15:15:22 +0000382 StringRef SegmentName = MachOOF->getSectionFinalSegmentName(DR);
383 if (SegmentName != "__TEXT")
Rafael Espindolaa9f810b2012-12-21 03:47:03 +0000384 continue;
385
Owen Andersond9243c42011-10-17 21:37:35 +0000386 StringRef Bytes;
387 Sections[SectIdx].getContents(Bytes);
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000388 StringRefMemoryObject memoryObject(Bytes);
389 bool symbolTableWorked = false;
390
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +0000391 // Parse relocations.
Alexey Samsonovaa4d2952014-03-14 14:22:49 +0000392 std::vector<std::pair<uint64_t, SymbolRef>> Relocs;
393 for (const RelocationRef &Reloc : Sections[SectIdx].relocations()) {
Owen Andersond9243c42011-10-17 21:37:35 +0000394 uint64_t RelocOffset, SectionAddress;
Alexey Samsonovaa4d2952014-03-14 14:22:49 +0000395 Reloc.getOffset(RelocOffset);
Owen Andersond9243c42011-10-17 21:37:35 +0000396 Sections[SectIdx].getAddress(SectionAddress);
397 RelocOffset -= SectionAddress;
398
Alexey Samsonovaa4d2952014-03-14 14:22:49 +0000399 symbol_iterator RelocSym = Reloc.getSymbol();
Owen Andersond9243c42011-10-17 21:37:35 +0000400
Rafael Espindola806f0062013-06-05 01:33:53 +0000401 Relocs.push_back(std::make_pair(RelocOffset, *RelocSym));
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000402 }
403 array_pod_sort(Relocs.begin(), Relocs.end());
404
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +0000405 // Disassemble symbol by symbol.
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000406 for (unsigned SymIdx = 0; SymIdx != Symbols.size(); SymIdx++) {
Owen Andersond9243c42011-10-17 21:37:35 +0000407 StringRef SymName;
408 Symbols[SymIdx].getName(SymName);
409
410 SymbolRef::Type ST;
411 Symbols[SymIdx].getType(ST);
412 if (ST != SymbolRef::ST_Function)
413 continue;
414
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +0000415 // Make sure the symbol is defined in this section.
Owen Andersond9243c42011-10-17 21:37:35 +0000416 bool containsSym = false;
417 Sections[SectIdx].containsSymbol(Symbols[SymIdx], containsSym);
418 if (!containsSym)
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000419 continue;
420
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +0000421 // Start at the address of the symbol relative to the section's address.
Cameron Zwarich54478a52012-02-03 05:42:17 +0000422 uint64_t SectionAddress = 0;
Owen Andersond9243c42011-10-17 21:37:35 +0000423 uint64_t Start = 0;
Cameron Zwarich54478a52012-02-03 05:42:17 +0000424 Sections[SectIdx].getAddress(SectionAddress);
Danil Malyshevcbe72fc2011-11-29 17:40:10 +0000425 Symbols[SymIdx].getAddress(Start);
Cameron Zwarich54478a52012-02-03 05:42:17 +0000426 Start -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +0000427
Benjamin Kramer2ad2eb52011-09-20 17:53:01 +0000428 // Stop disassembling either at the beginning of the next symbol or at
429 // the end of the section.
Kevin Enderbyedd58722012-05-15 18:57:14 +0000430 bool containsNextSym = false;
Owen Andersond9243c42011-10-17 21:37:35 +0000431 uint64_t NextSym = 0;
432 uint64_t NextSymIdx = SymIdx+1;
433 while (Symbols.size() > NextSymIdx) {
434 SymbolRef::Type NextSymType;
435 Symbols[NextSymIdx].getType(NextSymType);
436 if (NextSymType == SymbolRef::ST_Function) {
437 Sections[SectIdx].containsSymbol(Symbols[NextSymIdx],
438 containsNextSym);
Danil Malyshevcbe72fc2011-11-29 17:40:10 +0000439 Symbols[NextSymIdx].getAddress(NextSym);
Cameron Zwarich54478a52012-02-03 05:42:17 +0000440 NextSym -= SectionAddress;
Owen Andersond9243c42011-10-17 21:37:35 +0000441 break;
442 }
443 ++NextSymIdx;
444 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000445
Owen Andersond9243c42011-10-17 21:37:35 +0000446 uint64_t SectSize;
447 Sections[SectIdx].getSize(SectSize);
448 uint64_t End = containsNextSym ? NextSym : SectSize;
449 uint64_t Size;
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000450
451 symbolTableWorked = true;
452
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000453 DataRefImpl Symb = Symbols[SymIdx].getRawDataRefImpl();
454 bool isThumb =
455 (MachOOF->getSymbolFlags(Symb) & SymbolRef::SF_Thumb) && ThumbTarget;
456
Ahmed Bougachaaa790682013-05-24 01:07:04 +0000457 outs() << SymName << ":\n";
458 DILineInfo lastLine;
459 for (uint64_t Index = Start; Index < End; Index += Size) {
460 MCInst Inst;
Owen Andersond9243c42011-10-17 21:37:35 +0000461
Kevin Enderby273ae012013-06-06 17:20:50 +0000462 uint64_t SectAddress = 0;
463 Sections[SectIdx].getAddress(SectAddress);
464 outs() << format("%8" PRIx64 ":\t", SectAddress + Index);
465
466 // Check the data in code table here to see if this is data not an
467 // instruction to be disassembled.
468 DiceTable Dice;
469 Dice.push_back(std::make_pair(SectAddress + Index, DiceRef()));
470 dice_table_iterator DTI = std::search(Dices.begin(), Dices.end(),
471 Dice.begin(), Dice.end(),
472 compareDiceTableEntries);
473 if (DTI != Dices.end()){
474 uint16_t Length;
475 DTI->second.getLength(Length);
476 DumpBytes(StringRef(Bytes.data() + Index, Length));
477 uint16_t Kind;
478 DTI->second.getKind(Kind);
479 DumpDataInCode(Bytes.data() + Index, Length, Kind);
480 continue;
481 }
482
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000483 bool gotInst;
484 if (isThumb)
485 gotInst = ThumbDisAsm->getInstruction(Inst, Size, memoryObject, Index,
486 DebugOut, nulls());
487 else
488 gotInst = DisAsm->getInstruction(Inst, Size, memoryObject, Index,
489 DebugOut, nulls());
490 if (gotInst) {
Ahmed Bougachaaa790682013-05-24 01:07:04 +0000491 DumpBytes(StringRef(Bytes.data() + Index, Size));
Kevin Enderbyec5ca032014-08-18 20:21:02 +0000492 if (isThumb)
493 ThumbIP->printInst(&Inst, outs(), "");
494 else
495 IP->printInst(&Inst, outs(), "");
Owen Andersond9243c42011-10-17 21:37:35 +0000496
Ahmed Bougachaaa790682013-05-24 01:07:04 +0000497 // Print debug info.
498 if (diContext) {
499 DILineInfo dli =
500 diContext->getLineInfoForAddress(SectAddress + Index);
501 // Print valid line info if it changed.
Alexey Samsonovd0109992014-04-18 21:36:39 +0000502 if (dli != lastLine && dli.Line != 0)
503 outs() << "\t## " << dli.FileName << ':' << dli.Line << ':'
504 << dli.Column;
Ahmed Bougachaaa790682013-05-24 01:07:04 +0000505 lastLine = dli;
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000506 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +0000507 outs() << "\n";
508 } else {
509 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
510 if (Size == 0)
511 Size = 1; // skip illegible bytes
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000512 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000513 }
514 }
Ahmed Bougachaaa790682013-05-24 01:07:04 +0000515 if (!symbolTableWorked) {
Kevin Enderbybadd1002012-05-18 00:13:56 +0000516 // Reading the symbol table didn't work, disassemble the whole section.
517 uint64_t SectAddress;
518 Sections[SectIdx].getAddress(SectAddress);
519 uint64_t SectSize;
520 Sections[SectIdx].getSize(SectSize);
521 uint64_t InstSize;
522 for (uint64_t Index = 0; Index < SectSize; Index += InstSize) {
Bill Wendling4e68e062012-07-19 00:17:40 +0000523 MCInst Inst;
Kevin Enderbybadd1002012-05-18 00:13:56 +0000524
Bill Wendling4e68e062012-07-19 00:17:40 +0000525 if (DisAsm->getInstruction(Inst, InstSize, memoryObject, Index,
526 DebugOut, nulls())) {
527 outs() << format("%8" PRIx64 ":\t", SectAddress + Index);
528 DumpBytes(StringRef(Bytes.data() + Index, InstSize));
529 IP->printInst(&Inst, outs(), "");
530 outs() << "\n";
531 } else {
532 errs() << "llvm-objdump: warning: invalid instruction encoding\n";
533 if (InstSize == 0)
534 InstSize = 1; // skip illegible bytes
535 }
Kevin Enderbybadd1002012-05-18 00:13:56 +0000536 }
537 }
Benjamin Kramer43a772e2011-09-19 17:56:04 +0000538 }
539}
Tim Northover4bd286a2014-08-01 13:07:19 +0000540
Tim Northover39c70bb2014-08-12 11:52:59 +0000541
542//===----------------------------------------------------------------------===//
543// __compact_unwind section dumping
544//===----------------------------------------------------------------------===//
545
Tim Northover4bd286a2014-08-01 13:07:19 +0000546namespace {
Tim Northover39c70bb2014-08-12 11:52:59 +0000547
548template <typename T> static uint64_t readNext(const char *&Buf) {
549 using llvm::support::little;
550 using llvm::support::unaligned;
551
552 uint64_t Val = support::endian::read<T, little, unaligned>(Buf);
553 Buf += sizeof(T);
554 return Val;
555 }
556
Tim Northover4bd286a2014-08-01 13:07:19 +0000557struct CompactUnwindEntry {
558 uint32_t OffsetInSection;
559
560 uint64_t FunctionAddr;
561 uint32_t Length;
562 uint32_t CompactEncoding;
563 uint64_t PersonalityAddr;
564 uint64_t LSDAAddr;
565
566 RelocationRef FunctionReloc;
567 RelocationRef PersonalityReloc;
568 RelocationRef LSDAReloc;
569
570 CompactUnwindEntry(StringRef Contents, unsigned Offset, bool Is64)
571 : OffsetInSection(Offset) {
572 if (Is64)
573 read<uint64_t>(Contents.data() + Offset);
574 else
575 read<uint32_t>(Contents.data() + Offset);
576 }
577
578private:
Tim Northover4bd286a2014-08-01 13:07:19 +0000579 template<typename UIntPtr>
580 void read(const char *Buf) {
581 FunctionAddr = readNext<UIntPtr>(Buf);
582 Length = readNext<uint32_t>(Buf);
583 CompactEncoding = readNext<uint32_t>(Buf);
584 PersonalityAddr = readNext<UIntPtr>(Buf);
585 LSDAAddr = readNext<UIntPtr>(Buf);
586 }
587};
588}
589
590/// Given a relocation from __compact_unwind, consisting of the RelocationRef
591/// and data being relocated, determine the best base Name and Addend to use for
592/// display purposes.
593///
594/// 1. An Extern relocation will directly reference a symbol (and the data is
595/// then already an addend), so use that.
596/// 2. Otherwise the data is an offset in the object file's layout; try to find
597// a symbol before it in the same section, and use the offset from there.
598/// 3. Finally, if all that fails, fall back to an offset from the start of the
599/// referenced section.
600static void findUnwindRelocNameAddend(const MachOObjectFile *Obj,
601 std::map<uint64_t, SymbolRef> &Symbols,
602 const RelocationRef &Reloc,
603 uint64_t Addr,
604 StringRef &Name, uint64_t &Addend) {
605 if (Reloc.getSymbol() != Obj->symbol_end()) {
606 Reloc.getSymbol()->getName(Name);
607 Addend = Addr;
608 return;
609 }
610
611 auto RE = Obj->getRelocation(Reloc.getRawDataRefImpl());
612 SectionRef RelocSection = Obj->getRelocationSection(RE);
613
614 uint64_t SectionAddr;
615 RelocSection.getAddress(SectionAddr);
616
617 auto Sym = Symbols.upper_bound(Addr);
618 if (Sym == Symbols.begin()) {
619 // The first symbol in the object is after this reference, the best we can
620 // do is section-relative notation.
621 RelocSection.getName(Name);
622 Addend = Addr - SectionAddr;
623 return;
624 }
625
626 // Go back one so that SymbolAddress <= Addr.
627 --Sym;
628
629 section_iterator SymSection = Obj->section_end();
630 Sym->second.getSection(SymSection);
631 if (RelocSection == *SymSection) {
632 // There's a valid symbol in the same section before this reference.
633 Sym->second.getName(Name);
634 Addend = Addr - Sym->first;
635 return;
636 }
637
638 // There is a symbol before this reference, but it's in a different
639 // section. Probably not helpful to mention it, so use the section name.
640 RelocSection.getName(Name);
641 Addend = Addr - SectionAddr;
642}
643
644static void printUnwindRelocDest(const MachOObjectFile *Obj,
645 std::map<uint64_t, SymbolRef> &Symbols,
646 const RelocationRef &Reloc,
647 uint64_t Addr) {
648 StringRef Name;
649 uint64_t Addend;
650
651 findUnwindRelocNameAddend(Obj, Symbols, Reloc, Addr, Name, Addend);
652
653 outs() << Name;
654 if (Addend)
Tim Northover63a25622014-08-11 09:14:06 +0000655 outs() << " + " << format("0x%" PRIx64, Addend);
Tim Northover4bd286a2014-08-01 13:07:19 +0000656}
657
658static void
659printMachOCompactUnwindSection(const MachOObjectFile *Obj,
660 std::map<uint64_t, SymbolRef> &Symbols,
661 const SectionRef &CompactUnwind) {
662
663 assert(Obj->isLittleEndian() &&
664 "There should not be a big-endian .o with __compact_unwind");
665
666 bool Is64 = Obj->is64Bit();
667 uint32_t PointerSize = Is64 ? sizeof(uint64_t) : sizeof(uint32_t);
668 uint32_t EntrySize = 3 * PointerSize + 2 * sizeof(uint32_t);
669
670 StringRef Contents;
671 CompactUnwind.getContents(Contents);
672
673 SmallVector<CompactUnwindEntry, 4> CompactUnwinds;
674
675 // First populate the initial raw offsets, encodings and so on from the entry.
676 for (unsigned Offset = 0; Offset < Contents.size(); Offset += EntrySize) {
677 CompactUnwindEntry Entry(Contents.data(), Offset, Is64);
678 CompactUnwinds.push_back(Entry);
679 }
680
681 // Next we need to look at the relocations to find out what objects are
682 // actually being referred to.
683 for (const RelocationRef &Reloc : CompactUnwind.relocations()) {
684 uint64_t RelocAddress;
685 Reloc.getOffset(RelocAddress);
686
687 uint32_t EntryIdx = RelocAddress / EntrySize;
688 uint32_t OffsetInEntry = RelocAddress - EntryIdx * EntrySize;
689 CompactUnwindEntry &Entry = CompactUnwinds[EntryIdx];
690
691 if (OffsetInEntry == 0)
692 Entry.FunctionReloc = Reloc;
693 else if (OffsetInEntry == PointerSize + 2 * sizeof(uint32_t))
694 Entry.PersonalityReloc = Reloc;
695 else if (OffsetInEntry == 2 * PointerSize + 2 * sizeof(uint32_t))
696 Entry.LSDAReloc = Reloc;
697 else
698 llvm_unreachable("Unexpected relocation in __compact_unwind section");
699 }
700
701 // Finally, we're ready to print the data we've gathered.
702 outs() << "Contents of __compact_unwind section:\n";
703 for (auto &Entry : CompactUnwinds) {
Tim Northover06af2602014-08-08 12:08:51 +0000704 outs() << " Entry at offset "
705 << format("0x%" PRIx32, Entry.OffsetInSection) << ":\n";
Tim Northover4bd286a2014-08-01 13:07:19 +0000706
707 // 1. Start of the region this entry applies to.
708 outs() << " start: "
Tim Northoverb911bf82014-08-08 12:00:09 +0000709 << format("0x%" PRIx64, Entry.FunctionAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +0000710 printUnwindRelocDest(Obj, Symbols, Entry.FunctionReloc,
711 Entry.FunctionAddr);
712 outs() << '\n';
713
714 // 2. Length of the region this entry applies to.
715 outs() << " length: "
Tim Northoverb911bf82014-08-08 12:00:09 +0000716 << format("0x%" PRIx32, Entry.Length) << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +0000717 // 3. The 32-bit compact encoding.
718 outs() << " compact encoding: "
Tim Northoverb911bf82014-08-08 12:00:09 +0000719 << format("0x%08" PRIx32, Entry.CompactEncoding) << '\n';
Tim Northover4bd286a2014-08-01 13:07:19 +0000720
721 // 4. The personality function, if present.
722 if (Entry.PersonalityReloc.getObjectFile()) {
723 outs() << " personality function: "
Tim Northoverb911bf82014-08-08 12:00:09 +0000724 << format("0x%" PRIx64, Entry.PersonalityAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +0000725 printUnwindRelocDest(Obj, Symbols, Entry.PersonalityReloc,
726 Entry.PersonalityAddr);
727 outs() << '\n';
728 }
729
730 // 5. This entry's language-specific data area.
731 if (Entry.LSDAReloc.getObjectFile()) {
732 outs() << " LSDA: "
Tim Northoverb911bf82014-08-08 12:00:09 +0000733 << format("0x%" PRIx64, Entry.LSDAAddr) << ' ';
Tim Northover4bd286a2014-08-01 13:07:19 +0000734 printUnwindRelocDest(Obj, Symbols, Entry.LSDAReloc, Entry.LSDAAddr);
735 outs() << '\n';
736 }
737 }
738}
739
Tim Northover39c70bb2014-08-12 11:52:59 +0000740//===----------------------------------------------------------------------===//
741// __unwind_info section dumping
742//===----------------------------------------------------------------------===//
743
744static void printRegularSecondLevelUnwindPage(const char *PageStart) {
745 const char *Pos = PageStart;
746 uint32_t Kind = readNext<uint32_t>(Pos);
747 (void)Kind;
748 assert(Kind == 2 && "kind for a regular 2nd level index should be 2");
749
750 uint16_t EntriesStart = readNext<uint16_t>(Pos);
751 uint16_t NumEntries = readNext<uint16_t>(Pos);
752
753 Pos = PageStart + EntriesStart;
754 for (unsigned i = 0; i < NumEntries; ++i) {
755 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
756 uint32_t Encoding = readNext<uint32_t>(Pos);
757
758 outs() << " [" << i << "]: "
759 << "function offset="
760 << format("0x%08" PRIx32, FunctionOffset) << ", "
761 << "encoding="
762 << format("0x%08" PRIx32, Encoding)
763 << '\n';
764 }
765}
766
767static void printCompressedSecondLevelUnwindPage(
768 const char *PageStart, uint32_t FunctionBase,
769 const SmallVectorImpl<uint32_t> &CommonEncodings) {
770 const char *Pos = PageStart;
771 uint32_t Kind = readNext<uint32_t>(Pos);
772 (void)Kind;
773 assert(Kind == 3 && "kind for a compressed 2nd level index should be 3");
774
775 uint16_t EntriesStart = readNext<uint16_t>(Pos);
776 uint16_t NumEntries = readNext<uint16_t>(Pos);
777
778 uint16_t EncodingsStart = readNext<uint16_t>(Pos);
779 readNext<uint16_t>(Pos);
Aaron Ballman80930af2014-08-14 13:53:19 +0000780 const auto *PageEncodings = reinterpret_cast<const support::ulittle32_t *>(
781 PageStart + EncodingsStart);
Tim Northover39c70bb2014-08-12 11:52:59 +0000782
783 Pos = PageStart + EntriesStart;
784 for (unsigned i = 0; i < NumEntries; ++i) {
785 uint32_t Entry = readNext<uint32_t>(Pos);
786 uint32_t FunctionOffset = FunctionBase + (Entry & 0xffffff);
787 uint32_t EncodingIdx = Entry >> 24;
788
789 uint32_t Encoding;
790 if (EncodingIdx < CommonEncodings.size())
791 Encoding = CommonEncodings[EncodingIdx];
792 else
793 Encoding = PageEncodings[EncodingIdx - CommonEncodings.size()];
794
795 outs() << " [" << i << "]: "
796 << "function offset="
797 << format("0x%08" PRIx32, FunctionOffset) << ", "
798 << "encoding[" << EncodingIdx << "]="
799 << format("0x%08" PRIx32, Encoding)
800 << '\n';
801 }
802}
803
804static void
805printMachOUnwindInfoSection(const MachOObjectFile *Obj,
806 std::map<uint64_t, SymbolRef> &Symbols,
807 const SectionRef &UnwindInfo) {
808
809 assert(Obj->isLittleEndian() &&
810 "There should not be a big-endian .o with __unwind_info");
811
812 outs() << "Contents of __unwind_info section:\n";
813
814 StringRef Contents;
815 UnwindInfo.getContents(Contents);
816 const char *Pos = Contents.data();
817
818 //===----------------------------------
819 // Section header
820 //===----------------------------------
821
822 uint32_t Version = readNext<uint32_t>(Pos);
823 outs() << " Version: "
824 << format("0x%" PRIx32, Version) << '\n';
825 assert(Version == 1 && "only understand version 1");
826
827 uint32_t CommonEncodingsStart = readNext<uint32_t>(Pos);
828 outs() << " Common encodings array section offset: "
829 << format("0x%" PRIx32, CommonEncodingsStart) << '\n';
830 uint32_t NumCommonEncodings = readNext<uint32_t>(Pos);
831 outs() << " Number of common encodings in array: "
832 << format("0x%" PRIx32, NumCommonEncodings) << '\n';
833
834 uint32_t PersonalitiesStart = readNext<uint32_t>(Pos);
835 outs() << " Personality function array section offset: "
836 << format("0x%" PRIx32, PersonalitiesStart) << '\n';
837 uint32_t NumPersonalities = readNext<uint32_t>(Pos);
838 outs() << " Number of personality functions in array: "
839 << format("0x%" PRIx32, NumPersonalities) << '\n';
840
841 uint32_t IndicesStart = readNext<uint32_t>(Pos);
842 outs() << " Index array section offset: "
843 << format("0x%" PRIx32, IndicesStart) << '\n';
844 uint32_t NumIndices = readNext<uint32_t>(Pos);
845 outs() << " Number of indices in array: "
846 << format("0x%" PRIx32, NumIndices) << '\n';
847
848 //===----------------------------------
849 // A shared list of common encodings
850 //===----------------------------------
851
852 // These occupy indices in the range [0, N] whenever an encoding is referenced
853 // from a compressed 2nd level index table. In practice the linker only
854 // creates ~128 of these, so that indices are available to embed encodings in
855 // the 2nd level index.
856
857 SmallVector<uint32_t, 64> CommonEncodings;
858 outs() << " Common encodings: (count = " << NumCommonEncodings << ")\n";
859 Pos = Contents.data() + CommonEncodingsStart;
860 for (unsigned i = 0; i < NumCommonEncodings; ++i) {
861 uint32_t Encoding = readNext<uint32_t>(Pos);
862 CommonEncodings.push_back(Encoding);
863
864 outs() << " encoding[" << i << "]: " << format("0x%08" PRIx32, Encoding)
865 << '\n';
866 }
867
868
869 //===----------------------------------
870 // Personality functions used in this executable
871 //===----------------------------------
872
873 // There should be only a handful of these (one per source language,
874 // roughly). Particularly since they only get 2 bits in the compact encoding.
875
876 outs() << " Personality functions: (count = " << NumPersonalities << ")\n";
877 Pos = Contents.data() + PersonalitiesStart;
878 for (unsigned i = 0; i < NumPersonalities; ++i) {
879 uint32_t PersonalityFn = readNext<uint32_t>(Pos);
880 outs() << " personality[" << i + 1
881 << "]: " << format("0x%08" PRIx32, PersonalityFn) << '\n';
882 }
883
884 //===----------------------------------
885 // The level 1 index entries
886 //===----------------------------------
887
888 // These specify an approximate place to start searching for the more detailed
889 // information, sorted by PC.
890
891 struct IndexEntry {
892 uint32_t FunctionOffset;
893 uint32_t SecondLevelPageStart;
894 uint32_t LSDAStart;
895 };
896
897 SmallVector<IndexEntry, 4> IndexEntries;
898
899 outs() << " Top level indices: (count = " << NumIndices << ")\n";
900 Pos = Contents.data() + IndicesStart;
901 for (unsigned i = 0; i < NumIndices; ++i) {
902 IndexEntry Entry;
903
904 Entry.FunctionOffset = readNext<uint32_t>(Pos);
905 Entry.SecondLevelPageStart = readNext<uint32_t>(Pos);
906 Entry.LSDAStart = readNext<uint32_t>(Pos);
907 IndexEntries.push_back(Entry);
908
909 outs() << " [" << i << "]: "
910 << "function offset="
911 << format("0x%08" PRIx32, Entry.FunctionOffset) << ", "
912 << "2nd level page offset="
913 << format("0x%08" PRIx32, Entry.SecondLevelPageStart) << ", "
914 << "LSDA offset="
915 << format("0x%08" PRIx32, Entry.LSDAStart) << '\n';
916 }
917
918
919 //===----------------------------------
920 // Next come the LSDA tables
921 //===----------------------------------
922
923 // The LSDA layout is rather implicit: it's a contiguous array of entries from
924 // the first top-level index's LSDAOffset to the last (sentinel).
925
926 outs() << " LSDA descriptors:\n";
927 Pos = Contents.data() + IndexEntries[0].LSDAStart;
928 int NumLSDAs = (IndexEntries.back().LSDAStart - IndexEntries[0].LSDAStart) /
929 (2 * sizeof(uint32_t));
930 for (int i = 0; i < NumLSDAs; ++i) {
931 uint32_t FunctionOffset = readNext<uint32_t>(Pos);
932 uint32_t LSDAOffset = readNext<uint32_t>(Pos);
933 outs() << " [" << i << "]: "
934 << "function offset="
935 << format("0x%08" PRIx32, FunctionOffset) << ", "
936 << "LSDA offset="
937 << format("0x%08" PRIx32, LSDAOffset) << '\n';
938 }
939
940 //===----------------------------------
941 // Finally, the 2nd level indices
942 //===----------------------------------
943
944 // Generally these are 4K in size, and have 2 possible forms:
945 // + Regular stores up to 511 entries with disparate encodings
946 // + Compressed stores up to 1021 entries if few enough compact encoding
947 // values are used.
948 outs() << " Second level indices:\n";
949 for (unsigned i = 0; i < IndexEntries.size() - 1; ++i) {
950 // The final sentinel top-level index has no associated 2nd level page
951 if (IndexEntries[i].SecondLevelPageStart == 0)
952 break;
953
954 outs() << " Second level index[" << i << "]: "
955 << "offset in section="
956 << format("0x%08" PRIx32, IndexEntries[i].SecondLevelPageStart)
957 << ", "
958 << "base function offset="
959 << format("0x%08" PRIx32, IndexEntries[i].FunctionOffset) << '\n';
960
961 Pos = Contents.data() + IndexEntries[i].SecondLevelPageStart;
Aaron Ballman80930af2014-08-14 13:53:19 +0000962 uint32_t Kind = *reinterpret_cast<const support::ulittle32_t *>(Pos);
Tim Northover39c70bb2014-08-12 11:52:59 +0000963 if (Kind == 2)
964 printRegularSecondLevelUnwindPage(Pos);
965 else if (Kind == 3)
966 printCompressedSecondLevelUnwindPage(Pos, IndexEntries[i].FunctionOffset,
967 CommonEncodings);
968 else
969 llvm_unreachable("Do not know how to print this kind of 2nd level page");
970
971 }
972}
973
Tim Northover4bd286a2014-08-01 13:07:19 +0000974void llvm::printMachOUnwindInfo(const MachOObjectFile *Obj) {
975 std::map<uint64_t, SymbolRef> Symbols;
976 for (const SymbolRef &SymRef : Obj->symbols()) {
977 // Discard any undefined or absolute symbols. They're not going to take part
978 // in the convenience lookup for unwind info and just take up resources.
979 section_iterator Section = Obj->section_end();
980 SymRef.getSection(Section);
981 if (Section == Obj->section_end())
982 continue;
983
984 uint64_t Addr;
985 SymRef.getAddress(Addr);
986 Symbols.insert(std::make_pair(Addr, SymRef));
987 }
988
989 for (const SectionRef &Section : Obj->sections()) {
990 StringRef SectName;
991 Section.getName(SectName);
992 if (SectName == "__compact_unwind")
993 printMachOCompactUnwindSection(Obj, Symbols, Section);
994 else if (SectName == "__unwind_info")
Tim Northover39c70bb2014-08-12 11:52:59 +0000995 printMachOUnwindInfoSection(Obj, Symbols, Section);
Tim Northover4bd286a2014-08-01 13:07:19 +0000996 else if (SectName == "__eh_frame")
997 outs() << "llvm-objdump: warning: unhandled __eh_frame section\n";
998
999 }
1000}