1 | //===-- llvm-objdump.cpp - Object file dumping utility for llvm -----------===// |
2 | // |
3 | // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
4 | // See https://llvm.org/LICENSE.txt for license information. |
5 | // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
6 | // |
7 | //===----------------------------------------------------------------------===// |
8 | // |
9 | // This program is a utility that works like binutils "objdump", that is, it |
10 | // dumps out a plethora of information about an object file depending on the |
11 | // flags. |
12 | // |
13 | // The flags and output of this program should be near identical to those of |
14 | // binutils objdump. |
15 | // |
16 | //===----------------------------------------------------------------------===// |
17 | |
18 | #include "llvm-objdump.h" |
19 | #include "COFFDump.h" |
20 | #include "ELFDump.h" |
21 | #include "MachODump.h" |
22 | #include "ObjdumpOptID.h" |
23 | #include "OffloadDump.h" |
24 | #include "SourcePrinter.h" |
25 | #include "WasmDump.h" |
26 | #include "XCOFFDump.h" |
27 | #include "llvm/ADT/STLExtras.h" |
28 | #include "llvm/ADT/SetOperations.h" |
29 | #include "llvm/ADT/StringExtras.h" |
30 | #include "llvm/ADT/StringSet.h" |
31 | #include "llvm/ADT/Twine.h" |
32 | #include "llvm/BinaryFormat/Wasm.h" |
33 | #include "llvm/DebugInfo/BTF/BTFParser.h" |
34 | #include "llvm/DebugInfo/DWARF/DWARFContext.h" |
35 | #include "llvm/DebugInfo/Symbolize/SymbolizableModule.h" |
36 | #include "llvm/DebugInfo/Symbolize/Symbolize.h" |
37 | #include "llvm/Debuginfod/BuildIDFetcher.h" |
38 | #include "llvm/Debuginfod/Debuginfod.h" |
39 | #include "llvm/Debuginfod/HTTPClient.h" |
40 | #include "llvm/Demangle/Demangle.h" |
41 | #include "llvm/MC/MCAsmInfo.h" |
42 | #include "llvm/MC/MCContext.h" |
43 | #include "llvm/MC/MCDisassembler/MCDisassembler.h" |
44 | #include "llvm/MC/MCDisassembler/MCRelocationInfo.h" |
45 | #include "llvm/MC/MCInst.h" |
46 | #include "llvm/MC/MCInstPrinter.h" |
47 | #include "llvm/MC/MCInstrAnalysis.h" |
48 | #include "llvm/MC/MCInstrInfo.h" |
49 | #include "llvm/MC/MCObjectFileInfo.h" |
50 | #include "llvm/MC/MCRegisterInfo.h" |
51 | #include "llvm/MC/MCTargetOptions.h" |
52 | #include "llvm/MC/TargetRegistry.h" |
53 | #include "llvm/Object/Archive.h" |
54 | #include "llvm/Object/BuildID.h" |
55 | #include "llvm/Object/COFF.h" |
56 | #include "llvm/Object/COFFImportFile.h" |
57 | #include "llvm/Object/ELFObjectFile.h" |
58 | #include "llvm/Object/ELFTypes.h" |
59 | #include "llvm/Object/FaultMapParser.h" |
60 | #include "llvm/Object/MachO.h" |
61 | #include "llvm/Object/MachOUniversal.h" |
62 | #include "llvm/Object/ObjectFile.h" |
63 | #include "llvm/Object/OffloadBinary.h" |
64 | #include "llvm/Object/Wasm.h" |
65 | #include "llvm/Option/Arg.h" |
66 | #include "llvm/Option/ArgList.h" |
67 | #include "llvm/Option/Option.h" |
68 | #include "llvm/Support/Casting.h" |
69 | #include "llvm/Support/Debug.h" |
70 | #include "llvm/Support/Errc.h" |
71 | #include "llvm/Support/FileSystem.h" |
72 | #include "llvm/Support/Format.h" |
73 | #include "llvm/Support/FormatVariadic.h" |
74 | #include "llvm/Support/GraphWriter.h" |
75 | #include "llvm/Support/LLVMDriver.h" |
76 | #include "llvm/Support/MemoryBuffer.h" |
77 | #include "llvm/Support/SourceMgr.h" |
78 | #include "llvm/Support/StringSaver.h" |
79 | #include "llvm/Support/TargetSelect.h" |
80 | #include "llvm/Support/WithColor.h" |
81 | #include "llvm/Support/raw_ostream.h" |
82 | #include "llvm/TargetParser/Host.h" |
83 | #include "llvm/TargetParser/Triple.h" |
84 | #include <algorithm> |
85 | #include <cctype> |
86 | #include <cstring> |
87 | #include <optional> |
88 | #include <set> |
89 | #include <system_error> |
90 | #include <unordered_map> |
91 | #include <utility> |
92 | |
93 | using namespace llvm; |
94 | using namespace llvm::object; |
95 | using namespace llvm::objdump; |
96 | using namespace llvm::opt; |
97 | |
98 | namespace { |
99 | |
100 | class CommonOptTable : public opt::GenericOptTable { |
101 | public: |
102 | CommonOptTable(ArrayRef<Info> OptionInfos, const char *Usage, |
103 | const char *Description) |
104 | : opt::GenericOptTable(OptionInfos), Usage(Usage), |
105 | Description(Description) { |
106 | setGroupedShortOptions(true); |
107 | } |
108 | |
109 | void printHelp(StringRef Argv0, bool ShowHidden = false) const { |
110 | Argv0 = sys::path::filename(path: Argv0); |
111 | opt::GenericOptTable::printHelp(OS&: outs(), Usage: (Argv0 + Usage).str().c_str(), |
112 | Title: Description, ShowHidden, ShowAllAliases: ShowHidden); |
113 | // TODO Replace this with OptTable API once it adds extrahelp support. |
114 | outs() << "\nPass @FILE as argument to read options from FILE.\n" ; |
115 | } |
116 | |
117 | private: |
118 | const char *Usage; |
119 | const char *Description; |
120 | }; |
121 | |
122 | // ObjdumpOptID is in ObjdumpOptID.h |
123 | namespace objdump_opt { |
124 | #define PREFIX(NAME, VALUE) \ |
125 | static constexpr StringLiteral NAME##_init[] = VALUE; \ |
126 | static constexpr ArrayRef<StringLiteral> NAME(NAME##_init, \ |
127 | std::size(NAME##_init) - 1); |
128 | #include "ObjdumpOpts.inc" |
129 | #undef PREFIX |
130 | |
131 | static constexpr opt::OptTable::Info ObjdumpInfoTable[] = { |
132 | #define OPTION(...) \ |
133 | LLVM_CONSTRUCT_OPT_INFO_WITH_ID_PREFIX(OBJDUMP_, __VA_ARGS__), |
134 | #include "ObjdumpOpts.inc" |
135 | #undef OPTION |
136 | }; |
137 | } // namespace objdump_opt |
138 | |
139 | class ObjdumpOptTable : public CommonOptTable { |
140 | public: |
141 | ObjdumpOptTable() |
142 | : CommonOptTable(objdump_opt::ObjdumpInfoTable, |
143 | " [options] <input object files>" , |
144 | "llvm object file dumper" ) {} |
145 | }; |
146 | |
147 | enum OtoolOptID { |
148 | OTOOL_INVALID = 0, // This is not an option ID. |
149 | #define OPTION(...) LLVM_MAKE_OPT_ID_WITH_ID_PREFIX(OTOOL_, __VA_ARGS__), |
150 | #include "OtoolOpts.inc" |
151 | #undef OPTION |
152 | }; |
153 | |
154 | namespace otool { |
155 | #define PREFIX(NAME, VALUE) \ |
156 | static constexpr StringLiteral NAME##_init[] = VALUE; \ |
157 | static constexpr ArrayRef<StringLiteral> NAME(NAME##_init, \ |
158 | std::size(NAME##_init) - 1); |
159 | #include "OtoolOpts.inc" |
160 | #undef PREFIX |
161 | |
162 | static constexpr opt::OptTable::Info OtoolInfoTable[] = { |
163 | #define OPTION(...) LLVM_CONSTRUCT_OPT_INFO_WITH_ID_PREFIX(OTOOL_, __VA_ARGS__), |
164 | #include "OtoolOpts.inc" |
165 | #undef OPTION |
166 | }; |
167 | } // namespace otool |
168 | |
169 | class OtoolOptTable : public CommonOptTable { |
170 | public: |
171 | OtoolOptTable() |
172 | : CommonOptTable(otool::OtoolInfoTable, " [option...] [file...]" , |
173 | "Mach-O object file displaying tool" ) {} |
174 | }; |
175 | |
176 | struct BBAddrMapLabel { |
177 | std::string BlockLabel; |
178 | std::string PGOAnalysis; |
179 | }; |
180 | |
181 | // This class represents the BBAddrMap and PGOMap associated with a single |
182 | // function. |
183 | class BBAddrMapFunctionEntry { |
184 | public: |
185 | BBAddrMapFunctionEntry(BBAddrMap AddrMap, PGOAnalysisMap PGOMap) |
186 | : AddrMap(std::move(AddrMap)), PGOMap(std::move(PGOMap)) {} |
187 | |
188 | const BBAddrMap &getAddrMap() const { return AddrMap; } |
189 | |
190 | // Returns the PGO string associated with the entry of index `PGOBBEntryIndex` |
191 | // in `PGOMap`. If PrettyPGOAnalysis is true, prints BFI as relative frequency |
192 | // and BPI as percentage. Otherwise raw values are displayed. |
193 | std::string constructPGOLabelString(size_t PGOBBEntryIndex, |
194 | bool PrettyPGOAnalysis) const { |
195 | if (!PGOMap.FeatEnable.hasPGOAnalysis()) |
196 | return "" ; |
197 | std::string PGOString; |
198 | raw_string_ostream PGOSS(PGOString); |
199 | |
200 | PGOSS << " (" ; |
201 | if (PGOMap.FeatEnable.FuncEntryCount && PGOBBEntryIndex == 0) { |
202 | PGOSS << "Entry count: " << Twine(PGOMap.FuncEntryCount); |
203 | if (PGOMap.FeatEnable.hasPGOAnalysisBBData()) { |
204 | PGOSS << ", " ; |
205 | } |
206 | } |
207 | |
208 | if (PGOMap.FeatEnable.hasPGOAnalysisBBData()) { |
209 | |
210 | assert(PGOBBEntryIndex < PGOMap.BBEntries.size() && |
211 | "Expected PGOAnalysisMap and BBAddrMap to have the same entries" ); |
212 | const PGOAnalysisMap::PGOBBEntry &PGOBBEntry = |
213 | PGOMap.BBEntries[PGOBBEntryIndex]; |
214 | |
215 | if (PGOMap.FeatEnable.BBFreq) { |
216 | PGOSS << "Frequency: " ; |
217 | if (PrettyPGOAnalysis) |
218 | printRelativeBlockFreq(OS&: PGOSS, EntryFreq: PGOMap.BBEntries.front().BlockFreq, |
219 | Freq: PGOBBEntry.BlockFreq); |
220 | else |
221 | PGOSS << Twine(PGOBBEntry.BlockFreq.getFrequency()); |
222 | if (PGOMap.FeatEnable.BrProb && PGOBBEntry.Successors.size() > 0) { |
223 | PGOSS << ", " ; |
224 | } |
225 | } |
226 | if (PGOMap.FeatEnable.BrProb && PGOBBEntry.Successors.size() > 0) { |
227 | PGOSS << "Successors: " ; |
228 | interleaveComma( |
229 | c: PGOBBEntry.Successors, os&: PGOSS, |
230 | each_fn: [&](const PGOAnalysisMap::PGOBBEntry::SuccessorEntry &SE) { |
231 | PGOSS << "BB" << SE.ID << ":" ; |
232 | if (PrettyPGOAnalysis) |
233 | PGOSS << "[" << SE.Prob << "]" ; |
234 | else |
235 | PGOSS.write_hex(N: SE.Prob.getNumerator()); |
236 | }); |
237 | } |
238 | } |
239 | PGOSS << ")" ; |
240 | |
241 | return PGOString; |
242 | } |
243 | |
244 | private: |
245 | const BBAddrMap AddrMap; |
246 | const PGOAnalysisMap PGOMap; |
247 | }; |
248 | |
249 | // This class represents the BBAddrMap and PGOMap of potentially multiple |
250 | // functions in a section. |
251 | class BBAddrMapInfo { |
252 | public: |
253 | void clear() { |
254 | FunctionAddrToMap.clear(); |
255 | RangeBaseAddrToFunctionAddr.clear(); |
256 | } |
257 | |
258 | bool empty() const { return FunctionAddrToMap.empty(); } |
259 | |
260 | void AddFunctionEntry(BBAddrMap AddrMap, PGOAnalysisMap PGOMap) { |
261 | uint64_t FunctionAddr = AddrMap.getFunctionAddress(); |
262 | for (size_t I = 1; I < AddrMap.BBRanges.size(); ++I) |
263 | RangeBaseAddrToFunctionAddr.emplace(args&: AddrMap.BBRanges[I].BaseAddress, |
264 | args&: FunctionAddr); |
265 | [[maybe_unused]] auto R = FunctionAddrToMap.try_emplace( |
266 | k: FunctionAddr, args: std::move(AddrMap), args: std::move(PGOMap)); |
267 | assert(R.second && "duplicate function address" ); |
268 | } |
269 | |
270 | // Returns the BBAddrMap entry for the function associated with `BaseAddress`. |
271 | // `BaseAddress` could be the function address or the address of a range |
272 | // associated with that function. Returns `nullptr` if `BaseAddress` is not |
273 | // mapped to any entry. |
274 | const BBAddrMapFunctionEntry *getEntryForAddress(uint64_t BaseAddress) const { |
275 | uint64_t FunctionAddr = BaseAddress; |
276 | auto S = RangeBaseAddrToFunctionAddr.find(x: BaseAddress); |
277 | if (S != RangeBaseAddrToFunctionAddr.end()) |
278 | FunctionAddr = S->second; |
279 | auto R = FunctionAddrToMap.find(x: FunctionAddr); |
280 | if (R == FunctionAddrToMap.end()) |
281 | return nullptr; |
282 | return &R->second; |
283 | } |
284 | |
285 | private: |
286 | std::unordered_map<uint64_t, BBAddrMapFunctionEntry> FunctionAddrToMap; |
287 | std::unordered_map<uint64_t, uint64_t> RangeBaseAddrToFunctionAddr; |
288 | }; |
289 | |
290 | } // namespace |
291 | |
292 | #define DEBUG_TYPE "objdump" |
293 | |
294 | enum class ColorOutput { |
295 | Auto, |
296 | Enable, |
297 | Disable, |
298 | Invalid, |
299 | }; |
300 | |
301 | static uint64_t AdjustVMA; |
302 | static bool ; |
303 | static std::string ArchName; |
304 | bool objdump::; |
305 | bool objdump::Demangle; |
306 | bool objdump::Disassemble; |
307 | bool objdump::DisassembleAll; |
308 | bool objdump::SymbolDescription; |
309 | bool objdump::TracebackTable; |
310 | static std::vector<std::string> DisassembleSymbols; |
311 | static bool DisassembleZeroes; |
312 | static std::vector<std::string> DisassemblerOptions; |
313 | static ColorOutput DisassemblyColor; |
314 | DIDumpType objdump::DwarfDumpType; |
315 | static bool DynamicRelocations; |
316 | static bool FaultMapSection; |
317 | static bool ; |
318 | bool objdump::SectionContents; |
319 | static std::vector<std::string> InputFilenames; |
320 | bool objdump::PrintLines; |
321 | static bool MachOOpt; |
322 | std::string objdump::MCPU; |
323 | std::vector<std::string> objdump::MAttrs; |
324 | bool objdump::ShowRawInsn; |
325 | bool objdump::LeadingAddr; |
326 | static bool Offloading; |
327 | static bool RawClangAST; |
328 | bool objdump::Relocations; |
329 | bool objdump::PrintImmHex; |
330 | bool objdump::; |
331 | std::vector<std::string> objdump::FilterSections; |
332 | bool objdump::; |
333 | static bool ShowAllSymbols; |
334 | static bool ShowLMA; |
335 | bool objdump::PrintSource; |
336 | |
337 | static uint64_t StartAddress; |
338 | static bool HasStartAddressFlag; |
339 | static uint64_t StopAddress = UINT64_MAX; |
340 | static bool HasStopAddressFlag; |
341 | |
342 | bool objdump::SymbolTable; |
343 | static bool SymbolizeOperands; |
344 | static bool PrettyPGOAnalysisMap; |
345 | static bool DynamicSymbolTable; |
346 | std::string objdump::TripleName; |
347 | bool objdump::UnwindInfo; |
348 | static bool Wide; |
349 | std::string objdump::Prefix; |
350 | uint32_t objdump::PrefixStrip; |
351 | |
352 | DebugVarsFormat objdump::DbgVariables = DVDisabled; |
353 | |
354 | int objdump::DbgIndent = 52; |
355 | |
356 | static StringSet<> DisasmSymbolSet; |
357 | StringSet<> objdump::FoundSectionSet; |
358 | static StringRef ToolName; |
359 | |
360 | std::unique_ptr<BuildIDFetcher> BIDFetcher; |
361 | |
362 | Dumper::Dumper(const object::ObjectFile &O) : O(O) { |
363 | WarningHandler = [this](const Twine &Msg) { |
364 | if (Warnings.insert(key: Msg.str()).second) |
365 | reportWarning(Message: Msg, File: this->O.getFileName()); |
366 | return Error::success(); |
367 | }; |
368 | } |
369 | |
370 | void Dumper::reportUniqueWarning(Error Err) { |
371 | reportUniqueWarning(Msg: toString(E: std::move(Err))); |
372 | } |
373 | |
374 | void Dumper::reportUniqueWarning(const Twine &Msg) { |
375 | cantFail(Err: WarningHandler(Msg)); |
376 | } |
377 | |
378 | static Expected<std::unique_ptr<Dumper>> createDumper(const ObjectFile &Obj) { |
379 | if (const auto *O = dyn_cast<COFFObjectFile>(Val: &Obj)) |
380 | return createCOFFDumper(Obj: *O); |
381 | if (const auto *O = dyn_cast<ELFObjectFileBase>(Val: &Obj)) |
382 | return createELFDumper(Obj: *O); |
383 | if (const auto *O = dyn_cast<MachOObjectFile>(Val: &Obj)) |
384 | return createMachODumper(Obj: *O); |
385 | if (const auto *O = dyn_cast<WasmObjectFile>(Val: &Obj)) |
386 | return createWasmDumper(Obj: *O); |
387 | if (const auto *O = dyn_cast<XCOFFObjectFile>(Val: &Obj)) |
388 | return createXCOFFDumper(Obj: *O); |
389 | |
390 | return createStringError(EC: errc::invalid_argument, |
391 | S: "unsupported object file format" ); |
392 | } |
393 | |
394 | namespace { |
395 | struct FilterResult { |
396 | // True if the section should not be skipped. |
397 | bool Keep; |
398 | |
399 | // True if the index counter should be incremented, even if the section should |
400 | // be skipped. For example, sections may be skipped if they are not included |
401 | // in the --section flag, but we still want those to count toward the section |
402 | // count. |
403 | bool IncrementIndex; |
404 | }; |
405 | } // namespace |
406 | |
407 | static FilterResult checkSectionFilter(object::SectionRef S) { |
408 | if (FilterSections.empty()) |
409 | return {/*Keep=*/true, /*IncrementIndex=*/true}; |
410 | |
411 | Expected<StringRef> SecNameOrErr = S.getName(); |
412 | if (!SecNameOrErr) { |
413 | consumeError(Err: SecNameOrErr.takeError()); |
414 | return {/*Keep=*/false, /*IncrementIndex=*/false}; |
415 | } |
416 | StringRef SecName = *SecNameOrErr; |
417 | |
418 | // StringSet does not allow empty key so avoid adding sections with |
419 | // no name (such as the section with index 0) here. |
420 | if (!SecName.empty()) |
421 | FoundSectionSet.insert(key: SecName); |
422 | |
423 | // Only show the section if it's in the FilterSections list, but always |
424 | // increment so the indexing is stable. |
425 | return {/*Keep=*/is_contained(Range&: FilterSections, Element: SecName), |
426 | /*IncrementIndex=*/true}; |
427 | } |
428 | |
429 | SectionFilter objdump::ToolSectionFilter(object::ObjectFile const &O, |
430 | uint64_t *Idx) { |
431 | // Start at UINT64_MAX so that the first index returned after an increment is |
432 | // zero (after the unsigned wrap). |
433 | if (Idx) |
434 | *Idx = UINT64_MAX; |
435 | return SectionFilter( |
436 | [Idx](object::SectionRef S) { |
437 | FilterResult Result = checkSectionFilter(S); |
438 | if (Idx != nullptr && Result.IncrementIndex) |
439 | *Idx += 1; |
440 | return Result.Keep; |
441 | }, |
442 | O); |
443 | } |
444 | |
445 | std::string objdump::getFileNameForError(const object::Archive::Child &C, |
446 | unsigned Index) { |
447 | Expected<StringRef> NameOrErr = C.getName(); |
448 | if (NameOrErr) |
449 | return std::string(NameOrErr.get()); |
450 | // If we have an error getting the name then we print the index of the archive |
451 | // member. Since we are already in an error state, we just ignore this error. |
452 | consumeError(Err: NameOrErr.takeError()); |
453 | return "<file index: " + std::to_string(val: Index) + ">" ; |
454 | } |
455 | |
456 | void objdump::reportWarning(const Twine &Message, StringRef File) { |
457 | // Output order between errs() and outs() matters especially for archive |
458 | // files where the output is per member object. |
459 | outs().flush(); |
460 | WithColor::warning(OS&: errs(), Prefix: ToolName) |
461 | << "'" << File << "': " << Message << "\n" ; |
462 | } |
463 | |
464 | [[noreturn]] void objdump::reportError(StringRef File, const Twine &Message) { |
465 | outs().flush(); |
466 | WithColor::error(OS&: errs(), Prefix: ToolName) << "'" << File << "': " << Message << "\n" ; |
467 | exit(status: 1); |
468 | } |
469 | |
470 | [[noreturn]] void objdump::reportError(Error E, StringRef FileName, |
471 | StringRef ArchiveName, |
472 | StringRef ArchitectureName) { |
473 | assert(E); |
474 | outs().flush(); |
475 | WithColor::error(OS&: errs(), Prefix: ToolName); |
476 | if (ArchiveName != "" ) |
477 | errs() << ArchiveName << "(" << FileName << ")" ; |
478 | else |
479 | errs() << "'" << FileName << "'" ; |
480 | if (!ArchitectureName.empty()) |
481 | errs() << " (for architecture " << ArchitectureName << ")" ; |
482 | errs() << ": " ; |
483 | logAllUnhandledErrors(E: std::move(E), OS&: errs()); |
484 | exit(status: 1); |
485 | } |
486 | |
487 | static void reportCmdLineWarning(const Twine &Message) { |
488 | WithColor::warning(OS&: errs(), Prefix: ToolName) << Message << "\n" ; |
489 | } |
490 | |
491 | [[noreturn]] static void reportCmdLineError(const Twine &Message) { |
492 | WithColor::error(OS&: errs(), Prefix: ToolName) << Message << "\n" ; |
493 | exit(status: 1); |
494 | } |
495 | |
496 | static void warnOnNoMatchForSections() { |
497 | SetVector<StringRef> MissingSections; |
498 | for (StringRef S : FilterSections) { |
499 | if (FoundSectionSet.count(Key: S)) |
500 | return; |
501 | // User may specify a unnamed section. Don't warn for it. |
502 | if (!S.empty()) |
503 | MissingSections.insert(X: S); |
504 | } |
505 | |
506 | // Warn only if no section in FilterSections is matched. |
507 | for (StringRef S : MissingSections) |
508 | reportCmdLineWarning(Message: "section '" + S + |
509 | "' mentioned in a -j/--section option, but not " |
510 | "found in any input file" ); |
511 | } |
512 | |
513 | static const Target *getTarget(const ObjectFile *Obj) { |
514 | // Figure out the target triple. |
515 | Triple TheTriple("unknown-unknown-unknown" ); |
516 | if (TripleName.empty()) { |
517 | TheTriple = Obj->makeTriple(); |
518 | } else { |
519 | TheTriple.setTriple(Triple::normalize(Str: TripleName)); |
520 | auto Arch = Obj->getArch(); |
521 | if (Arch == Triple::arm || Arch == Triple::armeb) |
522 | Obj->setARMSubArch(TheTriple); |
523 | } |
524 | |
525 | // Get the target specific parser. |
526 | std::string Error; |
527 | const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple, |
528 | Error); |
529 | if (!TheTarget) |
530 | reportError(File: Obj->getFileName(), Message: "can't find target: " + Error); |
531 | |
532 | // Update the triple name and return the found target. |
533 | TripleName = TheTriple.getTriple(); |
534 | return TheTarget; |
535 | } |
536 | |
537 | bool objdump::isRelocAddressLess(RelocationRef A, RelocationRef B) { |
538 | return A.getOffset() < B.getOffset(); |
539 | } |
540 | |
541 | static Error getRelocationValueString(const RelocationRef &Rel, |
542 | bool SymbolDescription, |
543 | SmallVectorImpl<char> &Result) { |
544 | const ObjectFile *Obj = Rel.getObject(); |
545 | if (auto *ELF = dyn_cast<ELFObjectFileBase>(Val: Obj)) |
546 | return getELFRelocationValueString(Obj: ELF, Rel, Result); |
547 | if (auto *COFF = dyn_cast<COFFObjectFile>(Val: Obj)) |
548 | return getCOFFRelocationValueString(Obj: COFF, Rel, Result); |
549 | if (auto *Wasm = dyn_cast<WasmObjectFile>(Val: Obj)) |
550 | return getWasmRelocationValueString(Obj: Wasm, RelRef: Rel, Result); |
551 | if (auto *MachO = dyn_cast<MachOObjectFile>(Val: Obj)) |
552 | return getMachORelocationValueString(Obj: MachO, RelRef: Rel, Result); |
553 | if (auto *XCOFF = dyn_cast<XCOFFObjectFile>(Val: Obj)) |
554 | return getXCOFFRelocationValueString(Obj: *XCOFF, RelRef: Rel, SymbolDescription, |
555 | Result); |
556 | llvm_unreachable("unknown object file format" ); |
557 | } |
558 | |
559 | /// Indicates whether this relocation should hidden when listing |
560 | /// relocations, usually because it is the trailing part of a multipart |
561 | /// relocation that will be printed as part of the leading relocation. |
562 | static bool getHidden(RelocationRef RelRef) { |
563 | auto *MachO = dyn_cast<MachOObjectFile>(Val: RelRef.getObject()); |
564 | if (!MachO) |
565 | return false; |
566 | |
567 | unsigned Arch = MachO->getArch(); |
568 | DataRefImpl Rel = RelRef.getRawDataRefImpl(); |
569 | uint64_t Type = MachO->getRelocationType(Rel); |
570 | |
571 | // On arches that use the generic relocations, GENERIC_RELOC_PAIR |
572 | // is always hidden. |
573 | if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc) |
574 | return Type == MachO::GENERIC_RELOC_PAIR; |
575 | |
576 | if (Arch == Triple::x86_64) { |
577 | // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows |
578 | // an X86_64_RELOC_SUBTRACTOR. |
579 | if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) { |
580 | DataRefImpl RelPrev = Rel; |
581 | RelPrev.d.a--; |
582 | uint64_t PrevType = MachO->getRelocationType(Rel: RelPrev); |
583 | if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR) |
584 | return true; |
585 | } |
586 | } |
587 | |
588 | return false; |
589 | } |
590 | |
591 | /// Get the column at which we want to start printing the instruction |
592 | /// disassembly, taking into account anything which appears to the left of it. |
593 | unsigned objdump::getInstStartColumn(const MCSubtargetInfo &STI) { |
594 | return !ShowRawInsn ? 16 : STI.getTargetTriple().isX86() ? 40 : 24; |
595 | } |
596 | |
597 | static void AlignToInstStartColumn(size_t Start, const MCSubtargetInfo &STI, |
598 | raw_ostream &OS) { |
599 | // The output of printInst starts with a tab. Print some spaces so that |
600 | // the tab has 1 column and advances to the target tab stop. |
601 | unsigned TabStop = getInstStartColumn(STI); |
602 | unsigned Column = OS.tell() - Start; |
603 | OS.indent(NumSpaces: Column < TabStop - 1 ? TabStop - 1 - Column : 7 - Column % 8); |
604 | } |
605 | |
606 | void objdump::printRawData(ArrayRef<uint8_t> Bytes, uint64_t Address, |
607 | formatted_raw_ostream &OS, |
608 | MCSubtargetInfo const &STI) { |
609 | size_t Start = OS.tell(); |
610 | if (LeadingAddr) |
611 | OS << format(Fmt: "%8" PRIx64 ":" , Vals: Address); |
612 | if (ShowRawInsn) { |
613 | OS << ' '; |
614 | dumpBytes(Bytes, OS); |
615 | } |
616 | AlignToInstStartColumn(Start, STI, OS); |
617 | } |
618 | |
619 | namespace { |
620 | |
621 | static bool isAArch64Elf(const ObjectFile &Obj) { |
622 | const auto *Elf = dyn_cast<ELFObjectFileBase>(Val: &Obj); |
623 | return Elf && Elf->getEMachine() == ELF::EM_AARCH64; |
624 | } |
625 | |
626 | static bool isArmElf(const ObjectFile &Obj) { |
627 | const auto *Elf = dyn_cast<ELFObjectFileBase>(Val: &Obj); |
628 | return Elf && Elf->getEMachine() == ELF::EM_ARM; |
629 | } |
630 | |
631 | static bool isCSKYElf(const ObjectFile &Obj) { |
632 | const auto *Elf = dyn_cast<ELFObjectFileBase>(Val: &Obj); |
633 | return Elf && Elf->getEMachine() == ELF::EM_CSKY; |
634 | } |
635 | |
636 | static bool hasMappingSymbols(const ObjectFile &Obj) { |
637 | return isArmElf(Obj) || isAArch64Elf(Obj) || isCSKYElf(Obj) ; |
638 | } |
639 | |
640 | static void printRelocation(formatted_raw_ostream &OS, StringRef FileName, |
641 | const RelocationRef &Rel, uint64_t Address, |
642 | bool Is64Bits) { |
643 | StringRef Fmt = Is64Bits ? "%016" PRIx64 ": " : "%08" PRIx64 ": " ; |
644 | SmallString<16> Name; |
645 | SmallString<32> Val; |
646 | Rel.getTypeName(Result&: Name); |
647 | if (Error E = getRelocationValueString(Rel, SymbolDescription, Result&: Val)) |
648 | reportError(E: std::move(E), FileName); |
649 | OS << (Is64Bits || !LeadingAddr ? "\t\t" : "\t\t\t" ); |
650 | if (LeadingAddr) |
651 | OS << format(Fmt: Fmt.data(), Vals: Address); |
652 | OS << Name << "\t" << Val; |
653 | } |
654 | |
655 | static void printBTFRelocation(formatted_raw_ostream &FOS, llvm::BTFParser &BTF, |
656 | object::SectionedAddress Address, |
657 | LiveVariablePrinter &LVP) { |
658 | const llvm::BTF::BPFFieldReloc *Reloc = BTF.findFieldReloc(Address); |
659 | if (!Reloc) |
660 | return; |
661 | |
662 | SmallString<64> Val; |
663 | BTF.symbolize(Reloc, Result&: Val); |
664 | FOS << "\t\t" ; |
665 | if (LeadingAddr) |
666 | FOS << format(Fmt: "%016" PRIx64 ": " , Vals: Address.Address + AdjustVMA); |
667 | FOS << "CO-RE " << Val; |
668 | LVP.printAfterOtherLine(OS&: FOS, AfterInst: true); |
669 | } |
670 | |
671 | class PrettyPrinter { |
672 | public: |
673 | virtual ~PrettyPrinter() = default; |
674 | virtual void |
675 | printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes, |
676 | object::SectionedAddress Address, formatted_raw_ostream &OS, |
677 | StringRef Annot, MCSubtargetInfo const &STI, SourcePrinter *SP, |
678 | StringRef ObjectFilename, std::vector<RelocationRef> *Rels, |
679 | LiveVariablePrinter &LVP) { |
680 | if (SP && (PrintSource || PrintLines)) |
681 | SP->printSourceLine(OS, Address, ObjectFilename, LVP); |
682 | LVP.printBetweenInsts(OS, MustPrint: false); |
683 | |
684 | printRawData(Bytes, Address: Address.Address, OS, STI); |
685 | |
686 | if (MI) { |
687 | // See MCInstPrinter::printInst. On targets where a PC relative immediate |
688 | // is relative to the next instruction and the length of a MCInst is |
689 | // difficult to measure (x86), this is the address of the next |
690 | // instruction. |
691 | uint64_t Addr = |
692 | Address.Address + (STI.getTargetTriple().isX86() ? Bytes.size() : 0); |
693 | IP.printInst(MI, Address: Addr, Annot: "" , STI, OS); |
694 | } else |
695 | OS << "\t<unknown>" ; |
696 | } |
697 | }; |
698 | PrettyPrinter PrettyPrinterInst; |
699 | |
700 | class HexagonPrettyPrinter : public PrettyPrinter { |
701 | public: |
702 | void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address, |
703 | formatted_raw_ostream &OS) { |
704 | uint32_t opcode = |
705 | (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0]; |
706 | if (LeadingAddr) |
707 | OS << format(Fmt: "%8" PRIx64 ":" , Vals: Address); |
708 | if (ShowRawInsn) { |
709 | OS << "\t" ; |
710 | dumpBytes(Bytes: Bytes.slice(N: 0, M: 4), OS); |
711 | OS << format(Fmt: "\t%08" PRIx32, Vals: opcode); |
712 | } |
713 | } |
714 | void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes, |
715 | object::SectionedAddress Address, formatted_raw_ostream &OS, |
716 | StringRef Annot, MCSubtargetInfo const &STI, SourcePrinter *SP, |
717 | StringRef ObjectFilename, std::vector<RelocationRef> *Rels, |
718 | LiveVariablePrinter &LVP) override { |
719 | if (SP && (PrintSource || PrintLines)) |
720 | SP->printSourceLine(OS, Address, ObjectFilename, LVP, Delimiter: "" ); |
721 | if (!MI) { |
722 | printLead(Bytes, Address: Address.Address, OS); |
723 | OS << " <unknown>" ; |
724 | return; |
725 | } |
726 | std::string Buffer; |
727 | { |
728 | raw_string_ostream TempStream(Buffer); |
729 | IP.printInst(MI, Address: Address.Address, Annot: "" , STI, OS&: TempStream); |
730 | } |
731 | StringRef Contents(Buffer); |
732 | // Split off bundle attributes |
733 | auto PacketBundle = Contents.rsplit(Separator: '\n'); |
734 | // Split off first instruction from the rest |
735 | auto HeadTail = PacketBundle.first.split(Separator: '\n'); |
736 | auto Preamble = " { " ; |
737 | auto Separator = "" ; |
738 | |
739 | // Hexagon's packets require relocations to be inline rather than |
740 | // clustered at the end of the packet. |
741 | std::vector<RelocationRef>::const_iterator RelCur = Rels->begin(); |
742 | std::vector<RelocationRef>::const_iterator RelEnd = Rels->end(); |
743 | auto PrintReloc = [&]() -> void { |
744 | while ((RelCur != RelEnd) && (RelCur->getOffset() <= Address.Address)) { |
745 | if (RelCur->getOffset() == Address.Address) { |
746 | printRelocation(OS, FileName: ObjectFilename, Rel: *RelCur, Address: Address.Address, Is64Bits: false); |
747 | return; |
748 | } |
749 | ++RelCur; |
750 | } |
751 | }; |
752 | |
753 | while (!HeadTail.first.empty()) { |
754 | OS << Separator; |
755 | Separator = "\n" ; |
756 | if (SP && (PrintSource || PrintLines)) |
757 | SP->printSourceLine(OS, Address, ObjectFilename, LVP, Delimiter: "" ); |
758 | printLead(Bytes, Address: Address.Address, OS); |
759 | OS << Preamble; |
760 | Preamble = " " ; |
761 | StringRef Inst; |
762 | auto Duplex = HeadTail.first.split(Separator: '\v'); |
763 | if (!Duplex.second.empty()) { |
764 | OS << Duplex.first; |
765 | OS << "; " ; |
766 | Inst = Duplex.second; |
767 | } |
768 | else |
769 | Inst = HeadTail.first; |
770 | OS << Inst; |
771 | HeadTail = HeadTail.second.split(Separator: '\n'); |
772 | if (HeadTail.first.empty()) |
773 | OS << " } " << PacketBundle.second; |
774 | PrintReloc(); |
775 | Bytes = Bytes.slice(N: 4); |
776 | Address.Address += 4; |
777 | } |
778 | } |
779 | }; |
780 | HexagonPrettyPrinter HexagonPrettyPrinterInst; |
781 | |
782 | class AMDGCNPrettyPrinter : public PrettyPrinter { |
783 | public: |
784 | void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes, |
785 | object::SectionedAddress Address, formatted_raw_ostream &OS, |
786 | StringRef Annot, MCSubtargetInfo const &STI, SourcePrinter *SP, |
787 | StringRef ObjectFilename, std::vector<RelocationRef> *Rels, |
788 | LiveVariablePrinter &LVP) override { |
789 | if (SP && (PrintSource || PrintLines)) |
790 | SP->printSourceLine(OS, Address, ObjectFilename, LVP); |
791 | |
792 | if (MI) { |
793 | SmallString<40> InstStr; |
794 | raw_svector_ostream IS(InstStr); |
795 | |
796 | IP.printInst(MI, Address: Address.Address, Annot: "" , STI, OS&: IS); |
797 | |
798 | OS << left_justify(Str: IS.str(), Width: 60); |
799 | } else { |
800 | // an unrecognized encoding - this is probably data so represent it |
801 | // using the .long directive, or .byte directive if fewer than 4 bytes |
802 | // remaining |
803 | if (Bytes.size() >= 4) { |
804 | OS << format( |
805 | Fmt: "\t.long 0x%08" PRIx32 " " , |
806 | Vals: support::endian::read32<llvm::endianness::little>(P: Bytes.data())); |
807 | OS.indent(NumSpaces: 42); |
808 | } else { |
809 | OS << format(Fmt: "\t.byte 0x%02" PRIx8, Vals: Bytes[0]); |
810 | for (unsigned int i = 1; i < Bytes.size(); i++) |
811 | OS << format(Fmt: ", 0x%02" PRIx8, Vals: Bytes[i]); |
812 | OS.indent(NumSpaces: 55 - (6 * Bytes.size())); |
813 | } |
814 | } |
815 | |
816 | OS << format(Fmt: "// %012" PRIX64 ":" , Vals: Address.Address); |
817 | if (Bytes.size() >= 4) { |
818 | // D should be casted to uint32_t here as it is passed by format to |
819 | // snprintf as vararg. |
820 | for (uint32_t D : |
821 | ArrayRef(reinterpret_cast<const support::little32_t *>(Bytes.data()), |
822 | Bytes.size() / 4)) |
823 | OS << format(Fmt: " %08" PRIX32, Vals: D); |
824 | } else { |
825 | for (unsigned char B : Bytes) |
826 | OS << format(Fmt: " %02" PRIX8, Vals: B); |
827 | } |
828 | |
829 | if (!Annot.empty()) |
830 | OS << " // " << Annot; |
831 | } |
832 | }; |
833 | AMDGCNPrettyPrinter AMDGCNPrettyPrinterInst; |
834 | |
835 | class BPFPrettyPrinter : public PrettyPrinter { |
836 | public: |
837 | void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes, |
838 | object::SectionedAddress Address, formatted_raw_ostream &OS, |
839 | StringRef Annot, MCSubtargetInfo const &STI, SourcePrinter *SP, |
840 | StringRef ObjectFilename, std::vector<RelocationRef> *Rels, |
841 | LiveVariablePrinter &LVP) override { |
842 | if (SP && (PrintSource || PrintLines)) |
843 | SP->printSourceLine(OS, Address, ObjectFilename, LVP); |
844 | if (LeadingAddr) |
845 | OS << format(Fmt: "%8" PRId64 ":" , Vals: Address.Address / 8); |
846 | if (ShowRawInsn) { |
847 | OS << "\t" ; |
848 | dumpBytes(Bytes, OS); |
849 | } |
850 | if (MI) |
851 | IP.printInst(MI, Address: Address.Address, Annot: "" , STI, OS); |
852 | else |
853 | OS << "\t<unknown>" ; |
854 | } |
855 | }; |
856 | BPFPrettyPrinter BPFPrettyPrinterInst; |
857 | |
858 | class ARMPrettyPrinter : public PrettyPrinter { |
859 | public: |
860 | void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes, |
861 | object::SectionedAddress Address, formatted_raw_ostream &OS, |
862 | StringRef Annot, MCSubtargetInfo const &STI, SourcePrinter *SP, |
863 | StringRef ObjectFilename, std::vector<RelocationRef> *Rels, |
864 | LiveVariablePrinter &LVP) override { |
865 | if (SP && (PrintSource || PrintLines)) |
866 | SP->printSourceLine(OS, Address, ObjectFilename, LVP); |
867 | LVP.printBetweenInsts(OS, MustPrint: false); |
868 | |
869 | size_t Start = OS.tell(); |
870 | if (LeadingAddr) |
871 | OS << format(Fmt: "%8" PRIx64 ":" , Vals: Address.Address); |
872 | if (ShowRawInsn) { |
873 | size_t Pos = 0, End = Bytes.size(); |
874 | if (STI.checkFeatures(FS: "+thumb-mode" )) { |
875 | for (; Pos + 2 <= End; Pos += 2) |
876 | OS << ' ' |
877 | << format_hex_no_prefix( |
878 | N: llvm::support::endian::read<uint16_t>( |
879 | memory: Bytes.data() + Pos, endian: InstructionEndianness), |
880 | Width: 4); |
881 | } else { |
882 | for (; Pos + 4 <= End; Pos += 4) |
883 | OS << ' ' |
884 | << format_hex_no_prefix( |
885 | N: llvm::support::endian::read<uint32_t>( |
886 | memory: Bytes.data() + Pos, endian: InstructionEndianness), |
887 | Width: 8); |
888 | } |
889 | if (Pos < End) { |
890 | OS << ' '; |
891 | dumpBytes(Bytes: Bytes.slice(N: Pos), OS); |
892 | } |
893 | } |
894 | |
895 | AlignToInstStartColumn(Start, STI, OS); |
896 | |
897 | if (MI) { |
898 | IP.printInst(MI, Address: Address.Address, Annot: "" , STI, OS); |
899 | } else |
900 | OS << "\t<unknown>" ; |
901 | } |
902 | |
903 | void setInstructionEndianness(llvm::endianness Endianness) { |
904 | InstructionEndianness = Endianness; |
905 | } |
906 | |
907 | private: |
908 | llvm::endianness InstructionEndianness = llvm::endianness::little; |
909 | }; |
910 | ARMPrettyPrinter ARMPrettyPrinterInst; |
911 | |
912 | class AArch64PrettyPrinter : public PrettyPrinter { |
913 | public: |
914 | void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes, |
915 | object::SectionedAddress Address, formatted_raw_ostream &OS, |
916 | StringRef Annot, MCSubtargetInfo const &STI, SourcePrinter *SP, |
917 | StringRef ObjectFilename, std::vector<RelocationRef> *Rels, |
918 | LiveVariablePrinter &LVP) override { |
919 | if (SP && (PrintSource || PrintLines)) |
920 | SP->printSourceLine(OS, Address, ObjectFilename, LVP); |
921 | LVP.printBetweenInsts(OS, MustPrint: false); |
922 | |
923 | size_t Start = OS.tell(); |
924 | if (LeadingAddr) |
925 | OS << format(Fmt: "%8" PRIx64 ":" , Vals: Address.Address); |
926 | if (ShowRawInsn) { |
927 | size_t Pos = 0, End = Bytes.size(); |
928 | for (; Pos + 4 <= End; Pos += 4) |
929 | OS << ' ' |
930 | << format_hex_no_prefix( |
931 | N: llvm::support::endian::read<uint32_t>( |
932 | memory: Bytes.data() + Pos, endian: llvm::endianness::little), |
933 | Width: 8); |
934 | if (Pos < End) { |
935 | OS << ' '; |
936 | dumpBytes(Bytes: Bytes.slice(N: Pos), OS); |
937 | } |
938 | } |
939 | |
940 | AlignToInstStartColumn(Start, STI, OS); |
941 | |
942 | if (MI) { |
943 | IP.printInst(MI, Address: Address.Address, Annot: "" , STI, OS); |
944 | } else |
945 | OS << "\t<unknown>" ; |
946 | } |
947 | }; |
948 | AArch64PrettyPrinter AArch64PrettyPrinterInst; |
949 | |
950 | class RISCVPrettyPrinter : public PrettyPrinter { |
951 | public: |
952 | void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes, |
953 | object::SectionedAddress Address, formatted_raw_ostream &OS, |
954 | StringRef Annot, MCSubtargetInfo const &STI, SourcePrinter *SP, |
955 | StringRef ObjectFilename, std::vector<RelocationRef> *Rels, |
956 | LiveVariablePrinter &LVP) override { |
957 | if (SP && (PrintSource || PrintLines)) |
958 | SP->printSourceLine(OS, Address, ObjectFilename, LVP); |
959 | LVP.printBetweenInsts(OS, MustPrint: false); |
960 | |
961 | size_t Start = OS.tell(); |
962 | if (LeadingAddr) |
963 | OS << format(Fmt: "%8" PRIx64 ":" , Vals: Address.Address); |
964 | if (ShowRawInsn) { |
965 | size_t Pos = 0, End = Bytes.size(); |
966 | if (End % 4 == 0) { |
967 | // 32-bit and 64-bit instructions. |
968 | for (; Pos + 4 <= End; Pos += 4) |
969 | OS << ' ' |
970 | << format_hex_no_prefix( |
971 | N: llvm::support::endian::read<uint32_t>( |
972 | memory: Bytes.data() + Pos, endian: llvm::endianness::little), |
973 | Width: 8); |
974 | } else if (End % 2 == 0) { |
975 | // 16-bit and 48-bits instructions. |
976 | for (; Pos + 2 <= End; Pos += 2) |
977 | OS << ' ' |
978 | << format_hex_no_prefix( |
979 | N: llvm::support::endian::read<uint16_t>( |
980 | memory: Bytes.data() + Pos, endian: llvm::endianness::little), |
981 | Width: 4); |
982 | } |
983 | if (Pos < End) { |
984 | OS << ' '; |
985 | dumpBytes(Bytes: Bytes.slice(N: Pos), OS); |
986 | } |
987 | } |
988 | |
989 | AlignToInstStartColumn(Start, STI, OS); |
990 | |
991 | if (MI) { |
992 | IP.printInst(MI, Address: Address.Address, Annot: "" , STI, OS); |
993 | } else |
994 | OS << "\t<unknown>" ; |
995 | } |
996 | }; |
997 | RISCVPrettyPrinter RISCVPrettyPrinterInst; |
998 | |
999 | PrettyPrinter &selectPrettyPrinter(Triple const &Triple) { |
1000 | switch(Triple.getArch()) { |
1001 | default: |
1002 | return PrettyPrinterInst; |
1003 | case Triple::hexagon: |
1004 | return HexagonPrettyPrinterInst; |
1005 | case Triple::amdgcn: |
1006 | return AMDGCNPrettyPrinterInst; |
1007 | case Triple::bpfel: |
1008 | case Triple::bpfeb: |
1009 | return BPFPrettyPrinterInst; |
1010 | case Triple::arm: |
1011 | case Triple::armeb: |
1012 | case Triple::thumb: |
1013 | case Triple::thumbeb: |
1014 | return ARMPrettyPrinterInst; |
1015 | case Triple::aarch64: |
1016 | case Triple::aarch64_be: |
1017 | case Triple::aarch64_32: |
1018 | return AArch64PrettyPrinterInst; |
1019 | case Triple::riscv32: |
1020 | case Triple::riscv64: |
1021 | return RISCVPrettyPrinterInst; |
1022 | } |
1023 | } |
1024 | |
1025 | class DisassemblerTarget { |
1026 | public: |
1027 | const Target *TheTarget; |
1028 | std::unique_ptr<const MCSubtargetInfo> SubtargetInfo; |
1029 | std::shared_ptr<MCContext> Context; |
1030 | std::unique_ptr<MCDisassembler> DisAsm; |
1031 | std::shared_ptr<MCInstrAnalysis> InstrAnalysis; |
1032 | std::shared_ptr<MCInstPrinter> InstPrinter; |
1033 | PrettyPrinter *Printer; |
1034 | |
1035 | DisassemblerTarget(const Target *TheTarget, ObjectFile &Obj, |
1036 | StringRef TripleName, StringRef MCPU, |
1037 | SubtargetFeatures &Features); |
1038 | DisassemblerTarget(DisassemblerTarget &Other, SubtargetFeatures &Features); |
1039 | |
1040 | private: |
1041 | MCTargetOptions Options; |
1042 | std::shared_ptr<const MCRegisterInfo> RegisterInfo; |
1043 | std::shared_ptr<const MCAsmInfo> AsmInfo; |
1044 | std::shared_ptr<const MCInstrInfo> InstrInfo; |
1045 | std::shared_ptr<MCObjectFileInfo> ObjectFileInfo; |
1046 | }; |
1047 | |
1048 | DisassemblerTarget::DisassemblerTarget(const Target *TheTarget, ObjectFile &Obj, |
1049 | StringRef TripleName, StringRef MCPU, |
1050 | SubtargetFeatures &Features) |
1051 | : TheTarget(TheTarget), |
1052 | Printer(&selectPrettyPrinter(Triple: Triple(TripleName))), |
1053 | RegisterInfo(TheTarget->createMCRegInfo(TT: TripleName)) { |
1054 | if (!RegisterInfo) |
1055 | reportError(File: Obj.getFileName(), Message: "no register info for target " + TripleName); |
1056 | |
1057 | // Set up disassembler. |
1058 | AsmInfo.reset(p: TheTarget->createMCAsmInfo(MRI: *RegisterInfo, TheTriple: TripleName, Options)); |
1059 | if (!AsmInfo) |
1060 | reportError(File: Obj.getFileName(), Message: "no assembly info for target " + TripleName); |
1061 | |
1062 | SubtargetInfo.reset( |
1063 | p: TheTarget->createMCSubtargetInfo(TheTriple: TripleName, CPU: MCPU, Features: Features.getString())); |
1064 | if (!SubtargetInfo) |
1065 | reportError(File: Obj.getFileName(), |
1066 | Message: "no subtarget info for target " + TripleName); |
1067 | InstrInfo.reset(p: TheTarget->createMCInstrInfo()); |
1068 | if (!InstrInfo) |
1069 | reportError(File: Obj.getFileName(), |
1070 | Message: "no instruction info for target " + TripleName); |
1071 | Context = |
1072 | std::make_shared<MCContext>(args: Triple(TripleName), args: AsmInfo.get(), |
1073 | args: RegisterInfo.get(), args: SubtargetInfo.get()); |
1074 | |
1075 | // FIXME: for now initialize MCObjectFileInfo with default values |
1076 | ObjectFileInfo.reset( |
1077 | p: TheTarget->createMCObjectFileInfo(Ctx&: *Context, /*PIC=*/false)); |
1078 | Context->setObjectFileInfo(ObjectFileInfo.get()); |
1079 | |
1080 | DisAsm.reset(p: TheTarget->createMCDisassembler(STI: *SubtargetInfo, Ctx&: *Context)); |
1081 | if (!DisAsm) |
1082 | reportError(File: Obj.getFileName(), Message: "no disassembler for target " + TripleName); |
1083 | |
1084 | if (auto *ELFObj = dyn_cast<ELFObjectFileBase>(Val: &Obj)) |
1085 | DisAsm->setABIVersion(ELFObj->getEIdentABIVersion()); |
1086 | |
1087 | InstrAnalysis.reset(p: TheTarget->createMCInstrAnalysis(Info: InstrInfo.get())); |
1088 | |
1089 | int AsmPrinterVariant = AsmInfo->getAssemblerDialect(); |
1090 | InstPrinter.reset(p: TheTarget->createMCInstPrinter(T: Triple(TripleName), |
1091 | SyntaxVariant: AsmPrinterVariant, MAI: *AsmInfo, |
1092 | MII: *InstrInfo, MRI: *RegisterInfo)); |
1093 | if (!InstPrinter) |
1094 | reportError(File: Obj.getFileName(), |
1095 | Message: "no instruction printer for target " + TripleName); |
1096 | InstPrinter->setPrintImmHex(PrintImmHex); |
1097 | InstPrinter->setPrintBranchImmAsAddress(true); |
1098 | InstPrinter->setSymbolizeOperands(SymbolizeOperands); |
1099 | InstPrinter->setMCInstrAnalysis(InstrAnalysis.get()); |
1100 | |
1101 | switch (DisassemblyColor) { |
1102 | case ColorOutput::Enable: |
1103 | InstPrinter->setUseColor(true); |
1104 | break; |
1105 | case ColorOutput::Auto: |
1106 | InstPrinter->setUseColor(outs().has_colors()); |
1107 | break; |
1108 | case ColorOutput::Disable: |
1109 | case ColorOutput::Invalid: |
1110 | InstPrinter->setUseColor(false); |
1111 | break; |
1112 | }; |
1113 | } |
1114 | |
1115 | DisassemblerTarget::DisassemblerTarget(DisassemblerTarget &Other, |
1116 | SubtargetFeatures &Features) |
1117 | : TheTarget(Other.TheTarget), |
1118 | SubtargetInfo(TheTarget->createMCSubtargetInfo(TheTriple: TripleName, CPU: MCPU, |
1119 | Features: Features.getString())), |
1120 | Context(Other.Context), |
1121 | DisAsm(TheTarget->createMCDisassembler(STI: *SubtargetInfo, Ctx&: *Context)), |
1122 | InstrAnalysis(Other.InstrAnalysis), InstPrinter(Other.InstPrinter), |
1123 | Printer(Other.Printer), RegisterInfo(Other.RegisterInfo), |
1124 | AsmInfo(Other.AsmInfo), InstrInfo(Other.InstrInfo), |
1125 | ObjectFileInfo(Other.ObjectFileInfo) {} |
1126 | } // namespace |
1127 | |
1128 | static uint8_t getElfSymbolType(const ObjectFile &Obj, const SymbolRef &Sym) { |
1129 | assert(Obj.isELF()); |
1130 | if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Val: &Obj)) |
1131 | return unwrapOrError(EO: Elf32LEObj->getSymbol(Sym: Sym.getRawDataRefImpl()), |
1132 | Args: Obj.getFileName()) |
1133 | ->getType(); |
1134 | if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Val: &Obj)) |
1135 | return unwrapOrError(EO: Elf64LEObj->getSymbol(Sym: Sym.getRawDataRefImpl()), |
1136 | Args: Obj.getFileName()) |
1137 | ->getType(); |
1138 | if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Val: &Obj)) |
1139 | return unwrapOrError(EO: Elf32BEObj->getSymbol(Sym: Sym.getRawDataRefImpl()), |
1140 | Args: Obj.getFileName()) |
1141 | ->getType(); |
1142 | if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Val: &Obj)) |
1143 | return unwrapOrError(EO: Elf64BEObj->getSymbol(Sym: Sym.getRawDataRefImpl()), |
1144 | Args: Obj.getFileName()) |
1145 | ->getType(); |
1146 | llvm_unreachable("Unsupported binary format" ); |
1147 | } |
1148 | |
1149 | template <class ELFT> |
1150 | static void |
1151 | addDynamicElfSymbols(const ELFObjectFile<ELFT> &Obj, |
1152 | std::map<SectionRef, SectionSymbolsTy> &AllSymbols) { |
1153 | for (auto Symbol : Obj.getDynamicSymbolIterators()) { |
1154 | uint8_t SymbolType = Symbol.getELFType(); |
1155 | if (SymbolType == ELF::STT_SECTION) |
1156 | continue; |
1157 | |
1158 | uint64_t Address = unwrapOrError(Symbol.getAddress(), Obj.getFileName()); |
1159 | // ELFSymbolRef::getAddress() returns size instead of value for common |
1160 | // symbols which is not desirable for disassembly output. Overriding. |
1161 | if (SymbolType == ELF::STT_COMMON) |
1162 | Address = unwrapOrError(Obj.getSymbol(Symbol.getRawDataRefImpl()), |
1163 | Obj.getFileName()) |
1164 | ->st_value; |
1165 | |
1166 | StringRef Name = unwrapOrError(Symbol.getName(), Obj.getFileName()); |
1167 | if (Name.empty()) |
1168 | continue; |
1169 | |
1170 | section_iterator SecI = |
1171 | unwrapOrError(Symbol.getSection(), Obj.getFileName()); |
1172 | if (SecI == Obj.section_end()) |
1173 | continue; |
1174 | |
1175 | AllSymbols[*SecI].emplace_back(args&: Address, args&: Name, args&: SymbolType); |
1176 | } |
1177 | } |
1178 | |
1179 | static void |
1180 | addDynamicElfSymbols(const ELFObjectFileBase &Obj, |
1181 | std::map<SectionRef, SectionSymbolsTy> &AllSymbols) { |
1182 | if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Val: &Obj)) |
1183 | addDynamicElfSymbols(Obj: *Elf32LEObj, AllSymbols); |
1184 | else if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Val: &Obj)) |
1185 | addDynamicElfSymbols(Obj: *Elf64LEObj, AllSymbols); |
1186 | else if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Val: &Obj)) |
1187 | addDynamicElfSymbols(Obj: *Elf32BEObj, AllSymbols); |
1188 | else if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Val: &Obj)) |
1189 | addDynamicElfSymbols(Obj: *Elf64BEObj, AllSymbols); |
1190 | else |
1191 | llvm_unreachable("Unsupported binary format" ); |
1192 | } |
1193 | |
1194 | static std::optional<SectionRef> getWasmCodeSection(const WasmObjectFile &Obj) { |
1195 | for (auto SecI : Obj.sections()) { |
1196 | const WasmSection &Section = Obj.getWasmSection(Section: SecI); |
1197 | if (Section.Type == wasm::WASM_SEC_CODE) |
1198 | return SecI; |
1199 | } |
1200 | return std::nullopt; |
1201 | } |
1202 | |
1203 | static void |
1204 | addMissingWasmCodeSymbols(const WasmObjectFile &Obj, |
1205 | std::map<SectionRef, SectionSymbolsTy> &AllSymbols) { |
1206 | std::optional<SectionRef> Section = getWasmCodeSection(Obj); |
1207 | if (!Section) |
1208 | return; |
1209 | SectionSymbolsTy &Symbols = AllSymbols[*Section]; |
1210 | |
1211 | std::set<uint64_t> SymbolAddresses; |
1212 | for (const auto &Sym : Symbols) |
1213 | SymbolAddresses.insert(x: Sym.Addr); |
1214 | |
1215 | for (const wasm::WasmFunction &Function : Obj.functions()) { |
1216 | // This adjustment mirrors the one in WasmObjectFile::getSymbolAddress. |
1217 | uint32_t Adjustment = Obj.isRelocatableObject() || Obj.isSharedObject() |
1218 | ? 0 |
1219 | : Section->getAddress(); |
1220 | uint64_t Address = Function.CodeSectionOffset + Adjustment; |
1221 | // Only add fallback symbols for functions not already present in the symbol |
1222 | // table. |
1223 | if (SymbolAddresses.count(x: Address)) |
1224 | continue; |
1225 | // This function has no symbol, so it should have no SymbolName. |
1226 | assert(Function.SymbolName.empty()); |
1227 | // We use DebugName for the name, though it may be empty if there is no |
1228 | // "name" custom section, or that section is missing a name for this |
1229 | // function. |
1230 | StringRef Name = Function.DebugName; |
1231 | Symbols.emplace_back(args&: Address, args&: Name, args: ELF::STT_NOTYPE); |
1232 | } |
1233 | } |
1234 | |
1235 | static void addPltEntries(const ObjectFile &Obj, |
1236 | std::map<SectionRef, SectionSymbolsTy> &AllSymbols, |
1237 | StringSaver &Saver) { |
1238 | auto *ElfObj = dyn_cast<ELFObjectFileBase>(Val: &Obj); |
1239 | if (!ElfObj) |
1240 | return; |
1241 | DenseMap<StringRef, SectionRef> Sections; |
1242 | for (SectionRef Section : Obj.sections()) { |
1243 | Expected<StringRef> SecNameOrErr = Section.getName(); |
1244 | if (!SecNameOrErr) { |
1245 | consumeError(Err: SecNameOrErr.takeError()); |
1246 | continue; |
1247 | } |
1248 | Sections[*SecNameOrErr] = Section; |
1249 | } |
1250 | for (auto Plt : ElfObj->getPltEntries()) { |
1251 | if (Plt.Symbol) { |
1252 | SymbolRef Symbol(*Plt.Symbol, ElfObj); |
1253 | uint8_t SymbolType = getElfSymbolType(Obj, Sym: Symbol); |
1254 | if (Expected<StringRef> NameOrErr = Symbol.getName()) { |
1255 | if (!NameOrErr->empty()) |
1256 | AllSymbols[Sections[Plt.Section]].emplace_back( |
1257 | args&: Plt.Address, args: Saver.save(S: (*NameOrErr + "@plt" ).str()), args&: SymbolType); |
1258 | continue; |
1259 | } else { |
1260 | // The warning has been reported in disassembleObject(). |
1261 | consumeError(Err: NameOrErr.takeError()); |
1262 | } |
1263 | } |
1264 | reportWarning(Message: "PLT entry at 0x" + Twine::utohexstr(Val: Plt.Address) + |
1265 | " references an invalid symbol" , |
1266 | File: Obj.getFileName()); |
1267 | } |
1268 | } |
1269 | |
1270 | // Normally the disassembly output will skip blocks of zeroes. This function |
1271 | // returns the number of zero bytes that can be skipped when dumping the |
1272 | // disassembly of the instructions in Buf. |
1273 | static size_t countSkippableZeroBytes(ArrayRef<uint8_t> Buf) { |
1274 | // Find the number of leading zeroes. |
1275 | size_t N = 0; |
1276 | while (N < Buf.size() && !Buf[N]) |
1277 | ++N; |
1278 | |
1279 | // We may want to skip blocks of zero bytes, but unless we see |
1280 | // at least 8 of them in a row. |
1281 | if (N < 8) |
1282 | return 0; |
1283 | |
1284 | // We skip zeroes in multiples of 4 because do not want to truncate an |
1285 | // instruction if it starts with a zero byte. |
1286 | return N & ~0x3; |
1287 | } |
1288 | |
1289 | // Returns a map from sections to their relocations. |
1290 | static std::map<SectionRef, std::vector<RelocationRef>> |
1291 | getRelocsMap(object::ObjectFile const &Obj) { |
1292 | std::map<SectionRef, std::vector<RelocationRef>> Ret; |
1293 | uint64_t I = (uint64_t)-1; |
1294 | for (SectionRef Sec : Obj.sections()) { |
1295 | ++I; |
1296 | Expected<section_iterator> RelocatedOrErr = Sec.getRelocatedSection(); |
1297 | if (!RelocatedOrErr) |
1298 | reportError(File: Obj.getFileName(), |
1299 | Message: "section (" + Twine(I) + |
1300 | "): failed to get a relocated section: " + |
1301 | toString(E: RelocatedOrErr.takeError())); |
1302 | |
1303 | section_iterator Relocated = *RelocatedOrErr; |
1304 | if (Relocated == Obj.section_end() || !checkSectionFilter(S: *Relocated).Keep) |
1305 | continue; |
1306 | std::vector<RelocationRef> &V = Ret[*Relocated]; |
1307 | append_range(C&: V, R: Sec.relocations()); |
1308 | // Sort relocations by address. |
1309 | llvm::stable_sort(Range&: V, C: isRelocAddressLess); |
1310 | } |
1311 | return Ret; |
1312 | } |
1313 | |
1314 | // Used for --adjust-vma to check if address should be adjusted by the |
1315 | // specified value for a given section. |
1316 | // For ELF we do not adjust non-allocatable sections like debug ones, |
1317 | // because they are not loadable. |
1318 | // TODO: implement for other file formats. |
1319 | static bool shouldAdjustVA(const SectionRef &Section) { |
1320 | const ObjectFile *Obj = Section.getObject(); |
1321 | if (Obj->isELF()) |
1322 | return ELFSectionRef(Section).getFlags() & ELF::SHF_ALLOC; |
1323 | return false; |
1324 | } |
1325 | |
1326 | |
1327 | typedef std::pair<uint64_t, char> MappingSymbolPair; |
1328 | static char getMappingSymbolKind(ArrayRef<MappingSymbolPair> MappingSymbols, |
1329 | uint64_t Address) { |
1330 | auto It = |
1331 | partition_point(Range&: MappingSymbols, P: [Address](const MappingSymbolPair &Val) { |
1332 | return Val.first <= Address; |
1333 | }); |
1334 | // Return zero for any address before the first mapping symbol; this means |
1335 | // we should use the default disassembly mode, depending on the target. |
1336 | if (It == MappingSymbols.begin()) |
1337 | return '\x00'; |
1338 | return (It - 1)->second; |
1339 | } |
1340 | |
1341 | static uint64_t dumpARMELFData(uint64_t SectionAddr, uint64_t Index, |
1342 | uint64_t End, const ObjectFile &Obj, |
1343 | ArrayRef<uint8_t> Bytes, |
1344 | ArrayRef<MappingSymbolPair> MappingSymbols, |
1345 | const MCSubtargetInfo &STI, raw_ostream &OS) { |
1346 | llvm::endianness Endian = |
1347 | Obj.isLittleEndian() ? llvm::endianness::little : llvm::endianness::big; |
1348 | size_t Start = OS.tell(); |
1349 | OS << format(Fmt: "%8" PRIx64 ": " , Vals: SectionAddr + Index); |
1350 | if (Index + 4 <= End) { |
1351 | dumpBytes(Bytes: Bytes.slice(N: Index, M: 4), OS); |
1352 | AlignToInstStartColumn(Start, STI, OS); |
1353 | OS << "\t.word\t" |
1354 | << format_hex(N: support::endian::read32(P: Bytes.data() + Index, E: Endian), |
1355 | Width: 10); |
1356 | return 4; |
1357 | } |
1358 | if (Index + 2 <= End) { |
1359 | dumpBytes(Bytes: Bytes.slice(N: Index, M: 2), OS); |
1360 | AlignToInstStartColumn(Start, STI, OS); |
1361 | OS << "\t.short\t" |
1362 | << format_hex(N: support::endian::read16(P: Bytes.data() + Index, E: Endian), Width: 6); |
1363 | return 2; |
1364 | } |
1365 | dumpBytes(Bytes: Bytes.slice(N: Index, M: 1), OS); |
1366 | AlignToInstStartColumn(Start, STI, OS); |
1367 | OS << "\t.byte\t" << format_hex(N: Bytes[Index], Width: 4); |
1368 | return 1; |
1369 | } |
1370 | |
1371 | static void dumpELFData(uint64_t SectionAddr, uint64_t Index, uint64_t End, |
1372 | ArrayRef<uint8_t> Bytes) { |
1373 | // print out data up to 8 bytes at a time in hex and ascii |
1374 | uint8_t AsciiData[9] = {'\0'}; |
1375 | uint8_t Byte; |
1376 | int NumBytes = 0; |
1377 | |
1378 | for (; Index < End; ++Index) { |
1379 | if (NumBytes == 0) |
1380 | outs() << format(Fmt: "%8" PRIx64 ":" , Vals: SectionAddr + Index); |
1381 | Byte = Bytes.slice(N: Index)[0]; |
1382 | outs() << format(Fmt: " %02x" , Vals: Byte); |
1383 | AsciiData[NumBytes] = isPrint(C: Byte) ? Byte : '.'; |
1384 | |
1385 | uint8_t IndentOffset = 0; |
1386 | NumBytes++; |
1387 | if (Index == End - 1 || NumBytes > 8) { |
1388 | // Indent the space for less than 8 bytes data. |
1389 | // 2 spaces for byte and one for space between bytes |
1390 | IndentOffset = 3 * (8 - NumBytes); |
1391 | for (int Excess = NumBytes; Excess < 8; Excess++) |
1392 | AsciiData[Excess] = '\0'; |
1393 | NumBytes = 8; |
1394 | } |
1395 | if (NumBytes == 8) { |
1396 | AsciiData[8] = '\0'; |
1397 | outs() << std::string(IndentOffset, ' ') << " " ; |
1398 | outs() << reinterpret_cast<char *>(AsciiData); |
1399 | outs() << '\n'; |
1400 | NumBytes = 0; |
1401 | } |
1402 | } |
1403 | } |
1404 | |
1405 | SymbolInfoTy objdump::createSymbolInfo(const ObjectFile &Obj, |
1406 | const SymbolRef &Symbol, |
1407 | bool IsMappingSymbol) { |
1408 | const StringRef FileName = Obj.getFileName(); |
1409 | const uint64_t Addr = unwrapOrError(EO: Symbol.getAddress(), Args: FileName); |
1410 | const StringRef Name = unwrapOrError(EO: Symbol.getName(), Args: FileName); |
1411 | |
1412 | if (Obj.isXCOFF() && (SymbolDescription || TracebackTable)) { |
1413 | const auto &XCOFFObj = cast<XCOFFObjectFile>(Val: Obj); |
1414 | DataRefImpl SymbolDRI = Symbol.getRawDataRefImpl(); |
1415 | |
1416 | const uint32_t SymbolIndex = XCOFFObj.getSymbolIndex(SymEntPtr: SymbolDRI.p); |
1417 | std::optional<XCOFF::StorageMappingClass> Smc = |
1418 | getXCOFFSymbolCsectSMC(Obj: XCOFFObj, Sym: Symbol); |
1419 | return SymbolInfoTy(Smc, Addr, Name, SymbolIndex, |
1420 | isLabel(Obj: XCOFFObj, Sym: Symbol)); |
1421 | } else if (Obj.isXCOFF()) { |
1422 | const SymbolRef::Type SymType = unwrapOrError(EO: Symbol.getType(), Args: FileName); |
1423 | return SymbolInfoTy(Addr, Name, SymType, /*IsMappingSymbol=*/false, |
1424 | /*IsXCOFF=*/true); |
1425 | } else if (Obj.isWasm()) { |
1426 | uint8_t SymType = |
1427 | cast<WasmObjectFile>(Val: &Obj)->getWasmSymbol(Symbol).Info.Kind; |
1428 | return SymbolInfoTy(Addr, Name, SymType, false); |
1429 | } else { |
1430 | uint8_t Type = |
1431 | Obj.isELF() ? getElfSymbolType(Obj, Sym: Symbol) : (uint8_t)ELF::STT_NOTYPE; |
1432 | return SymbolInfoTy(Addr, Name, Type, IsMappingSymbol); |
1433 | } |
1434 | } |
1435 | |
1436 | static SymbolInfoTy createDummySymbolInfo(const ObjectFile &Obj, |
1437 | const uint64_t Addr, StringRef &Name, |
1438 | uint8_t Type) { |
1439 | if (Obj.isXCOFF() && (SymbolDescription || TracebackTable)) |
1440 | return SymbolInfoTy(std::nullopt, Addr, Name, std::nullopt, false); |
1441 | if (Obj.isWasm()) |
1442 | return SymbolInfoTy(Addr, Name, wasm::WASM_SYMBOL_TYPE_SECTION); |
1443 | return SymbolInfoTy(Addr, Name, Type); |
1444 | } |
1445 | |
1446 | static void collectBBAddrMapLabels( |
1447 | const BBAddrMapInfo &FullAddrMap, uint64_t SectionAddr, uint64_t Start, |
1448 | uint64_t End, |
1449 | std::unordered_map<uint64_t, std::vector<BBAddrMapLabel>> &Labels) { |
1450 | if (FullAddrMap.empty()) |
1451 | return; |
1452 | Labels.clear(); |
1453 | uint64_t StartAddress = SectionAddr + Start; |
1454 | uint64_t EndAddress = SectionAddr + End; |
1455 | const BBAddrMapFunctionEntry *FunctionMap = |
1456 | FullAddrMap.getEntryForAddress(BaseAddress: StartAddress); |
1457 | if (!FunctionMap) |
1458 | return; |
1459 | std::optional<size_t> BBRangeIndex = |
1460 | FunctionMap->getAddrMap().getBBRangeIndexForBaseAddress(BaseAddress: StartAddress); |
1461 | if (!BBRangeIndex) |
1462 | return; |
1463 | size_t NumBBEntriesBeforeRange = 0; |
1464 | for (size_t I = 0; I < *BBRangeIndex; ++I) |
1465 | NumBBEntriesBeforeRange += |
1466 | FunctionMap->getAddrMap().BBRanges[I].BBEntries.size(); |
1467 | const auto &BBRange = FunctionMap->getAddrMap().BBRanges[*BBRangeIndex]; |
1468 | for (size_t I = 0; I < BBRange.BBEntries.size(); ++I) { |
1469 | const BBAddrMap::BBEntry &BBEntry = BBRange.BBEntries[I]; |
1470 | uint64_t BBAddress = BBEntry.Offset + BBRange.BaseAddress; |
1471 | if (BBAddress >= EndAddress) |
1472 | continue; |
1473 | |
1474 | std::string LabelString = ("BB" + Twine(BBEntry.ID)).str(); |
1475 | Labels[BBAddress].push_back( |
1476 | x: {.BlockLabel: LabelString, .PGOAnalysis: FunctionMap->constructPGOLabelString( |
1477 | PGOBBEntryIndex: NumBBEntriesBeforeRange + I, PrettyPGOAnalysis: PrettyPGOAnalysisMap)}); |
1478 | } |
1479 | } |
1480 | |
1481 | static void |
1482 | collectLocalBranchTargets(ArrayRef<uint8_t> Bytes, MCInstrAnalysis *MIA, |
1483 | MCDisassembler *DisAsm, MCInstPrinter *IP, |
1484 | const MCSubtargetInfo *STI, uint64_t SectionAddr, |
1485 | uint64_t Start, uint64_t End, |
1486 | std::unordered_map<uint64_t, std::string> &Labels) { |
1487 | // So far only supports PowerPC and X86. |
1488 | const bool isPPC = STI->getTargetTriple().isPPC(); |
1489 | if (!isPPC && !STI->getTargetTriple().isX86()) |
1490 | return; |
1491 | |
1492 | if (MIA) |
1493 | MIA->resetState(); |
1494 | |
1495 | Labels.clear(); |
1496 | unsigned LabelCount = 0; |
1497 | Start += SectionAddr; |
1498 | End += SectionAddr; |
1499 | const bool isXCOFF = STI->getTargetTriple().isOSBinFormatXCOFF(); |
1500 | for (uint64_t Index = Start; Index < End;) { |
1501 | // Disassemble a real instruction and record function-local branch labels. |
1502 | MCInst Inst; |
1503 | uint64_t Size; |
1504 | ArrayRef<uint8_t> ThisBytes = Bytes.slice(N: Index - SectionAddr); |
1505 | bool Disassembled = |
1506 | DisAsm->getInstruction(Instr&: Inst, Size, Bytes: ThisBytes, Address: Index, CStream&: nulls()); |
1507 | if (Size == 0) |
1508 | Size = std::min<uint64_t>(a: ThisBytes.size(), |
1509 | b: DisAsm->suggestBytesToSkip(Bytes: ThisBytes, Address: Index)); |
1510 | |
1511 | if (MIA) { |
1512 | if (Disassembled) { |
1513 | uint64_t Target; |
1514 | bool TargetKnown = MIA->evaluateBranch(Inst, Addr: Index, Size, Target); |
1515 | if (TargetKnown && (Target >= Start && Target < End) && |
1516 | !Labels.count(x: Target)) { |
1517 | // On PowerPC and AIX, a function call is encoded as a branch to 0. |
1518 | // On other PowerPC platforms (ELF), a function call is encoded as |
1519 | // a branch to self. Do not add a label for these cases. |
1520 | if (!(isPPC && |
1521 | ((Target == 0 && isXCOFF) || (Target == Index && !isXCOFF)))) |
1522 | Labels[Target] = ("L" + Twine(LabelCount++)).str(); |
1523 | } |
1524 | MIA->updateState(Inst, Addr: Index); |
1525 | } else |
1526 | MIA->resetState(); |
1527 | } |
1528 | Index += Size; |
1529 | } |
1530 | } |
1531 | |
1532 | // Create an MCSymbolizer for the target and add it to the MCDisassembler. |
1533 | // This is currently only used on AMDGPU, and assumes the format of the |
1534 | // void * argument passed to AMDGPU's createMCSymbolizer. |
1535 | static void addSymbolizer( |
1536 | MCContext &Ctx, const Target *Target, StringRef TripleName, |
1537 | MCDisassembler *DisAsm, uint64_t SectionAddr, ArrayRef<uint8_t> Bytes, |
1538 | SectionSymbolsTy &Symbols, |
1539 | std::vector<std::unique_ptr<std::string>> &SynthesizedLabelNames) { |
1540 | |
1541 | std::unique_ptr<MCRelocationInfo> RelInfo( |
1542 | Target->createMCRelocationInfo(TT: TripleName, Ctx)); |
1543 | if (!RelInfo) |
1544 | return; |
1545 | std::unique_ptr<MCSymbolizer> Symbolizer(Target->createMCSymbolizer( |
1546 | TT: TripleName, GetOpInfo: nullptr, SymbolLookUp: nullptr, DisInfo: &Symbols, Ctx: &Ctx, RelInfo: std::move(RelInfo))); |
1547 | MCSymbolizer *SymbolizerPtr = &*Symbolizer; |
1548 | DisAsm->setSymbolizer(std::move(Symbolizer)); |
1549 | |
1550 | if (!SymbolizeOperands) |
1551 | return; |
1552 | |
1553 | // Synthesize labels referenced by branch instructions by |
1554 | // disassembling, discarding the output, and collecting the referenced |
1555 | // addresses from the symbolizer. |
1556 | for (size_t Index = 0; Index != Bytes.size();) { |
1557 | MCInst Inst; |
1558 | uint64_t Size; |
1559 | ArrayRef<uint8_t> ThisBytes = Bytes.slice(N: Index); |
1560 | const uint64_t ThisAddr = SectionAddr + Index; |
1561 | DisAsm->getInstruction(Instr&: Inst, Size, Bytes: ThisBytes, Address: ThisAddr, CStream&: nulls()); |
1562 | if (Size == 0) |
1563 | Size = std::min<uint64_t>(a: ThisBytes.size(), |
1564 | b: DisAsm->suggestBytesToSkip(Bytes: ThisBytes, Address: Index)); |
1565 | Index += Size; |
1566 | } |
1567 | ArrayRef<uint64_t> LabelAddrsRef = SymbolizerPtr->getReferencedAddresses(); |
1568 | // Copy and sort to remove duplicates. |
1569 | std::vector<uint64_t> LabelAddrs; |
1570 | LabelAddrs.insert(position: LabelAddrs.end(), first: LabelAddrsRef.begin(), |
1571 | last: LabelAddrsRef.end()); |
1572 | llvm::sort(C&: LabelAddrs); |
1573 | LabelAddrs.resize(new_size: llvm::unique(R&: LabelAddrs) - LabelAddrs.begin()); |
1574 | // Add the labels. |
1575 | for (unsigned LabelNum = 0; LabelNum != LabelAddrs.size(); ++LabelNum) { |
1576 | auto Name = std::make_unique<std::string>(); |
1577 | *Name = (Twine("L" ) + Twine(LabelNum)).str(); |
1578 | SynthesizedLabelNames.push_back(x: std::move(Name)); |
1579 | Symbols.push_back(x: SymbolInfoTy( |
1580 | LabelAddrs[LabelNum], *SynthesizedLabelNames.back(), ELF::STT_NOTYPE)); |
1581 | } |
1582 | llvm::stable_sort(Range&: Symbols); |
1583 | // Recreate the symbolizer with the new symbols list. |
1584 | RelInfo.reset(p: Target->createMCRelocationInfo(TT: TripleName, Ctx)); |
1585 | Symbolizer.reset(p: Target->createMCSymbolizer( |
1586 | TT: TripleName, GetOpInfo: nullptr, SymbolLookUp: nullptr, DisInfo: &Symbols, Ctx: &Ctx, RelInfo: std::move(RelInfo))); |
1587 | DisAsm->setSymbolizer(std::move(Symbolizer)); |
1588 | } |
1589 | |
1590 | static StringRef getSegmentName(const MachOObjectFile *MachO, |
1591 | const SectionRef &Section) { |
1592 | if (MachO) { |
1593 | DataRefImpl DR = Section.getRawDataRefImpl(); |
1594 | StringRef SegmentName = MachO->getSectionFinalSegmentName(Sec: DR); |
1595 | return SegmentName; |
1596 | } |
1597 | return "" ; |
1598 | } |
1599 | |
1600 | static void emitPostInstructionInfo(formatted_raw_ostream &FOS, |
1601 | const MCAsmInfo &MAI, |
1602 | const MCSubtargetInfo &STI, |
1603 | StringRef , |
1604 | LiveVariablePrinter &LVP) { |
1605 | do { |
1606 | if (!Comments.empty()) { |
1607 | // Emit a line of comments. |
1608 | StringRef ; |
1609 | std::tie(args&: Comment, args&: Comments) = Comments.split(Separator: '\n'); |
1610 | // MAI.getCommentColumn() assumes that instructions are printed at the |
1611 | // position of 8, while getInstStartColumn() returns the actual position. |
1612 | unsigned CommentColumn = |
1613 | MAI.getCommentColumn() - 8 + getInstStartColumn(STI); |
1614 | FOS.PadToColumn(NewCol: CommentColumn); |
1615 | FOS << MAI.getCommentString() << ' ' << Comment; |
1616 | } |
1617 | LVP.printAfterInst(OS&: FOS); |
1618 | FOS << '\n'; |
1619 | } while (!Comments.empty()); |
1620 | FOS.flush(); |
1621 | } |
1622 | |
1623 | static void createFakeELFSections(ObjectFile &Obj) { |
1624 | assert(Obj.isELF()); |
1625 | if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Val: &Obj)) |
1626 | Elf32LEObj->createFakeSections(); |
1627 | else if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Val: &Obj)) |
1628 | Elf64LEObj->createFakeSections(); |
1629 | else if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Val: &Obj)) |
1630 | Elf32BEObj->createFakeSections(); |
1631 | else if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Val: &Obj)) |
1632 | Elf64BEObj->createFakeSections(); |
1633 | else |
1634 | llvm_unreachable("Unsupported binary format" ); |
1635 | } |
1636 | |
1637 | // Tries to fetch a more complete version of the given object file using its |
1638 | // Build ID. Returns std::nullopt if nothing was found. |
1639 | static std::optional<OwningBinary<Binary>> |
1640 | fetchBinaryByBuildID(const ObjectFile &Obj) { |
1641 | object::BuildIDRef BuildID = getBuildID(Obj: &Obj); |
1642 | if (BuildID.empty()) |
1643 | return std::nullopt; |
1644 | std::optional<std::string> Path = BIDFetcher->fetch(BuildID); |
1645 | if (!Path) |
1646 | return std::nullopt; |
1647 | Expected<OwningBinary<Binary>> DebugBinary = createBinary(Path: *Path); |
1648 | if (!DebugBinary) { |
1649 | reportWarning(Message: toString(E: DebugBinary.takeError()), File: *Path); |
1650 | return std::nullopt; |
1651 | } |
1652 | return std::move(*DebugBinary); |
1653 | } |
1654 | |
1655 | static void |
1656 | disassembleObject(ObjectFile &Obj, const ObjectFile &DbgObj, |
1657 | DisassemblerTarget &PrimaryTarget, |
1658 | std::optional<DisassemblerTarget> &SecondaryTarget, |
1659 | SourcePrinter &SP, bool InlineRelocs) { |
1660 | DisassemblerTarget *DT = &PrimaryTarget; |
1661 | bool PrimaryIsThumb = false; |
1662 | SmallVector<std::pair<uint64_t, uint64_t>, 0> CHPECodeMap; |
1663 | |
1664 | if (SecondaryTarget) { |
1665 | if (isArmElf(Obj)) { |
1666 | PrimaryIsThumb = |
1667 | PrimaryTarget.SubtargetInfo->checkFeatures(FS: "+thumb-mode" ); |
1668 | } else if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Val: &Obj)) { |
1669 | const chpe_metadata *CHPEMetadata = COFFObj->getCHPEMetadata(); |
1670 | if (CHPEMetadata && CHPEMetadata->CodeMapCount) { |
1671 | uintptr_t CodeMapInt; |
1672 | cantFail(Err: COFFObj->getRvaPtr(Rva: CHPEMetadata->CodeMap, Res&: CodeMapInt)); |
1673 | auto CodeMap = reinterpret_cast<const chpe_range_entry *>(CodeMapInt); |
1674 | |
1675 | for (uint32_t i = 0; i < CHPEMetadata->CodeMapCount; ++i) { |
1676 | if (CodeMap[i].getType() == chpe_range_type::Amd64 && |
1677 | CodeMap[i].Length) { |
1678 | // Store x86_64 CHPE code ranges. |
1679 | uint64_t Start = CodeMap[i].getStart() + COFFObj->getImageBase(); |
1680 | CHPECodeMap.emplace_back(Args&: Start, Args: Start + CodeMap[i].Length); |
1681 | } |
1682 | } |
1683 | llvm::sort(C&: CHPECodeMap); |
1684 | } |
1685 | } |
1686 | } |
1687 | |
1688 | std::map<SectionRef, std::vector<RelocationRef>> RelocMap; |
1689 | if (InlineRelocs || Obj.isXCOFF()) |
1690 | RelocMap = getRelocsMap(Obj); |
1691 | bool Is64Bits = Obj.getBytesInAddress() > 4; |
1692 | |
1693 | // Create a mapping from virtual address to symbol name. This is used to |
1694 | // pretty print the symbols while disassembling. |
1695 | std::map<SectionRef, SectionSymbolsTy> AllSymbols; |
1696 | std::map<SectionRef, SmallVector<MappingSymbolPair, 0>> AllMappingSymbols; |
1697 | SectionSymbolsTy AbsoluteSymbols; |
1698 | const StringRef FileName = Obj.getFileName(); |
1699 | const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Val: &Obj); |
1700 | for (const SymbolRef &Symbol : Obj.symbols()) { |
1701 | Expected<StringRef> NameOrErr = Symbol.getName(); |
1702 | if (!NameOrErr) { |
1703 | reportWarning(Message: toString(E: NameOrErr.takeError()), File: FileName); |
1704 | continue; |
1705 | } |
1706 | if (NameOrErr->empty() && !(Obj.isXCOFF() && SymbolDescription)) |
1707 | continue; |
1708 | |
1709 | if (Obj.isELF() && |
1710 | (cantFail(ValOrErr: Symbol.getFlags()) & SymbolRef::SF_FormatSpecific)) { |
1711 | // Symbol is intended not to be displayed by default (STT_FILE, |
1712 | // STT_SECTION, or a mapping symbol). Ignore STT_SECTION symbols. We will |
1713 | // synthesize a section symbol if no symbol is defined at offset 0. |
1714 | // |
1715 | // For a mapping symbol, store it within both AllSymbols and |
1716 | // AllMappingSymbols. If --show-all-symbols is unspecified, its label will |
1717 | // not be printed in disassembly listing. |
1718 | if (getElfSymbolType(Obj, Sym: Symbol) != ELF::STT_SECTION && |
1719 | hasMappingSymbols(Obj)) { |
1720 | section_iterator SecI = unwrapOrError(EO: Symbol.getSection(), Args: FileName); |
1721 | if (SecI != Obj.section_end()) { |
1722 | uint64_t SectionAddr = SecI->getAddress(); |
1723 | uint64_t Address = cantFail(ValOrErr: Symbol.getAddress()); |
1724 | StringRef Name = *NameOrErr; |
1725 | if (Name.consume_front(Prefix: "$" ) && Name.size() && |
1726 | strchr(s: "adtx" , c: Name[0])) { |
1727 | AllMappingSymbols[*SecI].emplace_back(Args: Address - SectionAddr, |
1728 | Args: Name[0]); |
1729 | AllSymbols[*SecI].push_back( |
1730 | x: createSymbolInfo(Obj, Symbol, /*MappingSymbol=*/IsMappingSymbol: true)); |
1731 | } |
1732 | } |
1733 | } |
1734 | continue; |
1735 | } |
1736 | |
1737 | if (MachO) { |
1738 | // __mh_(execute|dylib|dylinker|bundle|preload|object)_header are special |
1739 | // symbols that support MachO header introspection. They do not bind to |
1740 | // code locations and are irrelevant for disassembly. |
1741 | if (NameOrErr->starts_with(Prefix: "__mh_" ) && NameOrErr->ends_with(Suffix: "_header" )) |
1742 | continue; |
1743 | // Don't ask a Mach-O STAB symbol for its section unless you know that |
1744 | // STAB symbol's section field refers to a valid section index. Otherwise |
1745 | // the symbol may error trying to load a section that does not exist. |
1746 | DataRefImpl SymDRI = Symbol.getRawDataRefImpl(); |
1747 | uint8_t NType = (MachO->is64Bit() ? |
1748 | MachO->getSymbol64TableEntry(DRI: SymDRI).n_type: |
1749 | MachO->getSymbolTableEntry(DRI: SymDRI).n_type); |
1750 | if (NType & MachO::N_STAB) |
1751 | continue; |
1752 | } |
1753 | |
1754 | section_iterator SecI = unwrapOrError(EO: Symbol.getSection(), Args: FileName); |
1755 | if (SecI != Obj.section_end()) |
1756 | AllSymbols[*SecI].push_back(x: createSymbolInfo(Obj, Symbol)); |
1757 | else |
1758 | AbsoluteSymbols.push_back(x: createSymbolInfo(Obj, Symbol)); |
1759 | } |
1760 | |
1761 | if (AllSymbols.empty() && Obj.isELF()) |
1762 | addDynamicElfSymbols(Obj: cast<ELFObjectFileBase>(Val&: Obj), AllSymbols); |
1763 | |
1764 | if (Obj.isWasm()) |
1765 | addMissingWasmCodeSymbols(Obj: cast<WasmObjectFile>(Val&: Obj), AllSymbols); |
1766 | |
1767 | if (Obj.isELF() && Obj.sections().empty()) |
1768 | createFakeELFSections(Obj); |
1769 | |
1770 | BumpPtrAllocator A; |
1771 | StringSaver Saver(A); |
1772 | addPltEntries(Obj, AllSymbols, Saver); |
1773 | |
1774 | // Create a mapping from virtual address to section. An empty section can |
1775 | // cause more than one section at the same address. Sort such sections to be |
1776 | // before same-addressed non-empty sections so that symbol lookups prefer the |
1777 | // non-empty section. |
1778 | std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses; |
1779 | for (SectionRef Sec : Obj.sections()) |
1780 | SectionAddresses.emplace_back(args: Sec.getAddress(), args&: Sec); |
1781 | llvm::stable_sort(Range&: SectionAddresses, C: [](const auto &LHS, const auto &RHS) { |
1782 | if (LHS.first != RHS.first) |
1783 | return LHS.first < RHS.first; |
1784 | return LHS.second.getSize() < RHS.second.getSize(); |
1785 | }); |
1786 | |
1787 | // Linked executables (.exe and .dll files) typically don't include a real |
1788 | // symbol table but they might contain an export table. |
1789 | if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Val: &Obj)) { |
1790 | for (const auto &ExportEntry : COFFObj->export_directories()) { |
1791 | StringRef Name; |
1792 | if (Error E = ExportEntry.getSymbolName(Result&: Name)) |
1793 | reportError(E: std::move(E), FileName: Obj.getFileName()); |
1794 | if (Name.empty()) |
1795 | continue; |
1796 | |
1797 | uint32_t RVA; |
1798 | if (Error E = ExportEntry.getExportRVA(Result&: RVA)) |
1799 | reportError(E: std::move(E), FileName: Obj.getFileName()); |
1800 | |
1801 | uint64_t VA = COFFObj->getImageBase() + RVA; |
1802 | auto Sec = partition_point( |
1803 | Range&: SectionAddresses, P: [VA](const std::pair<uint64_t, SectionRef> &O) { |
1804 | return O.first <= VA; |
1805 | }); |
1806 | if (Sec != SectionAddresses.begin()) { |
1807 | --Sec; |
1808 | AllSymbols[Sec->second].emplace_back(args&: VA, args&: Name, args: ELF::STT_NOTYPE); |
1809 | } else |
1810 | AbsoluteSymbols.emplace_back(args&: VA, args&: Name, args: ELF::STT_NOTYPE); |
1811 | } |
1812 | } |
1813 | |
1814 | // Sort all the symbols, this allows us to use a simple binary search to find |
1815 | // Multiple symbols can have the same address. Use a stable sort to stabilize |
1816 | // the output. |
1817 | StringSet<> FoundDisasmSymbolSet; |
1818 | for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols) |
1819 | llvm::stable_sort(Range&: SecSyms.second); |
1820 | llvm::stable_sort(Range&: AbsoluteSymbols); |
1821 | |
1822 | std::unique_ptr<DWARFContext> DICtx; |
1823 | LiveVariablePrinter LVP(*DT->Context->getRegisterInfo(), *DT->SubtargetInfo); |
1824 | |
1825 | if (DbgVariables != DVDisabled) { |
1826 | DICtx = DWARFContext::create(Obj: DbgObj); |
1827 | for (const std::unique_ptr<DWARFUnit> &CU : DICtx->compile_units()) |
1828 | LVP.addCompileUnit(D: CU->getUnitDIE(ExtractUnitDIEOnly: false)); |
1829 | } |
1830 | |
1831 | LLVM_DEBUG(LVP.dump()); |
1832 | |
1833 | BBAddrMapInfo FullAddrMap; |
1834 | auto ReadBBAddrMap = [&](std::optional<unsigned> SectionIndex = |
1835 | std::nullopt) { |
1836 | FullAddrMap.clear(); |
1837 | if (const auto *Elf = dyn_cast<ELFObjectFileBase>(Val: &Obj)) { |
1838 | std::vector<PGOAnalysisMap> PGOAnalyses; |
1839 | auto BBAddrMapsOrErr = Elf->readBBAddrMap(TextSectionIndex: SectionIndex, PGOAnalyses: &PGOAnalyses); |
1840 | if (!BBAddrMapsOrErr) { |
1841 | reportWarning(Message: toString(E: BBAddrMapsOrErr.takeError()), File: Obj.getFileName()); |
1842 | return; |
1843 | } |
1844 | for (auto &&[FunctionBBAddrMap, FunctionPGOAnalysis] : |
1845 | zip_equal(t&: *std::move(BBAddrMapsOrErr), u: std::move(PGOAnalyses))) { |
1846 | FullAddrMap.AddFunctionEntry(AddrMap: std::move(FunctionBBAddrMap), |
1847 | PGOMap: std::move(FunctionPGOAnalysis)); |
1848 | } |
1849 | } |
1850 | }; |
1851 | |
1852 | // For non-relocatable objects, Read all LLVM_BB_ADDR_MAP sections into a |
1853 | // single mapping, since they don't have any conflicts. |
1854 | if (SymbolizeOperands && !Obj.isRelocatableObject()) |
1855 | ReadBBAddrMap(); |
1856 | |
1857 | std::optional<llvm::BTFParser> BTF; |
1858 | if (InlineRelocs && BTFParser::hasBTFSections(Obj)) { |
1859 | BTF.emplace(); |
1860 | BTFParser::ParseOptions Opts = {}; |
1861 | Opts.LoadTypes = true; |
1862 | Opts.LoadRelocs = true; |
1863 | if (Error E = BTF->parse(Obj, Opts)) |
1864 | WithColor::defaultErrorHandler(Err: std::move(E)); |
1865 | } |
1866 | |
1867 | for (const SectionRef &Section : ToolSectionFilter(O: Obj)) { |
1868 | if (FilterSections.empty() && !DisassembleAll && |
1869 | (!Section.isText() || Section.isVirtual())) |
1870 | continue; |
1871 | |
1872 | uint64_t SectionAddr = Section.getAddress(); |
1873 | uint64_t SectSize = Section.getSize(); |
1874 | if (!SectSize) |
1875 | continue; |
1876 | |
1877 | // For relocatable object files, read the LLVM_BB_ADDR_MAP section |
1878 | // corresponding to this section, if present. |
1879 | if (SymbolizeOperands && Obj.isRelocatableObject()) |
1880 | ReadBBAddrMap(Section.getIndex()); |
1881 | |
1882 | // Get the list of all the symbols in this section. |
1883 | SectionSymbolsTy &Symbols = AllSymbols[Section]; |
1884 | auto &MappingSymbols = AllMappingSymbols[Section]; |
1885 | llvm::sort(C&: MappingSymbols); |
1886 | |
1887 | ArrayRef<uint8_t> Bytes = arrayRefFromStringRef( |
1888 | Input: unwrapOrError(EO: Section.getContents(), Args: Obj.getFileName())); |
1889 | |
1890 | std::vector<std::unique_ptr<std::string>> SynthesizedLabelNames; |
1891 | if (Obj.isELF() && Obj.getArch() == Triple::amdgcn) { |
1892 | // AMDGPU disassembler uses symbolizer for printing labels |
1893 | addSymbolizer(Ctx&: *DT->Context, Target: DT->TheTarget, TripleName, DisAsm: DT->DisAsm.get(), |
1894 | SectionAddr, Bytes, Symbols, SynthesizedLabelNames); |
1895 | } |
1896 | |
1897 | StringRef SegmentName = getSegmentName(MachO, Section); |
1898 | StringRef SectionName = unwrapOrError(EO: Section.getName(), Args: Obj.getFileName()); |
1899 | // If the section has no symbol at the start, just insert a dummy one. |
1900 | // Without --show-all-symbols, also insert one if all symbols at the start |
1901 | // are mapping symbols. |
1902 | bool CreateDummy = Symbols.empty(); |
1903 | if (!CreateDummy) { |
1904 | CreateDummy = true; |
1905 | for (auto &Sym : Symbols) { |
1906 | if (Sym.Addr != SectionAddr) |
1907 | break; |
1908 | if (!Sym.IsMappingSymbol || ShowAllSymbols) |
1909 | CreateDummy = false; |
1910 | } |
1911 | } |
1912 | if (CreateDummy) { |
1913 | SymbolInfoTy Sym = createDummySymbolInfo( |
1914 | Obj, Addr: SectionAddr, Name&: SectionName, |
1915 | Type: Section.isText() ? ELF::STT_FUNC : ELF::STT_OBJECT); |
1916 | if (Obj.isXCOFF()) |
1917 | Symbols.insert(position: Symbols.begin(), x: Sym); |
1918 | else |
1919 | Symbols.insert(position: llvm::lower_bound(Range&: Symbols, Value&: Sym), x: Sym); |
1920 | } |
1921 | |
1922 | SmallString<40> ; |
1923 | raw_svector_ostream (Comments); |
1924 | |
1925 | uint64_t VMAAdjustment = 0; |
1926 | if (shouldAdjustVA(Section)) |
1927 | VMAAdjustment = AdjustVMA; |
1928 | |
1929 | // In executable and shared objects, r_offset holds a virtual address. |
1930 | // Subtract SectionAddr from the r_offset field of a relocation to get |
1931 | // the section offset. |
1932 | uint64_t RelAdjustment = Obj.isRelocatableObject() ? 0 : SectionAddr; |
1933 | uint64_t Size; |
1934 | uint64_t Index; |
1935 | bool PrintedSection = false; |
1936 | std::vector<RelocationRef> Rels = RelocMap[Section]; |
1937 | std::vector<RelocationRef>::const_iterator RelCur = Rels.begin(); |
1938 | std::vector<RelocationRef>::const_iterator RelEnd = Rels.end(); |
1939 | |
1940 | // Loop over each chunk of code between two points where at least |
1941 | // one symbol is defined. |
1942 | for (size_t SI = 0, SE = Symbols.size(); SI != SE;) { |
1943 | // Advance SI past all the symbols starting at the same address, |
1944 | // and make an ArrayRef of them. |
1945 | unsigned FirstSI = SI; |
1946 | uint64_t Start = Symbols[SI].Addr; |
1947 | ArrayRef<SymbolInfoTy> SymbolsHere; |
1948 | while (SI != SE && Symbols[SI].Addr == Start) |
1949 | ++SI; |
1950 | SymbolsHere = ArrayRef<SymbolInfoTy>(&Symbols[FirstSI], SI - FirstSI); |
1951 | |
1952 | // Get the demangled names of all those symbols. We end up with a vector |
1953 | // of StringRef that holds the names we're going to use, and a vector of |
1954 | // std::string that stores the new strings returned by demangle(), if |
1955 | // any. If we don't call demangle() then that vector can stay empty. |
1956 | std::vector<StringRef> SymNamesHere; |
1957 | std::vector<std::string> DemangledSymNamesHere; |
1958 | if (Demangle) { |
1959 | // Fetch the demangled names and store them locally. |
1960 | for (const SymbolInfoTy &Symbol : SymbolsHere) |
1961 | DemangledSymNamesHere.push_back(x: demangle(MangledName: Symbol.Name)); |
1962 | // Now we've finished modifying that vector, it's safe to make |
1963 | // a vector of StringRefs pointing into it. |
1964 | SymNamesHere.insert(position: SymNamesHere.begin(), first: DemangledSymNamesHere.begin(), |
1965 | last: DemangledSymNamesHere.end()); |
1966 | } else { |
1967 | for (const SymbolInfoTy &Symbol : SymbolsHere) |
1968 | SymNamesHere.push_back(x: Symbol.Name); |
1969 | } |
1970 | |
1971 | // Distinguish ELF data from code symbols, which will be used later on to |
1972 | // decide whether to 'disassemble' this chunk as a data declaration via |
1973 | // dumpELFData(), or whether to treat it as code. |
1974 | // |
1975 | // If data _and_ code symbols are defined at the same address, the code |
1976 | // takes priority, on the grounds that disassembling code is our main |
1977 | // purpose here, and it would be a worse failure to _not_ interpret |
1978 | // something that _was_ meaningful as code than vice versa. |
1979 | // |
1980 | // Any ELF symbol type that is not clearly data will be regarded as code. |
1981 | // In particular, one of the uses of STT_NOTYPE is for branch targets |
1982 | // inside functions, for which STT_FUNC would be inaccurate. |
1983 | // |
1984 | // So here, we spot whether there's any non-data symbol present at all, |
1985 | // and only set the DisassembleAsELFData flag if there isn't. Also, we use |
1986 | // this distinction to inform the decision of which symbol to print at |
1987 | // the head of the section, so that if we're printing code, we print a |
1988 | // code-related symbol name to go with it. |
1989 | bool DisassembleAsELFData = false; |
1990 | size_t DisplaySymIndex = SymbolsHere.size() - 1; |
1991 | if (Obj.isELF() && !DisassembleAll && Section.isText()) { |
1992 | DisassembleAsELFData = true; // unless we find a code symbol below |
1993 | |
1994 | for (size_t i = 0; i < SymbolsHere.size(); ++i) { |
1995 | uint8_t SymTy = SymbolsHere[i].Type; |
1996 | if (SymTy != ELF::STT_OBJECT && SymTy != ELF::STT_COMMON) { |
1997 | DisassembleAsELFData = false; |
1998 | DisplaySymIndex = i; |
1999 | } |
2000 | } |
2001 | } |
2002 | |
2003 | // Decide which symbol(s) from this collection we're going to print. |
2004 | std::vector<bool> SymsToPrint(SymbolsHere.size(), false); |
2005 | // If the user has given the --disassemble-symbols option, then we must |
2006 | // display every symbol in that set, and no others. |
2007 | if (!DisasmSymbolSet.empty()) { |
2008 | bool FoundAny = false; |
2009 | for (size_t i = 0; i < SymbolsHere.size(); ++i) { |
2010 | if (DisasmSymbolSet.count(Key: SymNamesHere[i])) { |
2011 | SymsToPrint[i] = true; |
2012 | FoundAny = true; |
2013 | } |
2014 | } |
2015 | |
2016 | // And if none of the symbols here is one that the user asked for, skip |
2017 | // disassembling this entire chunk of code. |
2018 | if (!FoundAny) |
2019 | continue; |
2020 | } else if (!SymbolsHere[DisplaySymIndex].IsMappingSymbol) { |
2021 | // Otherwise, print whichever symbol at this location is last in the |
2022 | // Symbols array, because that array is pre-sorted in a way intended to |
2023 | // correlate with priority of which symbol to display. |
2024 | SymsToPrint[DisplaySymIndex] = true; |
2025 | } |
2026 | |
2027 | // Now that we know we're disassembling this section, override the choice |
2028 | // of which symbols to display by printing _all_ of them at this address |
2029 | // if the user asked for all symbols. |
2030 | // |
2031 | // That way, '--show-all-symbols --disassemble-symbol=foo' will print |
2032 | // only the chunk of code headed by 'foo', but also show any other |
2033 | // symbols defined at that address, such as aliases for 'foo', or the ARM |
2034 | // mapping symbol preceding its code. |
2035 | if (ShowAllSymbols) { |
2036 | for (size_t i = 0; i < SymbolsHere.size(); ++i) |
2037 | SymsToPrint[i] = true; |
2038 | } |
2039 | |
2040 | if (Start < SectionAddr || StopAddress <= Start) |
2041 | continue; |
2042 | |
2043 | for (size_t i = 0; i < SymbolsHere.size(); ++i) |
2044 | FoundDisasmSymbolSet.insert(key: SymNamesHere[i]); |
2045 | |
2046 | // The end is the section end, the beginning of the next symbol, or |
2047 | // --stop-address. |
2048 | uint64_t End = std::min<uint64_t>(a: SectionAddr + SectSize, b: StopAddress); |
2049 | if (SI < SE) |
2050 | End = std::min(a: End, b: Symbols[SI].Addr); |
2051 | if (Start >= End || End <= StartAddress) |
2052 | continue; |
2053 | Start -= SectionAddr; |
2054 | End -= SectionAddr; |
2055 | |
2056 | if (!PrintedSection) { |
2057 | PrintedSection = true; |
2058 | outs() << "\nDisassembly of section " ; |
2059 | if (!SegmentName.empty()) |
2060 | outs() << SegmentName << "," ; |
2061 | outs() << SectionName << ":\n" ; |
2062 | } |
2063 | |
2064 | bool PrintedLabel = false; |
2065 | for (size_t i = 0; i < SymbolsHere.size(); ++i) { |
2066 | if (!SymsToPrint[i]) |
2067 | continue; |
2068 | |
2069 | const SymbolInfoTy &Symbol = SymbolsHere[i]; |
2070 | const StringRef SymbolName = SymNamesHere[i]; |
2071 | |
2072 | if (!PrintedLabel) { |
2073 | outs() << '\n'; |
2074 | PrintedLabel = true; |
2075 | } |
2076 | if (LeadingAddr) |
2077 | outs() << format(Fmt: Is64Bits ? "%016" PRIx64 " " : "%08" PRIx64 " " , |
2078 | Vals: SectionAddr + Start + VMAAdjustment); |
2079 | if (Obj.isXCOFF() && SymbolDescription) { |
2080 | outs() << getXCOFFSymbolDescription(SymbolInfo: Symbol, SymbolName) << ":\n" ; |
2081 | } else |
2082 | outs() << '<' << SymbolName << ">:\n" ; |
2083 | } |
2084 | |
2085 | // Don't print raw contents of a virtual section. A virtual section |
2086 | // doesn't have any contents in the file. |
2087 | if (Section.isVirtual()) { |
2088 | outs() << "...\n" ; |
2089 | continue; |
2090 | } |
2091 | |
2092 | // See if any of the symbols defined at this location triggers target- |
2093 | // specific disassembly behavior, e.g. of special descriptors or function |
2094 | // prelude information. |
2095 | // |
2096 | // We stop this loop at the first symbol that triggers some kind of |
2097 | // interesting behavior (if any), on the assumption that if two symbols |
2098 | // defined at the same address trigger two conflicting symbol handlers, |
2099 | // the object file is probably confused anyway, and it would make even |
2100 | // less sense to present the output of _both_ handlers, because that |
2101 | // would describe the same data twice. |
2102 | for (size_t SHI = 0; SHI < SymbolsHere.size(); ++SHI) { |
2103 | SymbolInfoTy Symbol = SymbolsHere[SHI]; |
2104 | |
2105 | Expected<bool> RespondedOrErr = DT->DisAsm->onSymbolStart( |
2106 | Symbol, Size, Bytes: Bytes.slice(N: Start, M: End - Start), Address: SectionAddr + Start); |
2107 | |
2108 | if (RespondedOrErr && !*RespondedOrErr) { |
2109 | // This symbol didn't trigger any interesting handling. Try the other |
2110 | // symbols defined at this address. |
2111 | continue; |
2112 | } |
2113 | |
2114 | // If onSymbolStart returned an Error, that means it identified some |
2115 | // kind of special data at this address, but wasn't able to disassemble |
2116 | // it meaningfully. So we fall back to printing the error out and |
2117 | // disassembling the failed region as bytes, assuming that the target |
2118 | // detected the failure before printing anything. |
2119 | if (!RespondedOrErr) { |
2120 | std::string ErrMsgStr = toString(E: RespondedOrErr.takeError()); |
2121 | StringRef ErrMsg = ErrMsgStr; |
2122 | do { |
2123 | StringRef Line; |
2124 | std::tie(args&: Line, args&: ErrMsg) = ErrMsg.split(Separator: '\n'); |
2125 | outs() << DT->Context->getAsmInfo()->getCommentString() |
2126 | << " error decoding " << SymNamesHere[SHI] << ": " << Line |
2127 | << '\n'; |
2128 | } while (!ErrMsg.empty()); |
2129 | |
2130 | if (Size) { |
2131 | outs() << DT->Context->getAsmInfo()->getCommentString() |
2132 | << " decoding failed region as bytes\n" ; |
2133 | for (uint64_t I = 0; I < Size; ++I) |
2134 | outs() << "\t.byte\t " << format_hex(N: Bytes[I], Width: 1, /*Upper=*/true) |
2135 | << '\n'; |
2136 | } |
2137 | } |
2138 | |
2139 | // Regardless of whether onSymbolStart returned an Error or true, 'Size' |
2140 | // will have been set to the amount of data covered by whatever prologue |
2141 | // the target identified. So we advance our own position to beyond that. |
2142 | // Sometimes that will be the entire distance to the next symbol, and |
2143 | // sometimes it will be just a prologue and we should start |
2144 | // disassembling instructions from where it left off. |
2145 | Start += Size; |
2146 | break; |
2147 | } |
2148 | |
2149 | Index = Start; |
2150 | if (SectionAddr < StartAddress) |
2151 | Index = std::max<uint64_t>(a: Index, b: StartAddress - SectionAddr); |
2152 | |
2153 | if (DisassembleAsELFData) { |
2154 | dumpELFData(SectionAddr, Index, End, Bytes); |
2155 | Index = End; |
2156 | continue; |
2157 | } |
2158 | |
2159 | // Skip relocations from symbols that are not dumped. |
2160 | for (; RelCur != RelEnd; ++RelCur) { |
2161 | uint64_t Offset = RelCur->getOffset() - RelAdjustment; |
2162 | if (Index <= Offset) |
2163 | break; |
2164 | } |
2165 | |
2166 | bool DumpARMELFData = false; |
2167 | bool DumpTracebackTableForXCOFFFunction = |
2168 | Obj.isXCOFF() && Section.isText() && TracebackTable && |
2169 | Symbols[SI - 1].XCOFFSymInfo.StorageMappingClass && |
2170 | (*Symbols[SI - 1].XCOFFSymInfo.StorageMappingClass == XCOFF::XMC_PR); |
2171 | |
2172 | formatted_raw_ostream FOS(outs()); |
2173 | |
2174 | std::unordered_map<uint64_t, std::string> AllLabels; |
2175 | std::unordered_map<uint64_t, std::vector<BBAddrMapLabel>> BBAddrMapLabels; |
2176 | if (SymbolizeOperands) { |
2177 | collectLocalBranchTargets(Bytes, MIA: DT->InstrAnalysis.get(), |
2178 | DisAsm: DT->DisAsm.get(), IP: DT->InstPrinter.get(), |
2179 | STI: PrimaryTarget.SubtargetInfo.get(), |
2180 | SectionAddr, Start: Index, End, Labels&: AllLabels); |
2181 | collectBBAddrMapLabels(FullAddrMap, SectionAddr, Start: Index, End, |
2182 | Labels&: BBAddrMapLabels); |
2183 | } |
2184 | |
2185 | if (DT->InstrAnalysis) |
2186 | DT->InstrAnalysis->resetState(); |
2187 | |
2188 | while (Index < End) { |
2189 | uint64_t RelOffset; |
2190 | |
2191 | // ARM and AArch64 ELF binaries can interleave data and text in the |
2192 | // same section. We rely on the markers introduced to understand what |
2193 | // we need to dump. If the data marker is within a function, it is |
2194 | // denoted as a word/short etc. |
2195 | if (!MappingSymbols.empty()) { |
2196 | char Kind = getMappingSymbolKind(MappingSymbols, Address: Index); |
2197 | DumpARMELFData = Kind == 'd'; |
2198 | if (SecondaryTarget) { |
2199 | if (Kind == 'a') { |
2200 | DT = PrimaryIsThumb ? &*SecondaryTarget : &PrimaryTarget; |
2201 | } else if (Kind == 't') { |
2202 | DT = PrimaryIsThumb ? &PrimaryTarget : &*SecondaryTarget; |
2203 | } |
2204 | } |
2205 | } else if (!CHPECodeMap.empty()) { |
2206 | uint64_t Address = SectionAddr + Index; |
2207 | auto It = partition_point( |
2208 | Range&: CHPECodeMap, |
2209 | P: [Address](const std::pair<uint64_t, uint64_t> &Entry) { |
2210 | return Entry.first <= Address; |
2211 | }); |
2212 | if (It != CHPECodeMap.begin() && Address < (It - 1)->second) { |
2213 | DT = &*SecondaryTarget; |
2214 | } else { |
2215 | DT = &PrimaryTarget; |
2216 | // X64 disassembler range may have left Index unaligned, so |
2217 | // make sure that it's aligned when we switch back to ARM64 |
2218 | // code. |
2219 | Index = llvm::alignTo(Value: Index, Align: 4); |
2220 | if (Index >= End) |
2221 | break; |
2222 | } |
2223 | } |
2224 | |
2225 | auto findRel = [&]() { |
2226 | while (RelCur != RelEnd) { |
2227 | RelOffset = RelCur->getOffset() - RelAdjustment; |
2228 | // If this relocation is hidden, skip it. |
2229 | if (getHidden(RelRef: *RelCur) || SectionAddr + RelOffset < StartAddress) { |
2230 | ++RelCur; |
2231 | continue; |
2232 | } |
2233 | |
2234 | // Stop when RelCur's offset is past the disassembled |
2235 | // instruction/data. |
2236 | if (RelOffset >= Index + Size) |
2237 | return false; |
2238 | if (RelOffset >= Index) |
2239 | return true; |
2240 | ++RelCur; |
2241 | } |
2242 | return false; |
2243 | }; |
2244 | |
2245 | if (DumpARMELFData) { |
2246 | Size = dumpARMELFData(SectionAddr, Index, End, Obj, Bytes, |
2247 | MappingSymbols, STI: *DT->SubtargetInfo, OS&: FOS); |
2248 | } else { |
2249 | // When -z or --disassemble-zeroes are given we always dissasemble |
2250 | // them. Otherwise we might want to skip zero bytes we see. |
2251 | if (!DisassembleZeroes) { |
2252 | uint64_t MaxOffset = End - Index; |
2253 | // For --reloc: print zero blocks patched by relocations, so that |
2254 | // relocations can be shown in the dump. |
2255 | if (InlineRelocs && RelCur != RelEnd) |
2256 | MaxOffset = std::min(a: RelCur->getOffset() - RelAdjustment - Index, |
2257 | b: MaxOffset); |
2258 | |
2259 | if (size_t N = |
2260 | countSkippableZeroBytes(Buf: Bytes.slice(N: Index, M: MaxOffset))) { |
2261 | FOS << "\t\t..." << '\n'; |
2262 | Index += N; |
2263 | continue; |
2264 | } |
2265 | } |
2266 | |
2267 | if (DumpTracebackTableForXCOFFFunction && |
2268 | doesXCOFFTracebackTableBegin(Bytes: Bytes.slice(N: Index, M: 4))) { |
2269 | dumpTracebackTable(Bytes: Bytes.slice(N: Index), |
2270 | Address: SectionAddr + Index + VMAAdjustment, OS&: FOS, |
2271 | End: SectionAddr + End + VMAAdjustment, |
2272 | STI: *DT->SubtargetInfo, Obj: cast<XCOFFObjectFile>(Val: &Obj)); |
2273 | Index = End; |
2274 | continue; |
2275 | } |
2276 | |
2277 | // Print local label if there's any. |
2278 | auto Iter1 = BBAddrMapLabels.find(x: SectionAddr + Index); |
2279 | if (Iter1 != BBAddrMapLabels.end()) { |
2280 | for (const auto &BBLabel : Iter1->second) |
2281 | FOS << "<" << BBLabel.BlockLabel << ">" << BBLabel.PGOAnalysis |
2282 | << ":\n" ; |
2283 | } else { |
2284 | auto Iter2 = AllLabels.find(x: SectionAddr + Index); |
2285 | if (Iter2 != AllLabels.end()) |
2286 | FOS << "<" << Iter2->second << ">:\n" ; |
2287 | } |
2288 | |
2289 | // Disassemble a real instruction or a data when disassemble all is |
2290 | // provided |
2291 | MCInst Inst; |
2292 | ArrayRef<uint8_t> ThisBytes = Bytes.slice(N: Index); |
2293 | uint64_t ThisAddr = SectionAddr + Index; |
2294 | bool Disassembled = DT->DisAsm->getInstruction( |
2295 | Instr&: Inst, Size, Bytes: ThisBytes, Address: ThisAddr, CStream&: CommentStream); |
2296 | if (Size == 0) |
2297 | Size = std::min<uint64_t>( |
2298 | a: ThisBytes.size(), |
2299 | b: DT->DisAsm->suggestBytesToSkip(Bytes: ThisBytes, Address: ThisAddr)); |
2300 | |
2301 | LVP.update(ThisAddr: {.Address: Index, .SectionIndex: Section.getIndex()}, |
2302 | NextAddr: {.Address: Index + Size, .SectionIndex: Section.getIndex()}, IncludeDefinedVars: Index + Size != End); |
2303 | |
2304 | DT->InstPrinter->setCommentStream(CommentStream); |
2305 | |
2306 | DT->Printer->printInst( |
2307 | IP&: *DT->InstPrinter, MI: Disassembled ? &Inst : nullptr, |
2308 | Bytes: Bytes.slice(N: Index, M: Size), |
2309 | Address: {.Address: SectionAddr + Index + VMAAdjustment, .SectionIndex: Section.getIndex()}, OS&: FOS, |
2310 | Annot: "" , STI: *DT->SubtargetInfo, SP: &SP, ObjectFilename: Obj.getFileName(), Rels: &Rels, LVP); |
2311 | |
2312 | DT->InstPrinter->setCommentStream(llvm::nulls()); |
2313 | |
2314 | // If disassembly succeeds, we try to resolve the target address |
2315 | // (jump target or memory operand address) and print it to the |
2316 | // right of the instruction. |
2317 | // |
2318 | // Otherwise, we don't print anything else so that we avoid |
2319 | // analyzing invalid or incomplete instruction information. |
2320 | if (Disassembled && DT->InstrAnalysis) { |
2321 | llvm::raw_ostream *TargetOS = &FOS; |
2322 | uint64_t Target; |
2323 | bool PrintTarget = DT->InstrAnalysis->evaluateBranch( |
2324 | Inst, Addr: SectionAddr + Index, Size, Target); |
2325 | |
2326 | if (!PrintTarget) { |
2327 | if (std::optional<uint64_t> MaybeTarget = |
2328 | DT->InstrAnalysis->evaluateMemoryOperandAddress( |
2329 | Inst, STI: DT->SubtargetInfo.get(), Addr: SectionAddr + Index, |
2330 | Size)) { |
2331 | Target = *MaybeTarget; |
2332 | PrintTarget = true; |
2333 | // Do not print real address when symbolizing. |
2334 | if (!SymbolizeOperands) { |
2335 | // Memory operand addresses are printed as comments. |
2336 | TargetOS = &CommentStream; |
2337 | *TargetOS << "0x" << Twine::utohexstr(Val: Target); |
2338 | } |
2339 | } |
2340 | } |
2341 | |
2342 | if (PrintTarget) { |
2343 | // In a relocatable object, the target's section must reside in |
2344 | // the same section as the call instruction or it is accessed |
2345 | // through a relocation. |
2346 | // |
2347 | // In a non-relocatable object, the target may be in any section. |
2348 | // In that case, locate the section(s) containing the target |
2349 | // address and find the symbol in one of those, if possible. |
2350 | // |
2351 | // N.B. Except for XCOFF, we don't walk the relocations in the |
2352 | // relocatable case yet. |
2353 | std::vector<const SectionSymbolsTy *> TargetSectionSymbols; |
2354 | if (!Obj.isRelocatableObject()) { |
2355 | auto It = llvm::partition_point( |
2356 | Range&: SectionAddresses, |
2357 | P: [=](const std::pair<uint64_t, SectionRef> &O) { |
2358 | return O.first <= Target; |
2359 | }); |
2360 | uint64_t TargetSecAddr = 0; |
2361 | while (It != SectionAddresses.begin()) { |
2362 | --It; |
2363 | if (TargetSecAddr == 0) |
2364 | TargetSecAddr = It->first; |
2365 | if (It->first != TargetSecAddr) |
2366 | break; |
2367 | TargetSectionSymbols.push_back(x: &AllSymbols[It->second]); |
2368 | } |
2369 | } else { |
2370 | TargetSectionSymbols.push_back(x: &Symbols); |
2371 | } |
2372 | TargetSectionSymbols.push_back(x: &AbsoluteSymbols); |
2373 | |
2374 | // Find the last symbol in the first candidate section whose |
2375 | // offset is less than or equal to the target. If there are no |
2376 | // such symbols, try in the next section and so on, before finally |
2377 | // using the nearest preceding absolute symbol (if any), if there |
2378 | // are no other valid symbols. |
2379 | const SymbolInfoTy *TargetSym = nullptr; |
2380 | for (const SectionSymbolsTy *TargetSymbols : |
2381 | TargetSectionSymbols) { |
2382 | auto It = llvm::partition_point( |
2383 | Range: *TargetSymbols, |
2384 | P: [=](const SymbolInfoTy &O) { return O.Addr <= Target; }); |
2385 | while (It != TargetSymbols->begin()) { |
2386 | --It; |
2387 | // Skip mapping symbols to avoid possible ambiguity as they |
2388 | // do not allow uniquely identifying the target address. |
2389 | if (!It->IsMappingSymbol) { |
2390 | TargetSym = &*It; |
2391 | break; |
2392 | } |
2393 | } |
2394 | if (TargetSym) |
2395 | break; |
2396 | } |
2397 | |
2398 | // Branch targets are printed just after the instructions. |
2399 | // Print the labels corresponding to the target if there's any. |
2400 | bool BBAddrMapLabelAvailable = BBAddrMapLabels.count(x: Target); |
2401 | bool LabelAvailable = AllLabels.count(x: Target); |
2402 | |
2403 | if (TargetSym != nullptr) { |
2404 | uint64_t TargetAddress = TargetSym->Addr; |
2405 | uint64_t Disp = Target - TargetAddress; |
2406 | std::string TargetName = Demangle ? demangle(MangledName: TargetSym->Name) |
2407 | : TargetSym->Name.str(); |
2408 | bool RelFixedUp = false; |
2409 | SmallString<32> Val; |
2410 | |
2411 | *TargetOS << " <" ; |
2412 | // On XCOFF, we use relocations, even without -r, so we |
2413 | // can print the correct name for an extern function call. |
2414 | if (Obj.isXCOFF() && findRel()) { |
2415 | // Check for possible branch relocations and |
2416 | // branches to fixup code. |
2417 | bool BranchRelocationType = true; |
2418 | XCOFF::RelocationType RelocType; |
2419 | if (Obj.is64Bit()) { |
2420 | const XCOFFRelocation64 *Reloc = |
2421 | reinterpret_cast<XCOFFRelocation64 *>( |
2422 | RelCur->getRawDataRefImpl().p); |
2423 | RelFixedUp = Reloc->isFixupIndicated(); |
2424 | RelocType = Reloc->Type; |
2425 | } else { |
2426 | const XCOFFRelocation32 *Reloc = |
2427 | reinterpret_cast<XCOFFRelocation32 *>( |
2428 | RelCur->getRawDataRefImpl().p); |
2429 | RelFixedUp = Reloc->isFixupIndicated(); |
2430 | RelocType = Reloc->Type; |
2431 | } |
2432 | BranchRelocationType = |
2433 | RelocType == XCOFF::R_BA || RelocType == XCOFF::R_BR || |
2434 | RelocType == XCOFF::R_RBA || RelocType == XCOFF::R_RBR; |
2435 | |
2436 | // If we have a valid relocation, try to print its |
2437 | // corresponding symbol name. Multiple relocations on the |
2438 | // same instruction are not handled. |
2439 | // Branches to fixup code will have the RelFixedUp flag set in |
2440 | // the RLD. For these instructions, we print the correct |
2441 | // branch target, but print the referenced symbol as a |
2442 | // comment. |
2443 | if (Error E = getRelocationValueString(Rel: *RelCur, SymbolDescription: false, Result&: Val)) { |
2444 | // If -r was used, this error will be printed later. |
2445 | // Otherwise, we ignore the error and print what |
2446 | // would have been printed without using relocations. |
2447 | consumeError(Err: std::move(E)); |
2448 | *TargetOS << TargetName; |
2449 | RelFixedUp = false; // Suppress comment for RLD sym name |
2450 | } else if (BranchRelocationType && !RelFixedUp) |
2451 | *TargetOS << Val; |
2452 | else |
2453 | *TargetOS << TargetName; |
2454 | if (Disp) |
2455 | *TargetOS << "+0x" << Twine::utohexstr(Val: Disp); |
2456 | } else if (!Disp) { |
2457 | *TargetOS << TargetName; |
2458 | } else if (BBAddrMapLabelAvailable) { |
2459 | *TargetOS << BBAddrMapLabels[Target].front().BlockLabel; |
2460 | } else if (LabelAvailable) { |
2461 | *TargetOS << AllLabels[Target]; |
2462 | } else { |
2463 | // Always Print the binary symbol plus an offset if there's no |
2464 | // local label corresponding to the target address. |
2465 | *TargetOS << TargetName << "+0x" << Twine::utohexstr(Val: Disp); |
2466 | } |
2467 | *TargetOS << ">" ; |
2468 | if (RelFixedUp && !InlineRelocs) { |
2469 | // We have fixup code for a relocation. We print the |
2470 | // referenced symbol as a comment. |
2471 | *TargetOS << "\t# " << Val; |
2472 | } |
2473 | |
2474 | } else if (BBAddrMapLabelAvailable) { |
2475 | *TargetOS << " <" << BBAddrMapLabels[Target].front().BlockLabel |
2476 | << ">" ; |
2477 | } else if (LabelAvailable) { |
2478 | *TargetOS << " <" << AllLabels[Target] << ">" ; |
2479 | } |
2480 | // By convention, each record in the comment stream should be |
2481 | // terminated. |
2482 | if (TargetOS == &CommentStream) |
2483 | *TargetOS << "\n" ; |
2484 | } |
2485 | |
2486 | DT->InstrAnalysis->updateState(Inst, Addr: SectionAddr + Index); |
2487 | } else if (!Disassembled && DT->InstrAnalysis) { |
2488 | DT->InstrAnalysis->resetState(); |
2489 | } |
2490 | } |
2491 | |
2492 | assert(DT->Context->getAsmInfo()); |
2493 | emitPostInstructionInfo(FOS, MAI: *DT->Context->getAsmInfo(), |
2494 | STI: *DT->SubtargetInfo, Comments: CommentStream.str(), LVP); |
2495 | Comments.clear(); |
2496 | |
2497 | if (BTF) |
2498 | printBTFRelocation(FOS, BTF&: *BTF, Address: {.Address: Index, .SectionIndex: Section.getIndex()}, LVP); |
2499 | |
2500 | // Hexagon handles relocs in pretty printer |
2501 | if (InlineRelocs && Obj.getArch() != Triple::hexagon) { |
2502 | while (findRel()) { |
2503 | // When --adjust-vma is used, update the address printed. |
2504 | if (RelCur->getSymbol() != Obj.symbol_end()) { |
2505 | Expected<section_iterator> SymSI = |
2506 | RelCur->getSymbol()->getSection(); |
2507 | if (SymSI && *SymSI != Obj.section_end() && |
2508 | shouldAdjustVA(Section: **SymSI)) |
2509 | RelOffset += AdjustVMA; |
2510 | } |
2511 | |
2512 | printRelocation(OS&: FOS, FileName: Obj.getFileName(), Rel: *RelCur, |
2513 | Address: SectionAddr + RelOffset, Is64Bits); |
2514 | LVP.printAfterOtherLine(OS&: FOS, AfterInst: true); |
2515 | ++RelCur; |
2516 | } |
2517 | } |
2518 | |
2519 | Index += Size; |
2520 | } |
2521 | } |
2522 | } |
2523 | StringSet<> MissingDisasmSymbolSet = |
2524 | set_difference(S1: DisasmSymbolSet, S2: FoundDisasmSymbolSet); |
2525 | for (StringRef Sym : MissingDisasmSymbolSet.keys()) |
2526 | reportWarning(Message: "failed to disassemble missing symbol " + Sym, File: FileName); |
2527 | } |
2528 | |
2529 | static void disassembleObject(ObjectFile *Obj, bool InlineRelocs) { |
2530 | // If information useful for showing the disassembly is missing, try to find a |
2531 | // more complete binary and disassemble that instead. |
2532 | OwningBinary<Binary> FetchedBinary; |
2533 | if (Obj->symbols().empty()) { |
2534 | if (std::optional<OwningBinary<Binary>> FetchedBinaryOpt = |
2535 | fetchBinaryByBuildID(Obj: *Obj)) { |
2536 | if (auto *O = dyn_cast<ObjectFile>(Val: FetchedBinaryOpt->getBinary())) { |
2537 | if (!O->symbols().empty() || |
2538 | (!O->sections().empty() && Obj->sections().empty())) { |
2539 | FetchedBinary = std::move(*FetchedBinaryOpt); |
2540 | Obj = O; |
2541 | } |
2542 | } |
2543 | } |
2544 | } |
2545 | |
2546 | const Target *TheTarget = getTarget(Obj); |
2547 | |
2548 | // Package up features to be passed to target/subtarget |
2549 | Expected<SubtargetFeatures> FeaturesValue = Obj->getFeatures(); |
2550 | if (!FeaturesValue) |
2551 | reportError(E: FeaturesValue.takeError(), FileName: Obj->getFileName()); |
2552 | SubtargetFeatures Features = *FeaturesValue; |
2553 | if (!MAttrs.empty()) { |
2554 | for (unsigned I = 0; I != MAttrs.size(); ++I) |
2555 | Features.AddFeature(String: MAttrs[I]); |
2556 | } else if (MCPU.empty() && Obj->getArch() == llvm::Triple::aarch64) { |
2557 | Features.AddFeature(String: "+all" ); |
2558 | } |
2559 | |
2560 | if (MCPU.empty()) |
2561 | MCPU = Obj->tryGetCPUName().value_or(u: "" ).str(); |
2562 | |
2563 | if (isArmElf(Obj: *Obj)) { |
2564 | // When disassembling big-endian Arm ELF, the instruction endianness is |
2565 | // determined in a complex way. In relocatable objects, AAELF32 mandates |
2566 | // that instruction endianness matches the ELF file endianness; in |
2567 | // executable images, that's true unless the file header has the EF_ARM_BE8 |
2568 | // flag, in which case instructions are little-endian regardless of data |
2569 | // endianness. |
2570 | // |
2571 | // We must set the big-endian-instructions SubtargetFeature to make the |
2572 | // disassembler read the instructions the right way round, and also tell |
2573 | // our own prettyprinter to retrieve the encodings the same way to print in |
2574 | // hex. |
2575 | const auto *Elf32BE = dyn_cast<ELF32BEObjectFile>(Val: Obj); |
2576 | |
2577 | if (Elf32BE && (Elf32BE->isRelocatableObject() || |
2578 | !(Elf32BE->getPlatformFlags() & ELF::EF_ARM_BE8))) { |
2579 | Features.AddFeature(String: "+big-endian-instructions" ); |
2580 | ARMPrettyPrinterInst.setInstructionEndianness(llvm::endianness::big); |
2581 | } else { |
2582 | ARMPrettyPrinterInst.setInstructionEndianness(llvm::endianness::little); |
2583 | } |
2584 | } |
2585 | |
2586 | DisassemblerTarget PrimaryTarget(TheTarget, *Obj, TripleName, MCPU, Features); |
2587 | |
2588 | // If we have an ARM object file, we need a second disassembler, because |
2589 | // ARM CPUs have two different instruction sets: ARM mode, and Thumb mode. |
2590 | // We use mapping symbols to switch between the two assemblers, where |
2591 | // appropriate. |
2592 | std::optional<DisassemblerTarget> SecondaryTarget; |
2593 | |
2594 | if (isArmElf(Obj: *Obj)) { |
2595 | if (!PrimaryTarget.SubtargetInfo->checkFeatures(FS: "+mclass" )) { |
2596 | if (PrimaryTarget.SubtargetInfo->checkFeatures(FS: "+thumb-mode" )) |
2597 | Features.AddFeature(String: "-thumb-mode" ); |
2598 | else |
2599 | Features.AddFeature(String: "+thumb-mode" ); |
2600 | SecondaryTarget.emplace(args&: PrimaryTarget, args&: Features); |
2601 | } |
2602 | } else if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Val: Obj)) { |
2603 | const chpe_metadata *CHPEMetadata = COFFObj->getCHPEMetadata(); |
2604 | if (CHPEMetadata && CHPEMetadata->CodeMapCount) { |
2605 | // Set up x86_64 disassembler for ARM64EC binaries. |
2606 | Triple X64Triple(TripleName); |
2607 | X64Triple.setArch(Kind: Triple::ArchType::x86_64); |
2608 | |
2609 | std::string Error; |
2610 | const Target *X64Target = |
2611 | TargetRegistry::lookupTarget(ArchName: "" , TheTriple&: X64Triple, Error); |
2612 | if (X64Target) { |
2613 | SubtargetFeatures X64Features; |
2614 | SecondaryTarget.emplace(args&: X64Target, args&: *Obj, args: X64Triple.getTriple(), args: "" , |
2615 | args&: X64Features); |
2616 | } else { |
2617 | reportWarning(Message: Error, File: Obj->getFileName()); |
2618 | } |
2619 | } |
2620 | } |
2621 | |
2622 | const ObjectFile *DbgObj = Obj; |
2623 | if (!FetchedBinary.getBinary() && !Obj->hasDebugInfo()) { |
2624 | if (std::optional<OwningBinary<Binary>> DebugBinaryOpt = |
2625 | fetchBinaryByBuildID(Obj: *Obj)) { |
2626 | if (auto *FetchedObj = |
2627 | dyn_cast<const ObjectFile>(Val: DebugBinaryOpt->getBinary())) { |
2628 | if (FetchedObj->hasDebugInfo()) { |
2629 | FetchedBinary = std::move(*DebugBinaryOpt); |
2630 | DbgObj = FetchedObj; |
2631 | } |
2632 | } |
2633 | } |
2634 | } |
2635 | |
2636 | std::unique_ptr<object::Binary> DSYMBinary; |
2637 | std::unique_ptr<MemoryBuffer> DSYMBuf; |
2638 | if (!DbgObj->hasDebugInfo()) { |
2639 | if (const MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(Val: &*Obj)) { |
2640 | DbgObj = objdump::getMachODSymObject(O: MachOOF, Filename: Obj->getFileName(), |
2641 | DSYMBinary, DSYMBuf); |
2642 | if (!DbgObj) |
2643 | return; |
2644 | } |
2645 | } |
2646 | |
2647 | SourcePrinter SP(DbgObj, TheTarget->getName()); |
2648 | |
2649 | for (StringRef Opt : DisassemblerOptions) |
2650 | if (!PrimaryTarget.InstPrinter->applyTargetSpecificCLOption(Opt)) |
2651 | reportError(File: Obj->getFileName(), |
2652 | Message: "Unrecognized disassembler option: " + Opt); |
2653 | |
2654 | disassembleObject(Obj&: *Obj, DbgObj: *DbgObj, PrimaryTarget, SecondaryTarget, SP, |
2655 | InlineRelocs); |
2656 | } |
2657 | |
2658 | void Dumper::printRelocations() { |
2659 | StringRef Fmt = O.getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64; |
2660 | |
2661 | // Build a mapping from relocation target to a vector of relocation |
2662 | // sections. Usually, there is an only one relocation section for |
2663 | // each relocated section. |
2664 | MapVector<SectionRef, std::vector<SectionRef>> SecToRelSec; |
2665 | uint64_t Ndx; |
2666 | for (const SectionRef &Section : ToolSectionFilter(O, Idx: &Ndx)) { |
2667 | if (O.isELF() && (ELFSectionRef(Section).getFlags() & ELF::SHF_ALLOC)) |
2668 | continue; |
2669 | if (Section.relocation_begin() == Section.relocation_end()) |
2670 | continue; |
2671 | Expected<section_iterator> SecOrErr = Section.getRelocatedSection(); |
2672 | if (!SecOrErr) |
2673 | reportError(File: O.getFileName(), |
2674 | Message: "section (" + Twine(Ndx) + |
2675 | "): unable to get a relocation target: " + |
2676 | toString(E: SecOrErr.takeError())); |
2677 | SecToRelSec[**SecOrErr].push_back(x: Section); |
2678 | } |
2679 | |
2680 | for (std::pair<SectionRef, std::vector<SectionRef>> &P : SecToRelSec) { |
2681 | StringRef SecName = unwrapOrError(EO: P.first.getName(), Args: O.getFileName()); |
2682 | outs() << "\nRELOCATION RECORDS FOR [" << SecName << "]:\n" ; |
2683 | uint32_t OffsetPadding = (O.getBytesInAddress() > 4 ? 16 : 8); |
2684 | uint32_t TypePadding = 24; |
2685 | outs() << left_justify(Str: "OFFSET" , Width: OffsetPadding) << " " |
2686 | << left_justify(Str: "TYPE" , Width: TypePadding) << " " |
2687 | << "VALUE\n" ; |
2688 | |
2689 | for (SectionRef Section : P.second) { |
2690 | // CREL sections require decoding, each section may have its own specific |
2691 | // decode problems. |
2692 | if (O.isELF() && ELFSectionRef(Section).getType() == ELF::SHT_CREL) { |
2693 | StringRef Err = |
2694 | cast<const ELFObjectFileBase>(Val: O).getCrelDecodeProblem(Sec: Section); |
2695 | if (!Err.empty()) { |
2696 | reportUniqueWarning(Msg: Err); |
2697 | continue; |
2698 | } |
2699 | } |
2700 | for (const RelocationRef &Reloc : Section.relocations()) { |
2701 | uint64_t Address = Reloc.getOffset(); |
2702 | SmallString<32> RelocName; |
2703 | SmallString<32> ValueStr; |
2704 | if (Address < StartAddress || Address > StopAddress || getHidden(RelRef: Reloc)) |
2705 | continue; |
2706 | Reloc.getTypeName(Result&: RelocName); |
2707 | if (Error E = |
2708 | getRelocationValueString(Rel: Reloc, SymbolDescription, Result&: ValueStr)) |
2709 | reportUniqueWarning(Err: std::move(E)); |
2710 | |
2711 | outs() << format(Fmt: Fmt.data(), Vals: Address) << " " |
2712 | << left_justify(Str: RelocName, Width: TypePadding) << " " << ValueStr |
2713 | << "\n" ; |
2714 | } |
2715 | } |
2716 | } |
2717 | } |
2718 | |
2719 | // Returns true if we need to show LMA column when dumping section headers. We |
2720 | // show it only when the platform is ELF and either we have at least one section |
2721 | // whose VMA and LMA are different and/or when --show-lma flag is used. |
2722 | static bool shouldDisplayLMA(const ObjectFile &Obj) { |
2723 | if (!Obj.isELF()) |
2724 | return false; |
2725 | for (const SectionRef &S : ToolSectionFilter(O: Obj)) |
2726 | if (S.getAddress() != getELFSectionLMA(Sec: S)) |
2727 | return true; |
2728 | return ShowLMA; |
2729 | } |
2730 | |
2731 | static size_t getMaxSectionNameWidth(const ObjectFile &Obj) { |
2732 | // Default column width for names is 13 even if no names are that long. |
2733 | size_t MaxWidth = 13; |
2734 | for (const SectionRef &Section : ToolSectionFilter(O: Obj)) { |
2735 | StringRef Name = unwrapOrError(EO: Section.getName(), Args: Obj.getFileName()); |
2736 | MaxWidth = std::max(a: MaxWidth, b: Name.size()); |
2737 | } |
2738 | return MaxWidth; |
2739 | } |
2740 | |
2741 | void objdump::(ObjectFile &Obj) { |
2742 | if (Obj.isELF() && Obj.sections().empty()) |
2743 | createFakeELFSections(Obj); |
2744 | |
2745 | size_t NameWidth = getMaxSectionNameWidth(Obj); |
2746 | size_t AddressWidth = 2 * Obj.getBytesInAddress(); |
2747 | bool HasLMAColumn = shouldDisplayLMA(Obj); |
2748 | outs() << "\nSections:\n" ; |
2749 | if (HasLMAColumn) |
2750 | outs() << "Idx " << left_justify(Str: "Name" , Width: NameWidth) << " Size " |
2751 | << left_justify(Str: "VMA" , Width: AddressWidth) << " " |
2752 | << left_justify(Str: "LMA" , Width: AddressWidth) << " Type\n" ; |
2753 | else |
2754 | outs() << "Idx " << left_justify(Str: "Name" , Width: NameWidth) << " Size " |
2755 | << left_justify(Str: "VMA" , Width: AddressWidth) << " Type\n" ; |
2756 | |
2757 | uint64_t Idx; |
2758 | for (const SectionRef &Section : ToolSectionFilter(O: Obj, Idx: &Idx)) { |
2759 | StringRef Name = unwrapOrError(EO: Section.getName(), Args: Obj.getFileName()); |
2760 | uint64_t VMA = Section.getAddress(); |
2761 | if (shouldAdjustVA(Section)) |
2762 | VMA += AdjustVMA; |
2763 | |
2764 | uint64_t Size = Section.getSize(); |
2765 | |
2766 | std::string Type = Section.isText() ? "TEXT" : "" ; |
2767 | if (Section.isData()) |
2768 | Type += Type.empty() ? "DATA" : ", DATA" ; |
2769 | if (Section.isBSS()) |
2770 | Type += Type.empty() ? "BSS" : ", BSS" ; |
2771 | if (Section.isDebugSection()) |
2772 | Type += Type.empty() ? "DEBUG" : ", DEBUG" ; |
2773 | |
2774 | if (HasLMAColumn) |
2775 | outs() << format(Fmt: "%3" PRIu64 " %-*s %08" PRIx64 " " , Vals: Idx, Vals: NameWidth, |
2776 | Vals: Name.str().c_str(), Vals: Size) |
2777 | << format_hex_no_prefix(N: VMA, Width: AddressWidth) << " " |
2778 | << format_hex_no_prefix(N: getELFSectionLMA(Sec: Section), Width: AddressWidth) |
2779 | << " " << Type << "\n" ; |
2780 | else |
2781 | outs() << format(Fmt: "%3" PRIu64 " %-*s %08" PRIx64 " " , Vals: Idx, Vals: NameWidth, |
2782 | Vals: Name.str().c_str(), Vals: Size) |
2783 | << format_hex_no_prefix(N: VMA, Width: AddressWidth) << " " << Type << "\n" ; |
2784 | } |
2785 | } |
2786 | |
2787 | void objdump::printSectionContents(const ObjectFile *Obj) { |
2788 | const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Val: Obj); |
2789 | |
2790 | for (const SectionRef &Section : ToolSectionFilter(O: *Obj)) { |
2791 | StringRef Name = unwrapOrError(EO: Section.getName(), Args: Obj->getFileName()); |
2792 | uint64_t BaseAddr = Section.getAddress(); |
2793 | uint64_t Size = Section.getSize(); |
2794 | if (!Size) |
2795 | continue; |
2796 | |
2797 | outs() << "Contents of section " ; |
2798 | StringRef SegmentName = getSegmentName(MachO, Section); |
2799 | if (!SegmentName.empty()) |
2800 | outs() << SegmentName << "," ; |
2801 | outs() << Name << ":\n" ; |
2802 | if (Section.isBSS()) { |
2803 | outs() << format(Fmt: "<skipping contents of bss section at [%04" PRIx64 |
2804 | ", %04" PRIx64 ")>\n" , |
2805 | Vals: BaseAddr, Vals: BaseAddr + Size); |
2806 | continue; |
2807 | } |
2808 | |
2809 | StringRef Contents = unwrapOrError(EO: Section.getContents(), Args: Obj->getFileName()); |
2810 | |
2811 | // Dump out the content as hex and printable ascii characters. |
2812 | for (std::size_t Addr = 0, End = Contents.size(); Addr < End; Addr += 16) { |
2813 | outs() << format(Fmt: " %04" PRIx64 " " , Vals: BaseAddr + Addr); |
2814 | // Dump line of hex. |
2815 | for (std::size_t I = 0; I < 16; ++I) { |
2816 | if (I != 0 && I % 4 == 0) |
2817 | outs() << ' '; |
2818 | if (Addr + I < End) |
2819 | outs() << hexdigit(X: (Contents[Addr + I] >> 4) & 0xF, LowerCase: true) |
2820 | << hexdigit(X: Contents[Addr + I] & 0xF, LowerCase: true); |
2821 | else |
2822 | outs() << " " ; |
2823 | } |
2824 | // Print ascii. |
2825 | outs() << " " ; |
2826 | for (std::size_t I = 0; I < 16 && Addr + I < End; ++I) { |
2827 | if (isPrint(C: static_cast<unsigned char>(Contents[Addr + I]) & 0xFF)) |
2828 | outs() << Contents[Addr + I]; |
2829 | else |
2830 | outs() << "." ; |
2831 | } |
2832 | outs() << "\n" ; |
2833 | } |
2834 | } |
2835 | } |
2836 | |
2837 | void Dumper::printSymbolTable(StringRef ArchiveName, StringRef ArchitectureName, |
2838 | bool DumpDynamic) { |
2839 | if (O.isCOFF() && !DumpDynamic) { |
2840 | outs() << "\nSYMBOL TABLE:\n" ; |
2841 | printCOFFSymbolTable(O: cast<const COFFObjectFile>(Val: O)); |
2842 | return; |
2843 | } |
2844 | |
2845 | const StringRef FileName = O.getFileName(); |
2846 | |
2847 | if (!DumpDynamic) { |
2848 | outs() << "\nSYMBOL TABLE:\n" ; |
2849 | for (auto I = O.symbol_begin(); I != O.symbol_end(); ++I) |
2850 | printSymbol(Symbol: *I, SymbolVersions: {}, FileName, ArchiveName, ArchitectureName, DumpDynamic); |
2851 | return; |
2852 | } |
2853 | |
2854 | outs() << "\nDYNAMIC SYMBOL TABLE:\n" ; |
2855 | if (!O.isELF()) { |
2856 | reportWarning( |
2857 | Message: "this operation is not currently supported for this file format" , |
2858 | File: FileName); |
2859 | return; |
2860 | } |
2861 | |
2862 | const ELFObjectFileBase *ELF = cast<const ELFObjectFileBase>(Val: &O); |
2863 | auto Symbols = ELF->getDynamicSymbolIterators(); |
2864 | Expected<std::vector<VersionEntry>> SymbolVersionsOrErr = |
2865 | ELF->readDynsymVersions(); |
2866 | if (!SymbolVersionsOrErr) { |
2867 | reportWarning(Message: toString(E: SymbolVersionsOrErr.takeError()), File: FileName); |
2868 | SymbolVersionsOrErr = std::vector<VersionEntry>(); |
2869 | (void)!SymbolVersionsOrErr; |
2870 | } |
2871 | for (auto &Sym : Symbols) |
2872 | printSymbol(Symbol: Sym, SymbolVersions: *SymbolVersionsOrErr, FileName, ArchiveName, |
2873 | ArchitectureName, DumpDynamic); |
2874 | } |
2875 | |
2876 | void Dumper::printSymbol(const SymbolRef &Symbol, |
2877 | ArrayRef<VersionEntry> SymbolVersions, |
2878 | StringRef FileName, StringRef ArchiveName, |
2879 | StringRef ArchitectureName, bool DumpDynamic) { |
2880 | const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Val: &O); |
2881 | Expected<uint64_t> AddrOrErr = Symbol.getAddress(); |
2882 | if (!AddrOrErr) { |
2883 | reportUniqueWarning(Err: AddrOrErr.takeError()); |
2884 | return; |
2885 | } |
2886 | uint64_t Address = *AddrOrErr; |
2887 | section_iterator SecI = unwrapOrError(EO: Symbol.getSection(), Args&: FileName); |
2888 | if (SecI != O.section_end() && shouldAdjustVA(Section: *SecI)) |
2889 | Address += AdjustVMA; |
2890 | if ((Address < StartAddress) || (Address > StopAddress)) |
2891 | return; |
2892 | SymbolRef::Type Type = |
2893 | unwrapOrError(EO: Symbol.getType(), Args&: FileName, Args&: ArchiveName, Args&: ArchitectureName); |
2894 | uint32_t Flags = |
2895 | unwrapOrError(EO: Symbol.getFlags(), Args&: FileName, Args&: ArchiveName, Args&: ArchitectureName); |
2896 | |
2897 | // Don't ask a Mach-O STAB symbol for its section unless you know that |
2898 | // STAB symbol's section field refers to a valid section index. Otherwise |
2899 | // the symbol may error trying to load a section that does not exist. |
2900 | bool IsSTAB = false; |
2901 | if (MachO) { |
2902 | DataRefImpl SymDRI = Symbol.getRawDataRefImpl(); |
2903 | uint8_t NType = |
2904 | (MachO->is64Bit() ? MachO->getSymbol64TableEntry(DRI: SymDRI).n_type |
2905 | : MachO->getSymbolTableEntry(DRI: SymDRI).n_type); |
2906 | if (NType & MachO::N_STAB) |
2907 | IsSTAB = true; |
2908 | } |
2909 | section_iterator Section = IsSTAB |
2910 | ? O.section_end() |
2911 | : unwrapOrError(EO: Symbol.getSection(), Args&: FileName, |
2912 | Args&: ArchiveName, Args&: ArchitectureName); |
2913 | |
2914 | StringRef Name; |
2915 | if (Type == SymbolRef::ST_Debug && Section != O.section_end()) { |
2916 | if (Expected<StringRef> NameOrErr = Section->getName()) |
2917 | Name = *NameOrErr; |
2918 | else |
2919 | consumeError(Err: NameOrErr.takeError()); |
2920 | |
2921 | } else { |
2922 | Name = unwrapOrError(EO: Symbol.getName(), Args&: FileName, Args&: ArchiveName, |
2923 | Args&: ArchitectureName); |
2924 | } |
2925 | |
2926 | bool Global = Flags & SymbolRef::SF_Global; |
2927 | bool Weak = Flags & SymbolRef::SF_Weak; |
2928 | bool Absolute = Flags & SymbolRef::SF_Absolute; |
2929 | bool Common = Flags & SymbolRef::SF_Common; |
2930 | bool Hidden = Flags & SymbolRef::SF_Hidden; |
2931 | |
2932 | char GlobLoc = ' '; |
2933 | if ((Section != O.section_end() || Absolute) && !Weak) |
2934 | GlobLoc = Global ? 'g' : 'l'; |
2935 | char IFunc = ' '; |
2936 | if (O.isELF()) { |
2937 | if (ELFSymbolRef(Symbol).getELFType() == ELF::STT_GNU_IFUNC) |
2938 | IFunc = 'i'; |
2939 | if (ELFSymbolRef(Symbol).getBinding() == ELF::STB_GNU_UNIQUE) |
2940 | GlobLoc = 'u'; |
2941 | } |
2942 | |
2943 | char Debug = ' '; |
2944 | if (DumpDynamic) |
2945 | Debug = 'D'; |
2946 | else if (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File) |
2947 | Debug = 'd'; |
2948 | |
2949 | char FileFunc = ' '; |
2950 | if (Type == SymbolRef::ST_File) |
2951 | FileFunc = 'f'; |
2952 | else if (Type == SymbolRef::ST_Function) |
2953 | FileFunc = 'F'; |
2954 | else if (Type == SymbolRef::ST_Data) |
2955 | FileFunc = 'O'; |
2956 | |
2957 | const char *Fmt = O.getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64; |
2958 | |
2959 | outs() << format(Fmt, Vals: Address) << " " |
2960 | << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' ' |
2961 | << (Weak ? 'w' : ' ') // Weak? |
2962 | << ' ' // Constructor. Not supported yet. |
2963 | << ' ' // Warning. Not supported yet. |
2964 | << IFunc // Indirect reference to another symbol. |
2965 | << Debug // Debugging (d) or dynamic (D) symbol. |
2966 | << FileFunc // Name of function (F), file (f) or object (O). |
2967 | << ' '; |
2968 | if (Absolute) { |
2969 | outs() << "*ABS*" ; |
2970 | } else if (Common) { |
2971 | outs() << "*COM*" ; |
2972 | } else if (Section == O.section_end()) { |
2973 | if (O.isXCOFF()) { |
2974 | XCOFFSymbolRef XCOFFSym = cast<const XCOFFObjectFile>(Val: O).toSymbolRef( |
2975 | Ref: Symbol.getRawDataRefImpl()); |
2976 | if (XCOFF::N_DEBUG == XCOFFSym.getSectionNumber()) |
2977 | outs() << "*DEBUG*" ; |
2978 | else |
2979 | outs() << "*UND*" ; |
2980 | } else |
2981 | outs() << "*UND*" ; |
2982 | } else { |
2983 | StringRef SegmentName = getSegmentName(MachO, Section: *Section); |
2984 | if (!SegmentName.empty()) |
2985 | outs() << SegmentName << "," ; |
2986 | StringRef SectionName = unwrapOrError(EO: Section->getName(), Args&: FileName); |
2987 | outs() << SectionName; |
2988 | if (O.isXCOFF()) { |
2989 | std::optional<SymbolRef> SymRef = |
2990 | getXCOFFSymbolContainingSymbolRef(Obj: cast<XCOFFObjectFile>(Val: O), Sym: Symbol); |
2991 | if (SymRef) { |
2992 | |
2993 | Expected<StringRef> NameOrErr = SymRef->getName(); |
2994 | |
2995 | if (NameOrErr) { |
2996 | outs() << " (csect:" ; |
2997 | std::string SymName = |
2998 | Demangle ? demangle(MangledName: *NameOrErr) : NameOrErr->str(); |
2999 | |
3000 | if (SymbolDescription) |
3001 | SymName = getXCOFFSymbolDescription(SymbolInfo: createSymbolInfo(Obj: O, Symbol: *SymRef), |
3002 | SymbolName: SymName); |
3003 | |
3004 | outs() << ' ' << SymName; |
3005 | outs() << ") " ; |
3006 | } else |
3007 | reportWarning(Message: toString(E: NameOrErr.takeError()), File: FileName); |
3008 | } |
3009 | } |
3010 | } |
3011 | |
3012 | if (Common) |
3013 | outs() << '\t' << format(Fmt, Vals: static_cast<uint64_t>(Symbol.getAlignment())); |
3014 | else if (O.isXCOFF()) |
3015 | outs() << '\t' |
3016 | << format(Fmt, Vals: cast<XCOFFObjectFile>(Val: O).getSymbolSize( |
3017 | Symb: Symbol.getRawDataRefImpl())); |
3018 | else if (O.isELF()) |
3019 | outs() << '\t' << format(Fmt, Vals: ELFSymbolRef(Symbol).getSize()); |
3020 | else if (O.isWasm()) |
3021 | outs() << '\t' |
3022 | << format(Fmt, Vals: static_cast<uint64_t>( |
3023 | cast<WasmObjectFile>(Val: O).getSymbolSize(Sym: Symbol))); |
3024 | |
3025 | if (O.isELF()) { |
3026 | if (!SymbolVersions.empty()) { |
3027 | const VersionEntry &Ver = |
3028 | SymbolVersions[Symbol.getRawDataRefImpl().d.b - 1]; |
3029 | std::string Str; |
3030 | if (!Ver.Name.empty()) |
3031 | Str = Ver.IsVerDef ? ' ' + Ver.Name : '(' + Ver.Name + ')'; |
3032 | outs() << ' ' << left_justify(Str, Width: 12); |
3033 | } |
3034 | |
3035 | uint8_t Other = ELFSymbolRef(Symbol).getOther(); |
3036 | switch (Other) { |
3037 | case ELF::STV_DEFAULT: |
3038 | break; |
3039 | case ELF::STV_INTERNAL: |
3040 | outs() << " .internal" ; |
3041 | break; |
3042 | case ELF::STV_HIDDEN: |
3043 | outs() << " .hidden" ; |
3044 | break; |
3045 | case ELF::STV_PROTECTED: |
3046 | outs() << " .protected" ; |
3047 | break; |
3048 | default: |
3049 | outs() << format(Fmt: " 0x%02x" , Vals: Other); |
3050 | break; |
3051 | } |
3052 | } else if (Hidden) { |
3053 | outs() << " .hidden" ; |
3054 | } |
3055 | |
3056 | std::string SymName = Demangle ? demangle(MangledName: Name) : Name.str(); |
3057 | if (O.isXCOFF() && SymbolDescription) |
3058 | SymName = getXCOFFSymbolDescription(SymbolInfo: createSymbolInfo(Obj: O, Symbol), SymbolName: SymName); |
3059 | |
3060 | outs() << ' ' << SymName << '\n'; |
3061 | } |
3062 | |
3063 | static void printUnwindInfo(const ObjectFile *O) { |
3064 | outs() << "Unwind info:\n\n" ; |
3065 | |
3066 | if (const COFFObjectFile *Coff = dyn_cast<COFFObjectFile>(Val: O)) |
3067 | printCOFFUnwindInfo(O: Coff); |
3068 | else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(Val: O)) |
3069 | printMachOUnwindInfo(O: MachO); |
3070 | else |
3071 | // TODO: Extract DWARF dump tool to objdump. |
3072 | WithColor::error(OS&: errs(), Prefix: ToolName) |
3073 | << "This operation is only currently supported " |
3074 | "for COFF and MachO object files.\n" ; |
3075 | } |
3076 | |
3077 | /// Dump the raw contents of the __clangast section so the output can be piped |
3078 | /// into llvm-bcanalyzer. |
3079 | static void printRawClangAST(const ObjectFile *Obj) { |
3080 | if (outs().is_displayed()) { |
3081 | WithColor::error(OS&: errs(), Prefix: ToolName) |
3082 | << "The -raw-clang-ast option will dump the raw binary contents of " |
3083 | "the clang ast section.\n" |
3084 | "Please redirect the output to a file or another program such as " |
3085 | "llvm-bcanalyzer.\n" ; |
3086 | return; |
3087 | } |
3088 | |
3089 | StringRef ClangASTSectionName("__clangast" ); |
3090 | if (Obj->isCOFF()) { |
3091 | ClangASTSectionName = "clangast" ; |
3092 | } |
3093 | |
3094 | std::optional<object::SectionRef> ClangASTSection; |
3095 | for (auto Sec : ToolSectionFilter(O: *Obj)) { |
3096 | StringRef Name; |
3097 | if (Expected<StringRef> NameOrErr = Sec.getName()) |
3098 | Name = *NameOrErr; |
3099 | else |
3100 | consumeError(Err: NameOrErr.takeError()); |
3101 | |
3102 | if (Name == ClangASTSectionName) { |
3103 | ClangASTSection = Sec; |
3104 | break; |
3105 | } |
3106 | } |
3107 | if (!ClangASTSection) |
3108 | return; |
3109 | |
3110 | StringRef ClangASTContents = |
3111 | unwrapOrError(EO: ClangASTSection->getContents(), Args: Obj->getFileName()); |
3112 | outs().write(Ptr: ClangASTContents.data(), Size: ClangASTContents.size()); |
3113 | } |
3114 | |
3115 | static void printFaultMaps(const ObjectFile *Obj) { |
3116 | StringRef FaultMapSectionName; |
3117 | |
3118 | if (Obj->isELF()) { |
3119 | FaultMapSectionName = ".llvm_faultmaps" ; |
3120 | } else if (Obj->isMachO()) { |
3121 | FaultMapSectionName = "__llvm_faultmaps" ; |
3122 | } else { |
3123 | WithColor::error(OS&: errs(), Prefix: ToolName) |
3124 | << "This operation is only currently supported " |
3125 | "for ELF and Mach-O executable files.\n" ; |
3126 | return; |
3127 | } |
3128 | |
3129 | std::optional<object::SectionRef> FaultMapSection; |
3130 | |
3131 | for (auto Sec : ToolSectionFilter(O: *Obj)) { |
3132 | StringRef Name; |
3133 | if (Expected<StringRef> NameOrErr = Sec.getName()) |
3134 | Name = *NameOrErr; |
3135 | else |
3136 | consumeError(Err: NameOrErr.takeError()); |
3137 | |
3138 | if (Name == FaultMapSectionName) { |
3139 | FaultMapSection = Sec; |
3140 | break; |
3141 | } |
3142 | } |
3143 | |
3144 | outs() << "FaultMap table:\n" ; |
3145 | |
3146 | if (!FaultMapSection) { |
3147 | outs() << "<not found>\n" ; |
3148 | return; |
3149 | } |
3150 | |
3151 | StringRef FaultMapContents = |
3152 | unwrapOrError(EO: FaultMapSection->getContents(), Args: Obj->getFileName()); |
3153 | FaultMapParser FMP(FaultMapContents.bytes_begin(), |
3154 | FaultMapContents.bytes_end()); |
3155 | |
3156 | outs() << FMP; |
3157 | } |
3158 | |
3159 | void Dumper::() { |
3160 | reportError(File: O.getFileName(), Message: "Invalid/Unsupported object file format" ); |
3161 | } |
3162 | |
3163 | static void (const ObjectFile *O) { |
3164 | if (!O->isELF() && !O->isCOFF() && !O->isXCOFF()) |
3165 | reportError(File: O->getFileName(), Message: "Invalid/Unsupported object file format" ); |
3166 | |
3167 | Triple::ArchType AT = O->getArch(); |
3168 | outs() << "architecture: " << Triple::getArchTypeName(Kind: AT) << "\n" ; |
3169 | uint64_t Address = unwrapOrError(EO: O->getStartAddress(), Args: O->getFileName()); |
3170 | |
3171 | StringRef Fmt = O->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64; |
3172 | outs() << "start address: " |
3173 | << "0x" << format(Fmt: Fmt.data(), Vals: Address) << "\n" ; |
3174 | } |
3175 | |
3176 | static void printArchiveChild(StringRef Filename, const Archive::Child &C) { |
3177 | Expected<sys::fs::perms> ModeOrErr = C.getAccessMode(); |
3178 | if (!ModeOrErr) { |
3179 | WithColor::error(OS&: errs(), Prefix: ToolName) << "ill-formed archive entry.\n" ; |
3180 | consumeError(Err: ModeOrErr.takeError()); |
3181 | return; |
3182 | } |
3183 | sys::fs::perms Mode = ModeOrErr.get(); |
3184 | outs() << ((Mode & sys::fs::owner_read) ? "r" : "-" ); |
3185 | outs() << ((Mode & sys::fs::owner_write) ? "w" : "-" ); |
3186 | outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-" ); |
3187 | outs() << ((Mode & sys::fs::group_read) ? "r" : "-" ); |
3188 | outs() << ((Mode & sys::fs::group_write) ? "w" : "-" ); |
3189 | outs() << ((Mode & sys::fs::group_exe) ? "x" : "-" ); |
3190 | outs() << ((Mode & sys::fs::others_read) ? "r" : "-" ); |
3191 | outs() << ((Mode & sys::fs::others_write) ? "w" : "-" ); |
3192 | outs() << ((Mode & sys::fs::others_exe) ? "x" : "-" ); |
3193 | |
3194 | outs() << " " ; |
3195 | |
3196 | outs() << format(Fmt: "%d/%d %6" PRId64 " " , Vals: unwrapOrError(EO: C.getUID(), Args&: Filename), |
3197 | Vals: unwrapOrError(EO: C.getGID(), Args&: Filename), |
3198 | Vals: unwrapOrError(EO: C.getRawSize(), Args&: Filename)); |
3199 | |
3200 | StringRef RawLastModified = C.getRawLastModified(); |
3201 | unsigned Seconds; |
3202 | if (RawLastModified.getAsInteger(Radix: 10, Result&: Seconds)) |
3203 | outs() << "(date: \"" << RawLastModified |
3204 | << "\" contains non-decimal chars) " ; |
3205 | else { |
3206 | // Since ctime(3) returns a 26 character string of the form: |
3207 | // "Sun Sep 16 01:03:52 1973\n\0" |
3208 | // just print 24 characters. |
3209 | time_t t = Seconds; |
3210 | outs() << format(Fmt: "%.24s " , Vals: ctime(timer: &t)); |
3211 | } |
3212 | |
3213 | StringRef Name = "" ; |
3214 | Expected<StringRef> NameOrErr = C.getName(); |
3215 | if (!NameOrErr) { |
3216 | consumeError(Err: NameOrErr.takeError()); |
3217 | Name = unwrapOrError(EO: C.getRawName(), Args&: Filename); |
3218 | } else { |
3219 | Name = NameOrErr.get(); |
3220 | } |
3221 | outs() << Name << "\n" ; |
3222 | } |
3223 | |
3224 | // For ELF only now. |
3225 | static bool shouldWarnForInvalidStartStopAddress(ObjectFile *Obj) { |
3226 | if (const auto *Elf = dyn_cast<ELFObjectFileBase>(Val: Obj)) { |
3227 | if (Elf->getEType() != ELF::ET_REL) |
3228 | return true; |
3229 | } |
3230 | return false; |
3231 | } |
3232 | |
3233 | static void checkForInvalidStartStopAddress(ObjectFile *Obj, |
3234 | uint64_t Start, uint64_t Stop) { |
3235 | if (!shouldWarnForInvalidStartStopAddress(Obj)) |
3236 | return; |
3237 | |
3238 | for (const SectionRef &Section : Obj->sections()) |
3239 | if (ELFSectionRef(Section).getFlags() & ELF::SHF_ALLOC) { |
3240 | uint64_t BaseAddr = Section.getAddress(); |
3241 | uint64_t Size = Section.getSize(); |
3242 | if ((Start < BaseAddr + Size) && Stop > BaseAddr) |
3243 | return; |
3244 | } |
3245 | |
3246 | if (!HasStartAddressFlag) |
3247 | reportWarning(Message: "no section has address less than 0x" + |
3248 | Twine::utohexstr(Val: Stop) + " specified by --stop-address" , |
3249 | File: Obj->getFileName()); |
3250 | else if (!HasStopAddressFlag) |
3251 | reportWarning(Message: "no section has address greater than or equal to 0x" + |
3252 | Twine::utohexstr(Val: Start) + " specified by --start-address" , |
3253 | File: Obj->getFileName()); |
3254 | else |
3255 | reportWarning(Message: "no section overlaps the range [0x" + |
3256 | Twine::utohexstr(Val: Start) + ",0x" + Twine::utohexstr(Val: Stop) + |
3257 | ") specified by --start-address/--stop-address" , |
3258 | File: Obj->getFileName()); |
3259 | } |
3260 | |
3261 | static void dumpObject(ObjectFile *O, const Archive *A = nullptr, |
3262 | const Archive::Child *C = nullptr) { |
3263 | Expected<std::unique_ptr<Dumper>> DumperOrErr = createDumper(Obj: *O); |
3264 | if (!DumperOrErr) { |
3265 | reportError(E: DumperOrErr.takeError(), FileName: O->getFileName(), |
3266 | ArchiveName: A ? A->getFileName() : "" ); |
3267 | return; |
3268 | } |
3269 | Dumper &D = **DumperOrErr; |
3270 | |
3271 | // Avoid other output when using a raw option. |
3272 | if (!RawClangAST) { |
3273 | outs() << '\n'; |
3274 | if (A) |
3275 | outs() << A->getFileName() << "(" << O->getFileName() << ")" ; |
3276 | else |
3277 | outs() << O->getFileName(); |
3278 | outs() << ":\tfile format " << O->getFileFormatName().lower() << "\n" ; |
3279 | } |
3280 | |
3281 | if (HasStartAddressFlag || HasStopAddressFlag) |
3282 | checkForInvalidStartStopAddress(Obj: O, Start: StartAddress, Stop: StopAddress); |
3283 | |
3284 | // TODO: Change print* free functions to Dumper member functions to utilitize |
3285 | // stateful functions like reportUniqueWarning. |
3286 | |
3287 | // Note: the order here matches GNU objdump for compatability. |
3288 | StringRef ArchiveName = A ? A->getFileName() : "" ; |
3289 | if (ArchiveHeaders && !MachOOpt && C) |
3290 | printArchiveChild(Filename: ArchiveName, C: *C); |
3291 | if (FileHeaders) |
3292 | printFileHeaders(O); |
3293 | if (PrivateHeaders || FirstPrivateHeader) |
3294 | D.printPrivateHeaders(); |
3295 | if (SectionHeaders) |
3296 | printSectionHeaders(Obj&: *O); |
3297 | if (SymbolTable) |
3298 | D.printSymbolTable(ArchiveName); |
3299 | if (DynamicSymbolTable) |
3300 | D.printSymbolTable(ArchiveName, /*ArchitectureName=*/"" , |
3301 | /*DumpDynamic=*/true); |
3302 | if (DwarfDumpType != DIDT_Null) { |
3303 | std::unique_ptr<DIContext> DICtx = DWARFContext::create(Obj: *O); |
3304 | // Dump the complete DWARF structure. |
3305 | DIDumpOptions DumpOpts; |
3306 | DumpOpts.DumpType = DwarfDumpType; |
3307 | DICtx->dump(OS&: outs(), DumpOpts); |
3308 | } |
3309 | if (Relocations && !Disassemble) |
3310 | D.printRelocations(); |
3311 | if (DynamicRelocations) |
3312 | D.printDynamicRelocations(); |
3313 | if (SectionContents) |
3314 | printSectionContents(Obj: O); |
3315 | if (Disassemble) |
3316 | disassembleObject(Obj: O, InlineRelocs: Relocations); |
3317 | if (UnwindInfo) |
3318 | printUnwindInfo(O); |
3319 | |
3320 | // Mach-O specific options: |
3321 | if (ExportsTrie) |
3322 | printExportsTrie(O); |
3323 | if (Rebase) |
3324 | printRebaseTable(O); |
3325 | if (Bind) |
3326 | printBindTable(O); |
3327 | if (LazyBind) |
3328 | printLazyBindTable(O); |
3329 | if (WeakBind) |
3330 | printWeakBindTable(O); |
3331 | |
3332 | // Other special sections: |
3333 | if (RawClangAST) |
3334 | printRawClangAST(Obj: O); |
3335 | if (FaultMapSection) |
3336 | printFaultMaps(Obj: O); |
3337 | if (Offloading) |
3338 | dumpOffloadBinary(O: *O); |
3339 | } |
3340 | |
3341 | static void dumpObject(const COFFImportFile *I, const Archive *A, |
3342 | const Archive::Child *C = nullptr) { |
3343 | StringRef ArchiveName = A ? A->getFileName() : "" ; |
3344 | |
3345 | // Avoid other output when using a raw option. |
3346 | if (!RawClangAST) |
3347 | outs() << '\n' |
3348 | << ArchiveName << "(" << I->getFileName() << ")" |
3349 | << ":\tfile format COFF-import-file" |
3350 | << "\n\n" ; |
3351 | |
3352 | if (ArchiveHeaders && !MachOOpt && C) |
3353 | printArchiveChild(Filename: ArchiveName, C: *C); |
3354 | if (SymbolTable) |
3355 | printCOFFSymbolTable(I: *I); |
3356 | } |
3357 | |
3358 | /// Dump each object file in \a a; |
3359 | static void dumpArchive(const Archive *A) { |
3360 | Error Err = Error::success(); |
3361 | unsigned I = -1; |
3362 | for (auto &C : A->children(Err)) { |
3363 | ++I; |
3364 | Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary(); |
3365 | if (!ChildOrErr) { |
3366 | if (auto E = isNotObjectErrorInvalidFileType(Err: ChildOrErr.takeError())) |
3367 | reportError(E: std::move(E), FileName: getFileNameForError(C, Index: I), ArchiveName: A->getFileName()); |
3368 | continue; |
3369 | } |
3370 | if (ObjectFile *O = dyn_cast<ObjectFile>(Val: &*ChildOrErr.get())) |
3371 | dumpObject(O, A, C: &C); |
3372 | else if (COFFImportFile *I = dyn_cast<COFFImportFile>(Val: &*ChildOrErr.get())) |
3373 | dumpObject(I, A, C: &C); |
3374 | else |
3375 | reportError(E: errorCodeToError(EC: object_error::invalid_file_type), |
3376 | FileName: A->getFileName()); |
3377 | } |
3378 | if (Err) |
3379 | reportError(E: std::move(Err), FileName: A->getFileName()); |
3380 | } |
3381 | |
3382 | /// Open file and figure out how to dump it. |
3383 | static void dumpInput(StringRef file) { |
3384 | // If we are using the Mach-O specific object file parser, then let it parse |
3385 | // the file and process the command line options. So the -arch flags can |
3386 | // be used to select specific slices, etc. |
3387 | if (MachOOpt) { |
3388 | parseInputMachO(Filename: file); |
3389 | return; |
3390 | } |
3391 | |
3392 | // Attempt to open the binary. |
3393 | OwningBinary<Binary> OBinary = unwrapOrError(EO: createBinary(Path: file), Args&: file); |
3394 | Binary &Binary = *OBinary.getBinary(); |
3395 | |
3396 | if (Archive *A = dyn_cast<Archive>(Val: &Binary)) |
3397 | dumpArchive(A); |
3398 | else if (ObjectFile *O = dyn_cast<ObjectFile>(Val: &Binary)) |
3399 | dumpObject(O); |
3400 | else if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(Val: &Binary)) |
3401 | parseInputMachO(UB); |
3402 | else if (OffloadBinary *OB = dyn_cast<OffloadBinary>(Val: &Binary)) |
3403 | dumpOffloadSections(OB: *OB); |
3404 | else |
3405 | reportError(E: errorCodeToError(EC: object_error::invalid_file_type), FileName: file); |
3406 | } |
3407 | |
3408 | template <typename T> |
3409 | static void parseIntArg(const llvm::opt::InputArgList &InputArgs, int ID, |
3410 | T &Value) { |
3411 | if (const opt::Arg *A = InputArgs.getLastArg(Ids: ID)) { |
3412 | StringRef V(A->getValue()); |
3413 | if (!llvm::to_integer(V, Value, 0)) { |
3414 | reportCmdLineError(Message: A->getSpelling() + |
3415 | ": expected a non-negative integer, but got '" + V + |
3416 | "'" ); |
3417 | } |
3418 | } |
3419 | } |
3420 | |
3421 | static object::BuildID parseBuildIDArg(const opt::Arg *A) { |
3422 | StringRef V(A->getValue()); |
3423 | object::BuildID BID = parseBuildID(Str: V); |
3424 | if (BID.empty()) |
3425 | reportCmdLineError(Message: A->getSpelling() + ": expected a build ID, but got '" + |
3426 | V + "'" ); |
3427 | return BID; |
3428 | } |
3429 | |
3430 | void objdump::invalidArgValue(const opt::Arg *A) { |
3431 | reportCmdLineError(Message: "'" + StringRef(A->getValue()) + |
3432 | "' is not a valid value for '" + A->getSpelling() + "'" ); |
3433 | } |
3434 | |
3435 | static std::vector<std::string> |
3436 | commaSeparatedValues(const llvm::opt::InputArgList &InputArgs, int ID) { |
3437 | std::vector<std::string> Values; |
3438 | for (StringRef Value : InputArgs.getAllArgValues(Id: ID)) { |
3439 | llvm::SmallVector<StringRef, 2> SplitValues; |
3440 | llvm::SplitString(Source: Value, OutFragments&: SplitValues, Delimiters: "," ); |
3441 | for (StringRef SplitValue : SplitValues) |
3442 | Values.push_back(x: SplitValue.str()); |
3443 | } |
3444 | return Values; |
3445 | } |
3446 | |
3447 | static void parseOtoolOptions(const llvm::opt::InputArgList &InputArgs) { |
3448 | MachOOpt = true; |
3449 | FullLeadingAddr = true; |
3450 | PrintImmHex = true; |
3451 | |
3452 | ArchName = InputArgs.getLastArgValue(Id: OTOOL_arch).str(); |
3453 | LinkOptHints = InputArgs.hasArg(Ids: OTOOL_C); |
3454 | if (InputArgs.hasArg(Ids: OTOOL_d)) |
3455 | FilterSections.push_back(x: "__DATA,__data" ); |
3456 | DylibId = InputArgs.hasArg(Ids: OTOOL_D); |
3457 | UniversalHeaders = InputArgs.hasArg(Ids: OTOOL_f); |
3458 | DataInCode = InputArgs.hasArg(Ids: OTOOL_G); |
3459 | FirstPrivateHeader = InputArgs.hasArg(Ids: OTOOL_h); |
3460 | IndirectSymbols = InputArgs.hasArg(Ids: OTOOL_I); |
3461 | ShowRawInsn = InputArgs.hasArg(Ids: OTOOL_j); |
3462 | PrivateHeaders = InputArgs.hasArg(Ids: OTOOL_l); |
3463 | DylibsUsed = InputArgs.hasArg(Ids: OTOOL_L); |
3464 | MCPU = InputArgs.getLastArgValue(Id: OTOOL_mcpu_EQ).str(); |
3465 | ObjcMetaData = InputArgs.hasArg(Ids: OTOOL_o); |
3466 | DisSymName = InputArgs.getLastArgValue(Id: OTOOL_p).str(); |
3467 | InfoPlist = InputArgs.hasArg(Ids: OTOOL_P); |
3468 | Relocations = InputArgs.hasArg(Ids: OTOOL_r); |
3469 | if (const Arg *A = InputArgs.getLastArg(Ids: OTOOL_s)) { |
3470 | auto Filter = (A->getValue(N: 0) + StringRef("," ) + A->getValue(N: 1)).str(); |
3471 | FilterSections.push_back(x: Filter); |
3472 | } |
3473 | if (InputArgs.hasArg(Ids: OTOOL_t)) |
3474 | FilterSections.push_back(x: "__TEXT,__text" ); |
3475 | Verbose = InputArgs.hasArg(Ids: OTOOL_v) || InputArgs.hasArg(Ids: OTOOL_V) || |
3476 | InputArgs.hasArg(Ids: OTOOL_o); |
3477 | SymbolicOperands = InputArgs.hasArg(Ids: OTOOL_V); |
3478 | if (InputArgs.hasArg(Ids: OTOOL_x)) |
3479 | FilterSections.push_back(x: ",__text" ); |
3480 | LeadingAddr = LeadingHeaders = !InputArgs.hasArg(Ids: OTOOL_X); |
3481 | |
3482 | ChainedFixups = InputArgs.hasArg(Ids: OTOOL_chained_fixups); |
3483 | DyldInfo = InputArgs.hasArg(Ids: OTOOL_dyld_info); |
3484 | |
3485 | InputFilenames = InputArgs.getAllArgValues(Id: OTOOL_INPUT); |
3486 | if (InputFilenames.empty()) |
3487 | reportCmdLineError(Message: "no input file" ); |
3488 | |
3489 | for (const Arg *A : InputArgs) { |
3490 | const Option &O = A->getOption(); |
3491 | if (O.getGroup().isValid() && O.getGroup().getID() == OTOOL_grp_obsolete) { |
3492 | reportCmdLineWarning(Message: O.getPrefixedName() + |
3493 | " is obsolete and not implemented" ); |
3494 | } |
3495 | } |
3496 | } |
3497 | |
3498 | static void parseObjdumpOptions(const llvm::opt::InputArgList &InputArgs) { |
3499 | parseIntArg(InputArgs, ID: OBJDUMP_adjust_vma_EQ, Value&: AdjustVMA); |
3500 | AllHeaders = InputArgs.hasArg(Ids: OBJDUMP_all_headers); |
3501 | ArchName = InputArgs.getLastArgValue(Id: OBJDUMP_arch_name_EQ).str(); |
3502 | ArchiveHeaders = InputArgs.hasArg(Ids: OBJDUMP_archive_headers); |
3503 | Demangle = InputArgs.hasArg(Ids: OBJDUMP_demangle); |
3504 | Disassemble = InputArgs.hasArg(Ids: OBJDUMP_disassemble); |
3505 | DisassembleAll = InputArgs.hasArg(Ids: OBJDUMP_disassemble_all); |
3506 | SymbolDescription = InputArgs.hasArg(Ids: OBJDUMP_symbol_description); |
3507 | TracebackTable = InputArgs.hasArg(Ids: OBJDUMP_traceback_table); |
3508 | DisassembleSymbols = |
3509 | commaSeparatedValues(InputArgs, ID: OBJDUMP_disassemble_symbols_EQ); |
3510 | DisassembleZeroes = InputArgs.hasArg(Ids: OBJDUMP_disassemble_zeroes); |
3511 | if (const opt::Arg *A = InputArgs.getLastArg(Ids: OBJDUMP_dwarf_EQ)) { |
3512 | DwarfDumpType = StringSwitch<DIDumpType>(A->getValue()) |
3513 | .Case(S: "frames" , Value: DIDT_DebugFrame) |
3514 | .Default(Value: DIDT_Null); |
3515 | if (DwarfDumpType == DIDT_Null) |
3516 | invalidArgValue(A); |
3517 | } |
3518 | DynamicRelocations = InputArgs.hasArg(Ids: OBJDUMP_dynamic_reloc); |
3519 | FaultMapSection = InputArgs.hasArg(Ids: OBJDUMP_fault_map_section); |
3520 | Offloading = InputArgs.hasArg(Ids: OBJDUMP_offloading); |
3521 | FileHeaders = InputArgs.hasArg(Ids: OBJDUMP_file_headers); |
3522 | SectionContents = InputArgs.hasArg(Ids: OBJDUMP_full_contents); |
3523 | PrintLines = InputArgs.hasArg(Ids: OBJDUMP_line_numbers); |
3524 | InputFilenames = InputArgs.getAllArgValues(Id: OBJDUMP_INPUT); |
3525 | MachOOpt = InputArgs.hasArg(Ids: OBJDUMP_macho); |
3526 | MCPU = InputArgs.getLastArgValue(Id: OBJDUMP_mcpu_EQ).str(); |
3527 | MAttrs = commaSeparatedValues(InputArgs, ID: OBJDUMP_mattr_EQ); |
3528 | ShowRawInsn = !InputArgs.hasArg(Ids: OBJDUMP_no_show_raw_insn); |
3529 | LeadingAddr = !InputArgs.hasArg(Ids: OBJDUMP_no_leading_addr); |
3530 | RawClangAST = InputArgs.hasArg(Ids: OBJDUMP_raw_clang_ast); |
3531 | Relocations = InputArgs.hasArg(Ids: OBJDUMP_reloc); |
3532 | PrintImmHex = |
3533 | InputArgs.hasFlag(Pos: OBJDUMP_print_imm_hex, Neg: OBJDUMP_no_print_imm_hex, Default: true); |
3534 | PrivateHeaders = InputArgs.hasArg(Ids: OBJDUMP_private_headers); |
3535 | FilterSections = InputArgs.getAllArgValues(Id: OBJDUMP_section_EQ); |
3536 | SectionHeaders = InputArgs.hasArg(Ids: OBJDUMP_section_headers); |
3537 | ShowAllSymbols = InputArgs.hasArg(Ids: OBJDUMP_show_all_symbols); |
3538 | ShowLMA = InputArgs.hasArg(Ids: OBJDUMP_show_lma); |
3539 | PrintSource = InputArgs.hasArg(Ids: OBJDUMP_source); |
3540 | parseIntArg(InputArgs, ID: OBJDUMP_start_address_EQ, Value&: StartAddress); |
3541 | HasStartAddressFlag = InputArgs.hasArg(Ids: OBJDUMP_start_address_EQ); |
3542 | parseIntArg(InputArgs, ID: OBJDUMP_stop_address_EQ, Value&: StopAddress); |
3543 | HasStopAddressFlag = InputArgs.hasArg(Ids: OBJDUMP_stop_address_EQ); |
3544 | SymbolTable = InputArgs.hasArg(Ids: OBJDUMP_syms); |
3545 | SymbolizeOperands = InputArgs.hasArg(Ids: OBJDUMP_symbolize_operands); |
3546 | PrettyPGOAnalysisMap = InputArgs.hasArg(Ids: OBJDUMP_pretty_pgo_analysis_map); |
3547 | if (PrettyPGOAnalysisMap && !SymbolizeOperands) |
3548 | reportCmdLineWarning(Message: "--symbolize-operands must be enabled for " |
3549 | "--pretty-pgo-analysis-map to have an effect" ); |
3550 | DynamicSymbolTable = InputArgs.hasArg(Ids: OBJDUMP_dynamic_syms); |
3551 | TripleName = InputArgs.getLastArgValue(Id: OBJDUMP_triple_EQ).str(); |
3552 | UnwindInfo = InputArgs.hasArg(Ids: OBJDUMP_unwind_info); |
3553 | Wide = InputArgs.hasArg(Ids: OBJDUMP_wide); |
3554 | Prefix = InputArgs.getLastArgValue(Id: OBJDUMP_prefix).str(); |
3555 | parseIntArg(InputArgs, ID: OBJDUMP_prefix_strip, Value&: PrefixStrip); |
3556 | if (const opt::Arg *A = InputArgs.getLastArg(Ids: OBJDUMP_debug_vars_EQ)) { |
3557 | DbgVariables = StringSwitch<DebugVarsFormat>(A->getValue()) |
3558 | .Case(S: "ascii" , Value: DVASCII) |
3559 | .Case(S: "unicode" , Value: DVUnicode) |
3560 | .Default(Value: DVInvalid); |
3561 | if (DbgVariables == DVInvalid) |
3562 | invalidArgValue(A); |
3563 | } |
3564 | if (const opt::Arg *A = InputArgs.getLastArg(Ids: OBJDUMP_disassembler_color_EQ)) { |
3565 | DisassemblyColor = StringSwitch<ColorOutput>(A->getValue()) |
3566 | .Case(S: "on" , Value: ColorOutput::Enable) |
3567 | .Case(S: "off" , Value: ColorOutput::Disable) |
3568 | .Case(S: "terminal" , Value: ColorOutput::Auto) |
3569 | .Default(Value: ColorOutput::Invalid); |
3570 | if (DisassemblyColor == ColorOutput::Invalid) |
3571 | invalidArgValue(A); |
3572 | } |
3573 | |
3574 | parseIntArg(InputArgs, ID: OBJDUMP_debug_vars_indent_EQ, Value&: DbgIndent); |
3575 | |
3576 | parseMachOOptions(InputArgs); |
3577 | |
3578 | // Parse -M (--disassembler-options) and deprecated |
3579 | // --x86-asm-syntax={att,intel}. |
3580 | // |
3581 | // Note, for x86, the asm dialect (AssemblerDialect) is initialized when the |
3582 | // MCAsmInfo is constructed. MCInstPrinter::applyTargetSpecificCLOption is |
3583 | // called too late. For now we have to use the internal cl::opt option. |
3584 | const char *AsmSyntax = nullptr; |
3585 | for (const auto *A : InputArgs.filtered(Ids: OBJDUMP_disassembler_options_EQ, |
3586 | Ids: OBJDUMP_x86_asm_syntax_att, |
3587 | Ids: OBJDUMP_x86_asm_syntax_intel)) { |
3588 | switch (A->getOption().getID()) { |
3589 | case OBJDUMP_x86_asm_syntax_att: |
3590 | AsmSyntax = "--x86-asm-syntax=att" ; |
3591 | continue; |
3592 | case OBJDUMP_x86_asm_syntax_intel: |
3593 | AsmSyntax = "--x86-asm-syntax=intel" ; |
3594 | continue; |
3595 | } |
3596 | |
3597 | SmallVector<StringRef, 2> Values; |
3598 | llvm::SplitString(Source: A->getValue(), OutFragments&: Values, Delimiters: "," ); |
3599 | for (StringRef V : Values) { |
3600 | if (V == "att" ) |
3601 | AsmSyntax = "--x86-asm-syntax=att" ; |
3602 | else if (V == "intel" ) |
3603 | AsmSyntax = "--x86-asm-syntax=intel" ; |
3604 | else |
3605 | DisassemblerOptions.push_back(x: V.str()); |
3606 | } |
3607 | } |
3608 | SmallVector<const char *> Args = {"llvm-objdump" }; |
3609 | for (const opt::Arg *A : InputArgs.filtered(Ids: OBJDUMP_mllvm)) |
3610 | Args.push_back(Elt: A->getValue()); |
3611 | if (AsmSyntax) |
3612 | Args.push_back(Elt: AsmSyntax); |
3613 | if (Args.size() > 1) |
3614 | llvm::cl::ParseCommandLineOptions(argc: Args.size(), argv: Args.data()); |
3615 | |
3616 | // Look up any provided build IDs, then append them to the input filenames. |
3617 | for (const opt::Arg *A : InputArgs.filtered(Ids: OBJDUMP_build_id)) { |
3618 | object::BuildID BuildID = parseBuildIDArg(A); |
3619 | std::optional<std::string> Path = BIDFetcher->fetch(BuildID); |
3620 | if (!Path) { |
3621 | reportCmdLineError(Message: A->getSpelling() + ": could not find build ID '" + |
3622 | A->getValue() + "'" ); |
3623 | } |
3624 | InputFilenames.push_back(x: std::move(*Path)); |
3625 | } |
3626 | |
3627 | // objdump defaults to a.out if no filenames specified. |
3628 | if (InputFilenames.empty()) |
3629 | InputFilenames.push_back(x: "a.out" ); |
3630 | } |
3631 | |
3632 | int llvm_objdump_main(int argc, char **argv, const llvm::ToolContext &) { |
3633 | using namespace llvm; |
3634 | |
3635 | ToolName = argv[0]; |
3636 | std::unique_ptr<CommonOptTable> T; |
3637 | OptSpecifier Unknown, HelpFlag, HelpHiddenFlag, VersionFlag; |
3638 | |
3639 | StringRef Stem = sys::path::stem(path: ToolName); |
3640 | auto Is = [=](StringRef Tool) { |
3641 | // We need to recognize the following filenames: |
3642 | // |
3643 | // llvm-objdump -> objdump |
3644 | // llvm-otool-10.exe -> otool |
3645 | // powerpc64-unknown-freebsd13-objdump -> objdump |
3646 | auto I = Stem.rfind_insensitive(Str: Tool); |
3647 | return I != StringRef::npos && |
3648 | (I + Tool.size() == Stem.size() || !isAlnum(C: Stem[I + Tool.size()])); |
3649 | }; |
3650 | if (Is("otool" )) { |
3651 | T = std::make_unique<OtoolOptTable>(); |
3652 | Unknown = OTOOL_UNKNOWN; |
3653 | HelpFlag = OTOOL_help; |
3654 | HelpHiddenFlag = OTOOL_help_hidden; |
3655 | VersionFlag = OTOOL_version; |
3656 | } else { |
3657 | T = std::make_unique<ObjdumpOptTable>(); |
3658 | Unknown = OBJDUMP_UNKNOWN; |
3659 | HelpFlag = OBJDUMP_help; |
3660 | HelpHiddenFlag = OBJDUMP_help_hidden; |
3661 | VersionFlag = OBJDUMP_version; |
3662 | } |
3663 | |
3664 | BumpPtrAllocator A; |
3665 | StringSaver Saver(A); |
3666 | opt::InputArgList InputArgs = |
3667 | T->parseArgs(Argc: argc, Argv: argv, Unknown, Saver, |
3668 | ErrorFn: [&](StringRef Msg) { reportCmdLineError(Message: Msg); }); |
3669 | |
3670 | if (InputArgs.size() == 0 || InputArgs.hasArg(Ids: HelpFlag)) { |
3671 | T->printHelp(Argv0: ToolName); |
3672 | return 0; |
3673 | } |
3674 | if (InputArgs.hasArg(Ids: HelpHiddenFlag)) { |
3675 | T->printHelp(Argv0: ToolName, /*ShowHidden=*/true); |
3676 | return 0; |
3677 | } |
3678 | |
3679 | // Initialize targets and assembly printers/parsers. |
3680 | InitializeAllTargetInfos(); |
3681 | InitializeAllTargetMCs(); |
3682 | InitializeAllDisassemblers(); |
3683 | |
3684 | if (InputArgs.hasArg(Ids: VersionFlag)) { |
3685 | cl::PrintVersionMessage(); |
3686 | if (!Is("otool" )) { |
3687 | outs() << '\n'; |
3688 | TargetRegistry::printRegisteredTargetsForVersion(OS&: outs()); |
3689 | } |
3690 | return 0; |
3691 | } |
3692 | |
3693 | // Initialize debuginfod. |
3694 | const bool ShouldUseDebuginfodByDefault = |
3695 | InputArgs.hasArg(Ids: OBJDUMP_build_id) || canUseDebuginfod(); |
3696 | std::vector<std::string> DebugFileDirectories = |
3697 | InputArgs.getAllArgValues(Id: OBJDUMP_debug_file_directory); |
3698 | if (InputArgs.hasFlag(Pos: OBJDUMP_debuginfod, Neg: OBJDUMP_no_debuginfod, |
3699 | Default: ShouldUseDebuginfodByDefault)) { |
3700 | HTTPClient::initialize(); |
3701 | BIDFetcher = |
3702 | std::make_unique<DebuginfodFetcher>(args: std::move(DebugFileDirectories)); |
3703 | } else { |
3704 | BIDFetcher = |
3705 | std::make_unique<BuildIDFetcher>(args: std::move(DebugFileDirectories)); |
3706 | } |
3707 | |
3708 | if (Is("otool" )) |
3709 | parseOtoolOptions(InputArgs); |
3710 | else |
3711 | parseObjdumpOptions(InputArgs); |
3712 | |
3713 | if (StartAddress >= StopAddress) |
3714 | reportCmdLineError(Message: "start address should be less than stop address" ); |
3715 | |
3716 | // Removes trailing separators from prefix. |
3717 | while (!Prefix.empty() && sys::path::is_separator(value: Prefix.back())) |
3718 | Prefix.pop_back(); |
3719 | |
3720 | if (AllHeaders) |
3721 | ArchiveHeaders = FileHeaders = PrivateHeaders = Relocations = |
3722 | SectionHeaders = SymbolTable = true; |
3723 | |
3724 | if (DisassembleAll || PrintSource || PrintLines || TracebackTable || |
3725 | !DisassembleSymbols.empty()) |
3726 | Disassemble = true; |
3727 | |
3728 | if (!ArchiveHeaders && !Disassemble && DwarfDumpType == DIDT_Null && |
3729 | !DynamicRelocations && !FileHeaders && !PrivateHeaders && !RawClangAST && |
3730 | !Relocations && !SectionHeaders && !SectionContents && !SymbolTable && |
3731 | !DynamicSymbolTable && !UnwindInfo && !FaultMapSection && !Offloading && |
3732 | !(MachOOpt && |
3733 | (Bind || DataInCode || ChainedFixups || DyldInfo || DylibId || |
3734 | DylibsUsed || ExportsTrie || FirstPrivateHeader || |
3735 | FunctionStartsType != FunctionStartsMode::None || IndirectSymbols || |
3736 | InfoPlist || LazyBind || LinkOptHints || ObjcMetaData || Rebase || |
3737 | Rpaths || UniversalHeaders || WeakBind || !FilterSections.empty()))) { |
3738 | T->printHelp(Argv0: ToolName); |
3739 | return 2; |
3740 | } |
3741 | |
3742 | DisasmSymbolSet.insert(begin: DisassembleSymbols.begin(), end: DisassembleSymbols.end()); |
3743 | |
3744 | llvm::for_each(Range&: InputFilenames, F: dumpInput); |
3745 | |
3746 | warnOnNoMatchForSections(); |
3747 | |
3748 | return EXIT_SUCCESS; |
3749 | } |
3750 | |