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 | PGOBBEntry.Successors, PGOSS, |
230 | [&](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(AddrMap.BBRanges[I].BaseAddress, |
264 | FunctionAddr); |
265 | [[maybe_unused]] auto R = FunctionAddrToMap.try_emplace( |
266 | FunctionAddr, std::move(AddrMap), 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(BaseAddress); |
277 | if (S != RangeBaseAddrToFunctionAddr.end()) |
278 | FunctionAddr = S->second; |
279 | auto R = FunctionAddrToMap.find(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 | Msg: "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 | PrettyPrinter &selectPrettyPrinter(Triple const &Triple) { |
951 | switch(Triple.getArch()) { |
952 | default: |
953 | return PrettyPrinterInst; |
954 | case Triple::hexagon: |
955 | return HexagonPrettyPrinterInst; |
956 | case Triple::amdgcn: |
957 | return AMDGCNPrettyPrinterInst; |
958 | case Triple::bpfel: |
959 | case Triple::bpfeb: |
960 | return BPFPrettyPrinterInst; |
961 | case Triple::arm: |
962 | case Triple::armeb: |
963 | case Triple::thumb: |
964 | case Triple::thumbeb: |
965 | return ARMPrettyPrinterInst; |
966 | case Triple::aarch64: |
967 | case Triple::aarch64_be: |
968 | case Triple::aarch64_32: |
969 | return AArch64PrettyPrinterInst; |
970 | } |
971 | } |
972 | |
973 | class DisassemblerTarget { |
974 | public: |
975 | const Target *TheTarget; |
976 | std::unique_ptr<const MCSubtargetInfo> SubtargetInfo; |
977 | std::shared_ptr<MCContext> Context; |
978 | std::unique_ptr<MCDisassembler> DisAsm; |
979 | std::shared_ptr<MCInstrAnalysis> InstrAnalysis; |
980 | std::shared_ptr<MCInstPrinter> InstPrinter; |
981 | PrettyPrinter *Printer; |
982 | |
983 | DisassemblerTarget(const Target *TheTarget, ObjectFile &Obj, |
984 | StringRef TripleName, StringRef MCPU, |
985 | SubtargetFeatures &Features); |
986 | DisassemblerTarget(DisassemblerTarget &Other, SubtargetFeatures &Features); |
987 | |
988 | private: |
989 | MCTargetOptions Options; |
990 | std::shared_ptr<const MCRegisterInfo> RegisterInfo; |
991 | std::shared_ptr<const MCAsmInfo> AsmInfo; |
992 | std::shared_ptr<const MCInstrInfo> InstrInfo; |
993 | std::shared_ptr<MCObjectFileInfo> ObjectFileInfo; |
994 | }; |
995 | |
996 | DisassemblerTarget::DisassemblerTarget(const Target *TheTarget, ObjectFile &Obj, |
997 | StringRef TripleName, StringRef MCPU, |
998 | SubtargetFeatures &Features) |
999 | : TheTarget(TheTarget), |
1000 | Printer(&selectPrettyPrinter(Triple: Triple(TripleName))), |
1001 | RegisterInfo(TheTarget->createMCRegInfo(TT: TripleName)) { |
1002 | if (!RegisterInfo) |
1003 | reportError(File: Obj.getFileName(), Message: "no register info for target " + TripleName); |
1004 | |
1005 | // Set up disassembler. |
1006 | AsmInfo.reset(p: TheTarget->createMCAsmInfo(MRI: *RegisterInfo, TheTriple: TripleName, Options)); |
1007 | if (!AsmInfo) |
1008 | reportError(File: Obj.getFileName(), Message: "no assembly info for target " + TripleName); |
1009 | |
1010 | SubtargetInfo.reset( |
1011 | p: TheTarget->createMCSubtargetInfo(TheTriple: TripleName, CPU: MCPU, Features: Features.getString())); |
1012 | if (!SubtargetInfo) |
1013 | reportError(File: Obj.getFileName(), |
1014 | Message: "no subtarget info for target " + TripleName); |
1015 | InstrInfo.reset(p: TheTarget->createMCInstrInfo()); |
1016 | if (!InstrInfo) |
1017 | reportError(File: Obj.getFileName(), |
1018 | Message: "no instruction info for target " + TripleName); |
1019 | Context = |
1020 | std::make_shared<MCContext>(args: Triple(TripleName), args: AsmInfo.get(), |
1021 | args: RegisterInfo.get(), args: SubtargetInfo.get()); |
1022 | |
1023 | // FIXME: for now initialize MCObjectFileInfo with default values |
1024 | ObjectFileInfo.reset( |
1025 | p: TheTarget->createMCObjectFileInfo(Ctx&: *Context, /*PIC=*/false)); |
1026 | Context->setObjectFileInfo(ObjectFileInfo.get()); |
1027 | |
1028 | DisAsm.reset(p: TheTarget->createMCDisassembler(STI: *SubtargetInfo, Ctx&: *Context)); |
1029 | if (!DisAsm) |
1030 | reportError(File: Obj.getFileName(), Message: "no disassembler for target " + TripleName); |
1031 | |
1032 | if (auto *ELFObj = dyn_cast<ELFObjectFileBase>(Val: &Obj)) |
1033 | DisAsm->setABIVersion(ELFObj->getEIdentABIVersion()); |
1034 | |
1035 | InstrAnalysis.reset(p: TheTarget->createMCInstrAnalysis(Info: InstrInfo.get())); |
1036 | |
1037 | int AsmPrinterVariant = AsmInfo->getAssemblerDialect(); |
1038 | InstPrinter.reset(p: TheTarget->createMCInstPrinter(T: Triple(TripleName), |
1039 | SyntaxVariant: AsmPrinterVariant, MAI: *AsmInfo, |
1040 | MII: *InstrInfo, MRI: *RegisterInfo)); |
1041 | if (!InstPrinter) |
1042 | reportError(File: Obj.getFileName(), |
1043 | Message: "no instruction printer for target " + TripleName); |
1044 | InstPrinter->setPrintImmHex(PrintImmHex); |
1045 | InstPrinter->setPrintBranchImmAsAddress(true); |
1046 | InstPrinter->setSymbolizeOperands(SymbolizeOperands); |
1047 | InstPrinter->setMCInstrAnalysis(InstrAnalysis.get()); |
1048 | |
1049 | switch (DisassemblyColor) { |
1050 | case ColorOutput::Enable: |
1051 | InstPrinter->setUseColor(true); |
1052 | break; |
1053 | case ColorOutput::Auto: |
1054 | InstPrinter->setUseColor(outs().has_colors()); |
1055 | break; |
1056 | case ColorOutput::Disable: |
1057 | case ColorOutput::Invalid: |
1058 | InstPrinter->setUseColor(false); |
1059 | break; |
1060 | }; |
1061 | } |
1062 | |
1063 | DisassemblerTarget::DisassemblerTarget(DisassemblerTarget &Other, |
1064 | SubtargetFeatures &Features) |
1065 | : TheTarget(Other.TheTarget), |
1066 | SubtargetInfo(TheTarget->createMCSubtargetInfo(TheTriple: TripleName, CPU: MCPU, |
1067 | Features: Features.getString())), |
1068 | Context(Other.Context), |
1069 | DisAsm(TheTarget->createMCDisassembler(STI: *SubtargetInfo, Ctx&: *Context)), |
1070 | InstrAnalysis(Other.InstrAnalysis), InstPrinter(Other.InstPrinter), |
1071 | Printer(Other.Printer), RegisterInfo(Other.RegisterInfo), |
1072 | AsmInfo(Other.AsmInfo), InstrInfo(Other.InstrInfo), |
1073 | ObjectFileInfo(Other.ObjectFileInfo) {} |
1074 | } // namespace |
1075 | |
1076 | static uint8_t getElfSymbolType(const ObjectFile &Obj, const SymbolRef &Sym) { |
1077 | assert(Obj.isELF()); |
1078 | if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Val: &Obj)) |
1079 | return unwrapOrError(EO: Elf32LEObj->getSymbol(Sym: Sym.getRawDataRefImpl()), |
1080 | Args: Obj.getFileName()) |
1081 | ->getType(); |
1082 | if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Val: &Obj)) |
1083 | return unwrapOrError(EO: Elf64LEObj->getSymbol(Sym: Sym.getRawDataRefImpl()), |
1084 | Args: Obj.getFileName()) |
1085 | ->getType(); |
1086 | if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Val: &Obj)) |
1087 | return unwrapOrError(EO: Elf32BEObj->getSymbol(Sym: Sym.getRawDataRefImpl()), |
1088 | Args: Obj.getFileName()) |
1089 | ->getType(); |
1090 | if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Val: &Obj)) |
1091 | return unwrapOrError(EO: Elf64BEObj->getSymbol(Sym: Sym.getRawDataRefImpl()), |
1092 | Args: Obj.getFileName()) |
1093 | ->getType(); |
1094 | llvm_unreachable("Unsupported binary format" ); |
1095 | } |
1096 | |
1097 | template <class ELFT> |
1098 | static void |
1099 | addDynamicElfSymbols(const ELFObjectFile<ELFT> &Obj, |
1100 | std::map<SectionRef, SectionSymbolsTy> &AllSymbols) { |
1101 | for (auto Symbol : Obj.getDynamicSymbolIterators()) { |
1102 | uint8_t SymbolType = Symbol.getELFType(); |
1103 | if (SymbolType == ELF::STT_SECTION) |
1104 | continue; |
1105 | |
1106 | uint64_t Address = unwrapOrError(Symbol.getAddress(), Obj.getFileName()); |
1107 | // ELFSymbolRef::getAddress() returns size instead of value for common |
1108 | // symbols which is not desirable for disassembly output. Overriding. |
1109 | if (SymbolType == ELF::STT_COMMON) |
1110 | Address = unwrapOrError(Obj.getSymbol(Symbol.getRawDataRefImpl()), |
1111 | Obj.getFileName()) |
1112 | ->st_value; |
1113 | |
1114 | StringRef Name = unwrapOrError(Symbol.getName(), Obj.getFileName()); |
1115 | if (Name.empty()) |
1116 | continue; |
1117 | |
1118 | section_iterator SecI = |
1119 | unwrapOrError(Symbol.getSection(), Obj.getFileName()); |
1120 | if (SecI == Obj.section_end()) |
1121 | continue; |
1122 | |
1123 | AllSymbols[*SecI].emplace_back(args&: Address, args&: Name, args&: SymbolType); |
1124 | } |
1125 | } |
1126 | |
1127 | static void |
1128 | addDynamicElfSymbols(const ELFObjectFileBase &Obj, |
1129 | std::map<SectionRef, SectionSymbolsTy> &AllSymbols) { |
1130 | if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Val: &Obj)) |
1131 | addDynamicElfSymbols(Obj: *Elf32LEObj, AllSymbols); |
1132 | else if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Val: &Obj)) |
1133 | addDynamicElfSymbols(Obj: *Elf64LEObj, AllSymbols); |
1134 | else if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Val: &Obj)) |
1135 | addDynamicElfSymbols(Obj: *Elf32BEObj, AllSymbols); |
1136 | else if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Val: &Obj)) |
1137 | addDynamicElfSymbols(Obj: *Elf64BEObj, AllSymbols); |
1138 | else |
1139 | llvm_unreachable("Unsupported binary format" ); |
1140 | } |
1141 | |
1142 | static std::optional<SectionRef> getWasmCodeSection(const WasmObjectFile &Obj) { |
1143 | for (auto SecI : Obj.sections()) { |
1144 | const WasmSection &Section = Obj.getWasmSection(Section: SecI); |
1145 | if (Section.Type == wasm::WASM_SEC_CODE) |
1146 | return SecI; |
1147 | } |
1148 | return std::nullopt; |
1149 | } |
1150 | |
1151 | static void |
1152 | addMissingWasmCodeSymbols(const WasmObjectFile &Obj, |
1153 | std::map<SectionRef, SectionSymbolsTy> &AllSymbols) { |
1154 | std::optional<SectionRef> Section = getWasmCodeSection(Obj); |
1155 | if (!Section) |
1156 | return; |
1157 | SectionSymbolsTy &Symbols = AllSymbols[*Section]; |
1158 | |
1159 | std::set<uint64_t> SymbolAddresses; |
1160 | for (const auto &Sym : Symbols) |
1161 | SymbolAddresses.insert(x: Sym.Addr); |
1162 | |
1163 | for (const wasm::WasmFunction &Function : Obj.functions()) { |
1164 | // This adjustment mirrors the one in WasmObjectFile::getSymbolAddress. |
1165 | uint32_t Adjustment = Obj.isRelocatableObject() || Obj.isSharedObject() |
1166 | ? 0 |
1167 | : Section->getAddress(); |
1168 | uint64_t Address = Function.CodeSectionOffset + Adjustment; |
1169 | // Only add fallback symbols for functions not already present in the symbol |
1170 | // table. |
1171 | if (SymbolAddresses.count(x: Address)) |
1172 | continue; |
1173 | // This function has no symbol, so it should have no SymbolName. |
1174 | assert(Function.SymbolName.empty()); |
1175 | // We use DebugName for the name, though it may be empty if there is no |
1176 | // "name" custom section, or that section is missing a name for this |
1177 | // function. |
1178 | StringRef Name = Function.DebugName; |
1179 | Symbols.emplace_back(args&: Address, args&: Name, args: ELF::STT_NOTYPE); |
1180 | } |
1181 | } |
1182 | |
1183 | static void addPltEntries(const ObjectFile &Obj, |
1184 | std::map<SectionRef, SectionSymbolsTy> &AllSymbols, |
1185 | StringSaver &Saver) { |
1186 | auto *ElfObj = dyn_cast<ELFObjectFileBase>(Val: &Obj); |
1187 | if (!ElfObj) |
1188 | return; |
1189 | DenseMap<StringRef, SectionRef> Sections; |
1190 | for (SectionRef Section : Obj.sections()) { |
1191 | Expected<StringRef> SecNameOrErr = Section.getName(); |
1192 | if (!SecNameOrErr) { |
1193 | consumeError(Err: SecNameOrErr.takeError()); |
1194 | continue; |
1195 | } |
1196 | Sections[*SecNameOrErr] = Section; |
1197 | } |
1198 | for (auto Plt : ElfObj->getPltEntries()) { |
1199 | if (Plt.Symbol) { |
1200 | SymbolRef Symbol(*Plt.Symbol, ElfObj); |
1201 | uint8_t SymbolType = getElfSymbolType(Obj, Sym: Symbol); |
1202 | if (Expected<StringRef> NameOrErr = Symbol.getName()) { |
1203 | if (!NameOrErr->empty()) |
1204 | AllSymbols[Sections[Plt.Section]].emplace_back( |
1205 | args&: Plt.Address, args: Saver.save(S: (*NameOrErr + "@plt" ).str()), args&: SymbolType); |
1206 | continue; |
1207 | } else { |
1208 | // The warning has been reported in disassembleObject(). |
1209 | consumeError(Err: NameOrErr.takeError()); |
1210 | } |
1211 | } |
1212 | reportWarning(Message: "PLT entry at 0x" + Twine::utohexstr(Val: Plt.Address) + |
1213 | " references an invalid symbol" , |
1214 | File: Obj.getFileName()); |
1215 | } |
1216 | } |
1217 | |
1218 | // Normally the disassembly output will skip blocks of zeroes. This function |
1219 | // returns the number of zero bytes that can be skipped when dumping the |
1220 | // disassembly of the instructions in Buf. |
1221 | static size_t countSkippableZeroBytes(ArrayRef<uint8_t> Buf) { |
1222 | // Find the number of leading zeroes. |
1223 | size_t N = 0; |
1224 | while (N < Buf.size() && !Buf[N]) |
1225 | ++N; |
1226 | |
1227 | // We may want to skip blocks of zero bytes, but unless we see |
1228 | // at least 8 of them in a row. |
1229 | if (N < 8) |
1230 | return 0; |
1231 | |
1232 | // We skip zeroes in multiples of 4 because do not want to truncate an |
1233 | // instruction if it starts with a zero byte. |
1234 | return N & ~0x3; |
1235 | } |
1236 | |
1237 | // Returns a map from sections to their relocations. |
1238 | static std::map<SectionRef, std::vector<RelocationRef>> |
1239 | getRelocsMap(object::ObjectFile const &Obj) { |
1240 | std::map<SectionRef, std::vector<RelocationRef>> Ret; |
1241 | uint64_t I = (uint64_t)-1; |
1242 | for (SectionRef Sec : Obj.sections()) { |
1243 | ++I; |
1244 | Expected<section_iterator> RelocatedOrErr = Sec.getRelocatedSection(); |
1245 | if (!RelocatedOrErr) |
1246 | reportError(File: Obj.getFileName(), |
1247 | Message: "section (" + Twine(I) + |
1248 | "): failed to get a relocated section: " + |
1249 | toString(E: RelocatedOrErr.takeError())); |
1250 | |
1251 | section_iterator Relocated = *RelocatedOrErr; |
1252 | if (Relocated == Obj.section_end() || !checkSectionFilter(S: *Relocated).Keep) |
1253 | continue; |
1254 | std::vector<RelocationRef> &V = Ret[*Relocated]; |
1255 | append_range(C&: V, R: Sec.relocations()); |
1256 | // Sort relocations by address. |
1257 | llvm::stable_sort(Range&: V, C: isRelocAddressLess); |
1258 | } |
1259 | return Ret; |
1260 | } |
1261 | |
1262 | // Used for --adjust-vma to check if address should be adjusted by the |
1263 | // specified value for a given section. |
1264 | // For ELF we do not adjust non-allocatable sections like debug ones, |
1265 | // because they are not loadable. |
1266 | // TODO: implement for other file formats. |
1267 | static bool shouldAdjustVA(const SectionRef &Section) { |
1268 | const ObjectFile *Obj = Section.getObject(); |
1269 | if (Obj->isELF()) |
1270 | return ELFSectionRef(Section).getFlags() & ELF::SHF_ALLOC; |
1271 | return false; |
1272 | } |
1273 | |
1274 | |
1275 | typedef std::pair<uint64_t, char> MappingSymbolPair; |
1276 | static char getMappingSymbolKind(ArrayRef<MappingSymbolPair> MappingSymbols, |
1277 | uint64_t Address) { |
1278 | auto It = |
1279 | partition_point(Range&: MappingSymbols, P: [Address](const MappingSymbolPair &Val) { |
1280 | return Val.first <= Address; |
1281 | }); |
1282 | // Return zero for any address before the first mapping symbol; this means |
1283 | // we should use the default disassembly mode, depending on the target. |
1284 | if (It == MappingSymbols.begin()) |
1285 | return '\x00'; |
1286 | return (It - 1)->second; |
1287 | } |
1288 | |
1289 | static uint64_t dumpARMELFData(uint64_t SectionAddr, uint64_t Index, |
1290 | uint64_t End, const ObjectFile &Obj, |
1291 | ArrayRef<uint8_t> Bytes, |
1292 | ArrayRef<MappingSymbolPair> MappingSymbols, |
1293 | const MCSubtargetInfo &STI, raw_ostream &OS) { |
1294 | llvm::endianness Endian = |
1295 | Obj.isLittleEndian() ? llvm::endianness::little : llvm::endianness::big; |
1296 | size_t Start = OS.tell(); |
1297 | OS << format(Fmt: "%8" PRIx64 ": " , Vals: SectionAddr + Index); |
1298 | if (Index + 4 <= End) { |
1299 | dumpBytes(Bytes: Bytes.slice(N: Index, M: 4), OS); |
1300 | AlignToInstStartColumn(Start, STI, OS); |
1301 | OS << "\t.word\t" |
1302 | << format_hex(N: support::endian::read32(P: Bytes.data() + Index, E: Endian), |
1303 | Width: 10); |
1304 | return 4; |
1305 | } |
1306 | if (Index + 2 <= End) { |
1307 | dumpBytes(Bytes: Bytes.slice(N: Index, M: 2), OS); |
1308 | AlignToInstStartColumn(Start, STI, OS); |
1309 | OS << "\t.short\t" |
1310 | << format_hex(N: support::endian::read16(P: Bytes.data() + Index, E: Endian), Width: 6); |
1311 | return 2; |
1312 | } |
1313 | dumpBytes(Bytes: Bytes.slice(N: Index, M: 1), OS); |
1314 | AlignToInstStartColumn(Start, STI, OS); |
1315 | OS << "\t.byte\t" << format_hex(N: Bytes[Index], Width: 4); |
1316 | return 1; |
1317 | } |
1318 | |
1319 | static void dumpELFData(uint64_t SectionAddr, uint64_t Index, uint64_t End, |
1320 | ArrayRef<uint8_t> Bytes) { |
1321 | // print out data up to 8 bytes at a time in hex and ascii |
1322 | uint8_t AsciiData[9] = {'\0'}; |
1323 | uint8_t Byte; |
1324 | int NumBytes = 0; |
1325 | |
1326 | for (; Index < End; ++Index) { |
1327 | if (NumBytes == 0) |
1328 | outs() << format(Fmt: "%8" PRIx64 ":" , Vals: SectionAddr + Index); |
1329 | Byte = Bytes.slice(N: Index)[0]; |
1330 | outs() << format(Fmt: " %02x" , Vals: Byte); |
1331 | AsciiData[NumBytes] = isPrint(C: Byte) ? Byte : '.'; |
1332 | |
1333 | uint8_t IndentOffset = 0; |
1334 | NumBytes++; |
1335 | if (Index == End - 1 || NumBytes > 8) { |
1336 | // Indent the space for less than 8 bytes data. |
1337 | // 2 spaces for byte and one for space between bytes |
1338 | IndentOffset = 3 * (8 - NumBytes); |
1339 | for (int Excess = NumBytes; Excess < 8; Excess++) |
1340 | AsciiData[Excess] = '\0'; |
1341 | NumBytes = 8; |
1342 | } |
1343 | if (NumBytes == 8) { |
1344 | AsciiData[8] = '\0'; |
1345 | outs() << std::string(IndentOffset, ' ') << " " ; |
1346 | outs() << reinterpret_cast<char *>(AsciiData); |
1347 | outs() << '\n'; |
1348 | NumBytes = 0; |
1349 | } |
1350 | } |
1351 | } |
1352 | |
1353 | SymbolInfoTy objdump::createSymbolInfo(const ObjectFile &Obj, |
1354 | const SymbolRef &Symbol, |
1355 | bool IsMappingSymbol) { |
1356 | const StringRef FileName = Obj.getFileName(); |
1357 | const uint64_t Addr = unwrapOrError(EO: Symbol.getAddress(), Args: FileName); |
1358 | const StringRef Name = unwrapOrError(EO: Symbol.getName(), Args: FileName); |
1359 | |
1360 | if (Obj.isXCOFF() && (SymbolDescription || TracebackTable)) { |
1361 | const auto &XCOFFObj = cast<XCOFFObjectFile>(Val: Obj); |
1362 | DataRefImpl SymbolDRI = Symbol.getRawDataRefImpl(); |
1363 | |
1364 | const uint32_t SymbolIndex = XCOFFObj.getSymbolIndex(SymEntPtr: SymbolDRI.p); |
1365 | std::optional<XCOFF::StorageMappingClass> Smc = |
1366 | getXCOFFSymbolCsectSMC(Obj: XCOFFObj, Sym: Symbol); |
1367 | return SymbolInfoTy(Smc, Addr, Name, SymbolIndex, |
1368 | isLabel(Obj: XCOFFObj, Sym: Symbol)); |
1369 | } else if (Obj.isXCOFF()) { |
1370 | const SymbolRef::Type SymType = unwrapOrError(EO: Symbol.getType(), Args: FileName); |
1371 | return SymbolInfoTy(Addr, Name, SymType, /*IsMappingSymbol=*/false, |
1372 | /*IsXCOFF=*/true); |
1373 | } else if (Obj.isWasm()) { |
1374 | uint8_t SymType = |
1375 | cast<WasmObjectFile>(Val: &Obj)->getWasmSymbol(Symbol).Info.Kind; |
1376 | return SymbolInfoTy(Addr, Name, SymType, false); |
1377 | } else { |
1378 | uint8_t Type = |
1379 | Obj.isELF() ? getElfSymbolType(Obj, Sym: Symbol) : (uint8_t)ELF::STT_NOTYPE; |
1380 | return SymbolInfoTy(Addr, Name, Type, IsMappingSymbol); |
1381 | } |
1382 | } |
1383 | |
1384 | static SymbolInfoTy createDummySymbolInfo(const ObjectFile &Obj, |
1385 | const uint64_t Addr, StringRef &Name, |
1386 | uint8_t Type) { |
1387 | if (Obj.isXCOFF() && (SymbolDescription || TracebackTable)) |
1388 | return SymbolInfoTy(std::nullopt, Addr, Name, std::nullopt, false); |
1389 | if (Obj.isWasm()) |
1390 | return SymbolInfoTy(Addr, Name, wasm::WASM_SYMBOL_TYPE_SECTION); |
1391 | return SymbolInfoTy(Addr, Name, Type); |
1392 | } |
1393 | |
1394 | static void collectBBAddrMapLabels( |
1395 | const BBAddrMapInfo &FullAddrMap, uint64_t SectionAddr, uint64_t Start, |
1396 | uint64_t End, |
1397 | std::unordered_map<uint64_t, std::vector<BBAddrMapLabel>> &Labels) { |
1398 | if (FullAddrMap.empty()) |
1399 | return; |
1400 | Labels.clear(); |
1401 | uint64_t StartAddress = SectionAddr + Start; |
1402 | uint64_t EndAddress = SectionAddr + End; |
1403 | const BBAddrMapFunctionEntry *FunctionMap = |
1404 | FullAddrMap.getEntryForAddress(BaseAddress: StartAddress); |
1405 | if (!FunctionMap) |
1406 | return; |
1407 | std::optional<size_t> BBRangeIndex = |
1408 | FunctionMap->getAddrMap().getBBRangeIndexForBaseAddress(BaseAddress: StartAddress); |
1409 | if (!BBRangeIndex) |
1410 | return; |
1411 | size_t NumBBEntriesBeforeRange = 0; |
1412 | for (size_t I = 0; I < *BBRangeIndex; ++I) |
1413 | NumBBEntriesBeforeRange += |
1414 | FunctionMap->getAddrMap().BBRanges[I].BBEntries.size(); |
1415 | const auto &BBRange = FunctionMap->getAddrMap().BBRanges[*BBRangeIndex]; |
1416 | for (size_t I = 0; I < BBRange.BBEntries.size(); ++I) { |
1417 | const BBAddrMap::BBEntry &BBEntry = BBRange.BBEntries[I]; |
1418 | uint64_t BBAddress = BBEntry.Offset + BBRange.BaseAddress; |
1419 | if (BBAddress >= EndAddress) |
1420 | continue; |
1421 | |
1422 | std::string LabelString = ("BB" + Twine(BBEntry.ID)).str(); |
1423 | Labels[BBAddress].push_back( |
1424 | x: {.BlockLabel: LabelString, .PGOAnalysis: FunctionMap->constructPGOLabelString( |
1425 | PGOBBEntryIndex: NumBBEntriesBeforeRange + I, PrettyPGOAnalysis: PrettyPGOAnalysisMap)}); |
1426 | } |
1427 | } |
1428 | |
1429 | static void |
1430 | collectLocalBranchTargets(ArrayRef<uint8_t> Bytes, MCInstrAnalysis *MIA, |
1431 | MCDisassembler *DisAsm, MCInstPrinter *IP, |
1432 | const MCSubtargetInfo *STI, uint64_t SectionAddr, |
1433 | uint64_t Start, uint64_t End, |
1434 | std::unordered_map<uint64_t, std::string> &Labels) { |
1435 | // So far only supports PowerPC and X86. |
1436 | const bool isPPC = STI->getTargetTriple().isPPC(); |
1437 | if (!isPPC && !STI->getTargetTriple().isX86()) |
1438 | return; |
1439 | |
1440 | if (MIA) |
1441 | MIA->resetState(); |
1442 | |
1443 | Labels.clear(); |
1444 | unsigned LabelCount = 0; |
1445 | Start += SectionAddr; |
1446 | End += SectionAddr; |
1447 | const bool isXCOFF = STI->getTargetTriple().isOSBinFormatXCOFF(); |
1448 | for (uint64_t Index = Start; Index < End;) { |
1449 | // Disassemble a real instruction and record function-local branch labels. |
1450 | MCInst Inst; |
1451 | uint64_t Size; |
1452 | ArrayRef<uint8_t> ThisBytes = Bytes.slice(N: Index - SectionAddr); |
1453 | bool Disassembled = |
1454 | DisAsm->getInstruction(Instr&: Inst, Size, Bytes: ThisBytes, Address: Index, CStream&: nulls()); |
1455 | if (Size == 0) |
1456 | Size = std::min<uint64_t>(a: ThisBytes.size(), |
1457 | b: DisAsm->suggestBytesToSkip(Bytes: ThisBytes, Address: Index)); |
1458 | |
1459 | if (MIA) { |
1460 | if (Disassembled) { |
1461 | uint64_t Target; |
1462 | bool TargetKnown = MIA->evaluateBranch(Inst, Addr: Index, Size, Target); |
1463 | if (TargetKnown && (Target >= Start && Target < End) && |
1464 | !Labels.count(x: Target)) { |
1465 | // On PowerPC and AIX, a function call is encoded as a branch to 0. |
1466 | // On other PowerPC platforms (ELF), a function call is encoded as |
1467 | // a branch to self. Do not add a label for these cases. |
1468 | if (!(isPPC && |
1469 | ((Target == 0 && isXCOFF) || (Target == Index && !isXCOFF)))) |
1470 | Labels[Target] = ("L" + Twine(LabelCount++)).str(); |
1471 | } |
1472 | MIA->updateState(Inst, Addr: Index); |
1473 | } else |
1474 | MIA->resetState(); |
1475 | } |
1476 | Index += Size; |
1477 | } |
1478 | } |
1479 | |
1480 | // Create an MCSymbolizer for the target and add it to the MCDisassembler. |
1481 | // This is currently only used on AMDGPU, and assumes the format of the |
1482 | // void * argument passed to AMDGPU's createMCSymbolizer. |
1483 | static void addSymbolizer( |
1484 | MCContext &Ctx, const Target *Target, StringRef TripleName, |
1485 | MCDisassembler *DisAsm, uint64_t SectionAddr, ArrayRef<uint8_t> Bytes, |
1486 | SectionSymbolsTy &Symbols, |
1487 | std::vector<std::unique_ptr<std::string>> &SynthesizedLabelNames) { |
1488 | |
1489 | std::unique_ptr<MCRelocationInfo> RelInfo( |
1490 | Target->createMCRelocationInfo(TT: TripleName, Ctx)); |
1491 | if (!RelInfo) |
1492 | return; |
1493 | std::unique_ptr<MCSymbolizer> Symbolizer(Target->createMCSymbolizer( |
1494 | TT: TripleName, GetOpInfo: nullptr, SymbolLookUp: nullptr, DisInfo: &Symbols, Ctx: &Ctx, RelInfo: std::move(RelInfo))); |
1495 | MCSymbolizer *SymbolizerPtr = &*Symbolizer; |
1496 | DisAsm->setSymbolizer(std::move(Symbolizer)); |
1497 | |
1498 | if (!SymbolizeOperands) |
1499 | return; |
1500 | |
1501 | // Synthesize labels referenced by branch instructions by |
1502 | // disassembling, discarding the output, and collecting the referenced |
1503 | // addresses from the symbolizer. |
1504 | for (size_t Index = 0; Index != Bytes.size();) { |
1505 | MCInst Inst; |
1506 | uint64_t Size; |
1507 | ArrayRef<uint8_t> ThisBytes = Bytes.slice(N: Index); |
1508 | const uint64_t ThisAddr = SectionAddr + Index; |
1509 | DisAsm->getInstruction(Instr&: Inst, Size, Bytes: ThisBytes, Address: ThisAddr, CStream&: nulls()); |
1510 | if (Size == 0) |
1511 | Size = std::min<uint64_t>(a: ThisBytes.size(), |
1512 | b: DisAsm->suggestBytesToSkip(Bytes: ThisBytes, Address: Index)); |
1513 | Index += Size; |
1514 | } |
1515 | ArrayRef<uint64_t> LabelAddrsRef = SymbolizerPtr->getReferencedAddresses(); |
1516 | // Copy and sort to remove duplicates. |
1517 | std::vector<uint64_t> LabelAddrs; |
1518 | LabelAddrs.insert(position: LabelAddrs.end(), first: LabelAddrsRef.begin(), |
1519 | last: LabelAddrsRef.end()); |
1520 | llvm::sort(C&: LabelAddrs); |
1521 | LabelAddrs.resize(new_size: std::unique(first: LabelAddrs.begin(), last: LabelAddrs.end()) - |
1522 | LabelAddrs.begin()); |
1523 | // Add the labels. |
1524 | for (unsigned LabelNum = 0; LabelNum != LabelAddrs.size(); ++LabelNum) { |
1525 | auto Name = std::make_unique<std::string>(); |
1526 | *Name = (Twine("L" ) + Twine(LabelNum)).str(); |
1527 | SynthesizedLabelNames.push_back(x: std::move(Name)); |
1528 | Symbols.push_back(x: SymbolInfoTy( |
1529 | LabelAddrs[LabelNum], *SynthesizedLabelNames.back(), ELF::STT_NOTYPE)); |
1530 | } |
1531 | llvm::stable_sort(Range&: Symbols); |
1532 | // Recreate the symbolizer with the new symbols list. |
1533 | RelInfo.reset(p: Target->createMCRelocationInfo(TT: TripleName, Ctx)); |
1534 | Symbolizer.reset(p: Target->createMCSymbolizer( |
1535 | TT: TripleName, GetOpInfo: nullptr, SymbolLookUp: nullptr, DisInfo: &Symbols, Ctx: &Ctx, RelInfo: std::move(RelInfo))); |
1536 | DisAsm->setSymbolizer(std::move(Symbolizer)); |
1537 | } |
1538 | |
1539 | static StringRef getSegmentName(const MachOObjectFile *MachO, |
1540 | const SectionRef &Section) { |
1541 | if (MachO) { |
1542 | DataRefImpl DR = Section.getRawDataRefImpl(); |
1543 | StringRef SegmentName = MachO->getSectionFinalSegmentName(Sec: DR); |
1544 | return SegmentName; |
1545 | } |
1546 | return "" ; |
1547 | } |
1548 | |
1549 | static void emitPostInstructionInfo(formatted_raw_ostream &FOS, |
1550 | const MCAsmInfo &MAI, |
1551 | const MCSubtargetInfo &STI, |
1552 | StringRef , |
1553 | LiveVariablePrinter &LVP) { |
1554 | do { |
1555 | if (!Comments.empty()) { |
1556 | // Emit a line of comments. |
1557 | StringRef ; |
1558 | std::tie(args&: Comment, args&: Comments) = Comments.split(Separator: '\n'); |
1559 | // MAI.getCommentColumn() assumes that instructions are printed at the |
1560 | // position of 8, while getInstStartColumn() returns the actual position. |
1561 | unsigned CommentColumn = |
1562 | MAI.getCommentColumn() - 8 + getInstStartColumn(STI); |
1563 | FOS.PadToColumn(NewCol: CommentColumn); |
1564 | FOS << MAI.getCommentString() << ' ' << Comment; |
1565 | } |
1566 | LVP.printAfterInst(OS&: FOS); |
1567 | FOS << '\n'; |
1568 | } while (!Comments.empty()); |
1569 | FOS.flush(); |
1570 | } |
1571 | |
1572 | static void createFakeELFSections(ObjectFile &Obj) { |
1573 | assert(Obj.isELF()); |
1574 | if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Val: &Obj)) |
1575 | Elf32LEObj->createFakeSections(); |
1576 | else if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Val: &Obj)) |
1577 | Elf64LEObj->createFakeSections(); |
1578 | else if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Val: &Obj)) |
1579 | Elf32BEObj->createFakeSections(); |
1580 | else if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Val: &Obj)) |
1581 | Elf64BEObj->createFakeSections(); |
1582 | else |
1583 | llvm_unreachable("Unsupported binary format" ); |
1584 | } |
1585 | |
1586 | // Tries to fetch a more complete version of the given object file using its |
1587 | // Build ID. Returns std::nullopt if nothing was found. |
1588 | static std::optional<OwningBinary<Binary>> |
1589 | fetchBinaryByBuildID(const ObjectFile &Obj) { |
1590 | object::BuildIDRef BuildID = getBuildID(Obj: &Obj); |
1591 | if (BuildID.empty()) |
1592 | return std::nullopt; |
1593 | std::optional<std::string> Path = BIDFetcher->fetch(BuildID); |
1594 | if (!Path) |
1595 | return std::nullopt; |
1596 | Expected<OwningBinary<Binary>> DebugBinary = createBinary(Path: *Path); |
1597 | if (!DebugBinary) { |
1598 | reportWarning(Message: toString(E: DebugBinary.takeError()), File: *Path); |
1599 | return std::nullopt; |
1600 | } |
1601 | return std::move(*DebugBinary); |
1602 | } |
1603 | |
1604 | static void |
1605 | disassembleObject(ObjectFile &Obj, const ObjectFile &DbgObj, |
1606 | DisassemblerTarget &PrimaryTarget, |
1607 | std::optional<DisassemblerTarget> &SecondaryTarget, |
1608 | SourcePrinter &SP, bool InlineRelocs) { |
1609 | DisassemblerTarget *DT = &PrimaryTarget; |
1610 | bool PrimaryIsThumb = false; |
1611 | SmallVector<std::pair<uint64_t, uint64_t>, 0> CHPECodeMap; |
1612 | |
1613 | if (SecondaryTarget) { |
1614 | if (isArmElf(Obj)) { |
1615 | PrimaryIsThumb = |
1616 | PrimaryTarget.SubtargetInfo->checkFeatures(FS: "+thumb-mode" ); |
1617 | } else if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Val: &Obj)) { |
1618 | const chpe_metadata *CHPEMetadata = COFFObj->getCHPEMetadata(); |
1619 | if (CHPEMetadata && CHPEMetadata->CodeMapCount) { |
1620 | uintptr_t CodeMapInt; |
1621 | cantFail(Err: COFFObj->getRvaPtr(Rva: CHPEMetadata->CodeMap, Res&: CodeMapInt)); |
1622 | auto CodeMap = reinterpret_cast<const chpe_range_entry *>(CodeMapInt); |
1623 | |
1624 | for (uint32_t i = 0; i < CHPEMetadata->CodeMapCount; ++i) { |
1625 | if (CodeMap[i].getType() == chpe_range_type::Amd64 && |
1626 | CodeMap[i].Length) { |
1627 | // Store x86_64 CHPE code ranges. |
1628 | uint64_t Start = CodeMap[i].getStart() + COFFObj->getImageBase(); |
1629 | CHPECodeMap.emplace_back(Args&: Start, Args: Start + CodeMap[i].Length); |
1630 | } |
1631 | } |
1632 | llvm::sort(C&: CHPECodeMap); |
1633 | } |
1634 | } |
1635 | } |
1636 | |
1637 | std::map<SectionRef, std::vector<RelocationRef>> RelocMap; |
1638 | if (InlineRelocs || Obj.isXCOFF()) |
1639 | RelocMap = getRelocsMap(Obj); |
1640 | bool Is64Bits = Obj.getBytesInAddress() > 4; |
1641 | |
1642 | // Create a mapping from virtual address to symbol name. This is used to |
1643 | // pretty print the symbols while disassembling. |
1644 | std::map<SectionRef, SectionSymbolsTy> AllSymbols; |
1645 | std::map<SectionRef, SmallVector<MappingSymbolPair, 0>> AllMappingSymbols; |
1646 | SectionSymbolsTy AbsoluteSymbols; |
1647 | const StringRef FileName = Obj.getFileName(); |
1648 | const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Val: &Obj); |
1649 | for (const SymbolRef &Symbol : Obj.symbols()) { |
1650 | Expected<StringRef> NameOrErr = Symbol.getName(); |
1651 | if (!NameOrErr) { |
1652 | reportWarning(Message: toString(E: NameOrErr.takeError()), File: FileName); |
1653 | continue; |
1654 | } |
1655 | if (NameOrErr->empty() && !(Obj.isXCOFF() && SymbolDescription)) |
1656 | continue; |
1657 | |
1658 | if (Obj.isELF() && |
1659 | (cantFail(ValOrErr: Symbol.getFlags()) & SymbolRef::SF_FormatSpecific)) { |
1660 | // Symbol is intended not to be displayed by default (STT_FILE, |
1661 | // STT_SECTION, or a mapping symbol). Ignore STT_SECTION symbols. We will |
1662 | // synthesize a section symbol if no symbol is defined at offset 0. |
1663 | // |
1664 | // For a mapping symbol, store it within both AllSymbols and |
1665 | // AllMappingSymbols. If --show-all-symbols is unspecified, its label will |
1666 | // not be printed in disassembly listing. |
1667 | if (getElfSymbolType(Obj, Sym: Symbol) != ELF::STT_SECTION && |
1668 | hasMappingSymbols(Obj)) { |
1669 | section_iterator SecI = unwrapOrError(EO: Symbol.getSection(), Args: FileName); |
1670 | if (SecI != Obj.section_end()) { |
1671 | uint64_t SectionAddr = SecI->getAddress(); |
1672 | uint64_t Address = cantFail(ValOrErr: Symbol.getAddress()); |
1673 | StringRef Name = *NameOrErr; |
1674 | if (Name.consume_front(Prefix: "$" ) && Name.size() && |
1675 | strchr(s: "adtx" , c: Name[0])) { |
1676 | AllMappingSymbols[*SecI].emplace_back(Args: Address - SectionAddr, |
1677 | Args: Name[0]); |
1678 | AllSymbols[*SecI].push_back( |
1679 | x: createSymbolInfo(Obj, Symbol, /*MappingSymbol=*/IsMappingSymbol: true)); |
1680 | } |
1681 | } |
1682 | } |
1683 | continue; |
1684 | } |
1685 | |
1686 | if (MachO) { |
1687 | // __mh_(execute|dylib|dylinker|bundle|preload|object)_header are special |
1688 | // symbols that support MachO header introspection. They do not bind to |
1689 | // code locations and are irrelevant for disassembly. |
1690 | if (NameOrErr->starts_with(Prefix: "__mh_" ) && NameOrErr->ends_with(Suffix: "_header" )) |
1691 | continue; |
1692 | // Don't ask a Mach-O STAB symbol for its section unless you know that |
1693 | // STAB symbol's section field refers to a valid section index. Otherwise |
1694 | // the symbol may error trying to load a section that does not exist. |
1695 | DataRefImpl SymDRI = Symbol.getRawDataRefImpl(); |
1696 | uint8_t NType = (MachO->is64Bit() ? |
1697 | MachO->getSymbol64TableEntry(DRI: SymDRI).n_type: |
1698 | MachO->getSymbolTableEntry(DRI: SymDRI).n_type); |
1699 | if (NType & MachO::N_STAB) |
1700 | continue; |
1701 | } |
1702 | |
1703 | section_iterator SecI = unwrapOrError(EO: Symbol.getSection(), Args: FileName); |
1704 | if (SecI != Obj.section_end()) |
1705 | AllSymbols[*SecI].push_back(x: createSymbolInfo(Obj, Symbol)); |
1706 | else |
1707 | AbsoluteSymbols.push_back(x: createSymbolInfo(Obj, Symbol)); |
1708 | } |
1709 | |
1710 | if (AllSymbols.empty() && Obj.isELF()) |
1711 | addDynamicElfSymbols(Obj: cast<ELFObjectFileBase>(Val&: Obj), AllSymbols); |
1712 | |
1713 | if (Obj.isWasm()) |
1714 | addMissingWasmCodeSymbols(Obj: cast<WasmObjectFile>(Val&: Obj), AllSymbols); |
1715 | |
1716 | if (Obj.isELF() && Obj.sections().empty()) |
1717 | createFakeELFSections(Obj); |
1718 | |
1719 | BumpPtrAllocator A; |
1720 | StringSaver Saver(A); |
1721 | addPltEntries(Obj, AllSymbols, Saver); |
1722 | |
1723 | // Create a mapping from virtual address to section. An empty section can |
1724 | // cause more than one section at the same address. Sort such sections to be |
1725 | // before same-addressed non-empty sections so that symbol lookups prefer the |
1726 | // non-empty section. |
1727 | std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses; |
1728 | for (SectionRef Sec : Obj.sections()) |
1729 | SectionAddresses.emplace_back(args: Sec.getAddress(), args&: Sec); |
1730 | llvm::stable_sort(Range&: SectionAddresses, C: [](const auto &LHS, const auto &RHS) { |
1731 | if (LHS.first != RHS.first) |
1732 | return LHS.first < RHS.first; |
1733 | return LHS.second.getSize() < RHS.second.getSize(); |
1734 | }); |
1735 | |
1736 | // Linked executables (.exe and .dll files) typically don't include a real |
1737 | // symbol table but they might contain an export table. |
1738 | if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Val: &Obj)) { |
1739 | for (const auto &ExportEntry : COFFObj->export_directories()) { |
1740 | StringRef Name; |
1741 | if (Error E = ExportEntry.getSymbolName(Result&: Name)) |
1742 | reportError(E: std::move(E), FileName: Obj.getFileName()); |
1743 | if (Name.empty()) |
1744 | continue; |
1745 | |
1746 | uint32_t RVA; |
1747 | if (Error E = ExportEntry.getExportRVA(Result&: RVA)) |
1748 | reportError(E: std::move(E), FileName: Obj.getFileName()); |
1749 | |
1750 | uint64_t VA = COFFObj->getImageBase() + RVA; |
1751 | auto Sec = partition_point( |
1752 | Range&: SectionAddresses, P: [VA](const std::pair<uint64_t, SectionRef> &O) { |
1753 | return O.first <= VA; |
1754 | }); |
1755 | if (Sec != SectionAddresses.begin()) { |
1756 | --Sec; |
1757 | AllSymbols[Sec->second].emplace_back(args&: VA, args&: Name, args: ELF::STT_NOTYPE); |
1758 | } else |
1759 | AbsoluteSymbols.emplace_back(args&: VA, args&: Name, args: ELF::STT_NOTYPE); |
1760 | } |
1761 | } |
1762 | |
1763 | // Sort all the symbols, this allows us to use a simple binary search to find |
1764 | // Multiple symbols can have the same address. Use a stable sort to stabilize |
1765 | // the output. |
1766 | StringSet<> FoundDisasmSymbolSet; |
1767 | for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols) |
1768 | llvm::stable_sort(Range&: SecSyms.second); |
1769 | llvm::stable_sort(Range&: AbsoluteSymbols); |
1770 | |
1771 | std::unique_ptr<DWARFContext> DICtx; |
1772 | LiveVariablePrinter LVP(*DT->Context->getRegisterInfo(), *DT->SubtargetInfo); |
1773 | |
1774 | if (DbgVariables != DVDisabled) { |
1775 | DICtx = DWARFContext::create(Obj: DbgObj); |
1776 | for (const std::unique_ptr<DWARFUnit> &CU : DICtx->compile_units()) |
1777 | LVP.addCompileUnit(D: CU->getUnitDIE(ExtractUnitDIEOnly: false)); |
1778 | } |
1779 | |
1780 | LLVM_DEBUG(LVP.dump()); |
1781 | |
1782 | BBAddrMapInfo FullAddrMap; |
1783 | auto ReadBBAddrMap = [&](std::optional<unsigned> SectionIndex = |
1784 | std::nullopt) { |
1785 | FullAddrMap.clear(); |
1786 | if (const auto *Elf = dyn_cast<ELFObjectFileBase>(Val: &Obj)) { |
1787 | std::vector<PGOAnalysisMap> PGOAnalyses; |
1788 | auto BBAddrMapsOrErr = Elf->readBBAddrMap(TextSectionIndex: SectionIndex, PGOAnalyses: &PGOAnalyses); |
1789 | if (!BBAddrMapsOrErr) { |
1790 | reportWarning(Message: toString(E: BBAddrMapsOrErr.takeError()), File: Obj.getFileName()); |
1791 | return; |
1792 | } |
1793 | for (auto &&[FunctionBBAddrMap, FunctionPGOAnalysis] : |
1794 | zip_equal(t&: *std::move(BBAddrMapsOrErr), u: std::move(PGOAnalyses))) { |
1795 | FullAddrMap.AddFunctionEntry(AddrMap: std::move(FunctionBBAddrMap), |
1796 | PGOMap: std::move(FunctionPGOAnalysis)); |
1797 | } |
1798 | } |
1799 | }; |
1800 | |
1801 | // For non-relocatable objects, Read all LLVM_BB_ADDR_MAP sections into a |
1802 | // single mapping, since they don't have any conflicts. |
1803 | if (SymbolizeOperands && !Obj.isRelocatableObject()) |
1804 | ReadBBAddrMap(); |
1805 | |
1806 | std::optional<llvm::BTFParser> BTF; |
1807 | if (InlineRelocs && BTFParser::hasBTFSections(Obj)) { |
1808 | BTF.emplace(); |
1809 | BTFParser::ParseOptions Opts = {}; |
1810 | Opts.LoadTypes = true; |
1811 | Opts.LoadRelocs = true; |
1812 | if (Error E = BTF->parse(Obj, Opts)) |
1813 | WithColor::defaultErrorHandler(Err: std::move(E)); |
1814 | } |
1815 | |
1816 | for (const SectionRef &Section : ToolSectionFilter(O: Obj)) { |
1817 | if (FilterSections.empty() && !DisassembleAll && |
1818 | (!Section.isText() || Section.isVirtual())) |
1819 | continue; |
1820 | |
1821 | uint64_t SectionAddr = Section.getAddress(); |
1822 | uint64_t SectSize = Section.getSize(); |
1823 | if (!SectSize) |
1824 | continue; |
1825 | |
1826 | // For relocatable object files, read the LLVM_BB_ADDR_MAP section |
1827 | // corresponding to this section, if present. |
1828 | if (SymbolizeOperands && Obj.isRelocatableObject()) |
1829 | ReadBBAddrMap(Section.getIndex()); |
1830 | |
1831 | // Get the list of all the symbols in this section. |
1832 | SectionSymbolsTy &Symbols = AllSymbols[Section]; |
1833 | auto &MappingSymbols = AllMappingSymbols[Section]; |
1834 | llvm::sort(C&: MappingSymbols); |
1835 | |
1836 | ArrayRef<uint8_t> Bytes = arrayRefFromStringRef( |
1837 | Input: unwrapOrError(EO: Section.getContents(), Args: Obj.getFileName())); |
1838 | |
1839 | std::vector<std::unique_ptr<std::string>> SynthesizedLabelNames; |
1840 | if (Obj.isELF() && Obj.getArch() == Triple::amdgcn) { |
1841 | // AMDGPU disassembler uses symbolizer for printing labels |
1842 | addSymbolizer(Ctx&: *DT->Context, Target: DT->TheTarget, TripleName, DisAsm: DT->DisAsm.get(), |
1843 | SectionAddr, Bytes, Symbols, SynthesizedLabelNames); |
1844 | } |
1845 | |
1846 | StringRef SegmentName = getSegmentName(MachO, Section); |
1847 | StringRef SectionName = unwrapOrError(EO: Section.getName(), Args: Obj.getFileName()); |
1848 | // If the section has no symbol at the start, just insert a dummy one. |
1849 | // Without --show-all-symbols, also insert one if all symbols at the start |
1850 | // are mapping symbols. |
1851 | bool CreateDummy = Symbols.empty(); |
1852 | if (!CreateDummy) { |
1853 | CreateDummy = true; |
1854 | for (auto &Sym : Symbols) { |
1855 | if (Sym.Addr != SectionAddr) |
1856 | break; |
1857 | if (!Sym.IsMappingSymbol || ShowAllSymbols) |
1858 | CreateDummy = false; |
1859 | } |
1860 | } |
1861 | if (CreateDummy) { |
1862 | SymbolInfoTy Sym = createDummySymbolInfo( |
1863 | Obj, Addr: SectionAddr, Name&: SectionName, |
1864 | Type: Section.isText() ? ELF::STT_FUNC : ELF::STT_OBJECT); |
1865 | if (Obj.isXCOFF()) |
1866 | Symbols.insert(position: Symbols.begin(), x: Sym); |
1867 | else |
1868 | Symbols.insert(position: llvm::lower_bound(Range&: Symbols, Value&: Sym), x: Sym); |
1869 | } |
1870 | |
1871 | SmallString<40> ; |
1872 | raw_svector_ostream (Comments); |
1873 | |
1874 | uint64_t VMAAdjustment = 0; |
1875 | if (shouldAdjustVA(Section)) |
1876 | VMAAdjustment = AdjustVMA; |
1877 | |
1878 | // In executable and shared objects, r_offset holds a virtual address. |
1879 | // Subtract SectionAddr from the r_offset field of a relocation to get |
1880 | // the section offset. |
1881 | uint64_t RelAdjustment = Obj.isRelocatableObject() ? 0 : SectionAddr; |
1882 | uint64_t Size; |
1883 | uint64_t Index; |
1884 | bool PrintedSection = false; |
1885 | std::vector<RelocationRef> Rels = RelocMap[Section]; |
1886 | std::vector<RelocationRef>::const_iterator RelCur = Rels.begin(); |
1887 | std::vector<RelocationRef>::const_iterator RelEnd = Rels.end(); |
1888 | |
1889 | // Loop over each chunk of code between two points where at least |
1890 | // one symbol is defined. |
1891 | for (size_t SI = 0, SE = Symbols.size(); SI != SE;) { |
1892 | // Advance SI past all the symbols starting at the same address, |
1893 | // and make an ArrayRef of them. |
1894 | unsigned FirstSI = SI; |
1895 | uint64_t Start = Symbols[SI].Addr; |
1896 | ArrayRef<SymbolInfoTy> SymbolsHere; |
1897 | while (SI != SE && Symbols[SI].Addr == Start) |
1898 | ++SI; |
1899 | SymbolsHere = ArrayRef<SymbolInfoTy>(&Symbols[FirstSI], SI - FirstSI); |
1900 | |
1901 | // Get the demangled names of all those symbols. We end up with a vector |
1902 | // of StringRef that holds the names we're going to use, and a vector of |
1903 | // std::string that stores the new strings returned by demangle(), if |
1904 | // any. If we don't call demangle() then that vector can stay empty. |
1905 | std::vector<StringRef> SymNamesHere; |
1906 | std::vector<std::string> DemangledSymNamesHere; |
1907 | if (Demangle) { |
1908 | // Fetch the demangled names and store them locally. |
1909 | for (const SymbolInfoTy &Symbol : SymbolsHere) |
1910 | DemangledSymNamesHere.push_back(x: demangle(MangledName: Symbol.Name)); |
1911 | // Now we've finished modifying that vector, it's safe to make |
1912 | // a vector of StringRefs pointing into it. |
1913 | SymNamesHere.insert(position: SymNamesHere.begin(), first: DemangledSymNamesHere.begin(), |
1914 | last: DemangledSymNamesHere.end()); |
1915 | } else { |
1916 | for (const SymbolInfoTy &Symbol : SymbolsHere) |
1917 | SymNamesHere.push_back(x: Symbol.Name); |
1918 | } |
1919 | |
1920 | // Distinguish ELF data from code symbols, which will be used later on to |
1921 | // decide whether to 'disassemble' this chunk as a data declaration via |
1922 | // dumpELFData(), or whether to treat it as code. |
1923 | // |
1924 | // If data _and_ code symbols are defined at the same address, the code |
1925 | // takes priority, on the grounds that disassembling code is our main |
1926 | // purpose here, and it would be a worse failure to _not_ interpret |
1927 | // something that _was_ meaningful as code than vice versa. |
1928 | // |
1929 | // Any ELF symbol type that is not clearly data will be regarded as code. |
1930 | // In particular, one of the uses of STT_NOTYPE is for branch targets |
1931 | // inside functions, for which STT_FUNC would be inaccurate. |
1932 | // |
1933 | // So here, we spot whether there's any non-data symbol present at all, |
1934 | // and only set the DisassembleAsELFData flag if there isn't. Also, we use |
1935 | // this distinction to inform the decision of which symbol to print at |
1936 | // the head of the section, so that if we're printing code, we print a |
1937 | // code-related symbol name to go with it. |
1938 | bool DisassembleAsELFData = false; |
1939 | size_t DisplaySymIndex = SymbolsHere.size() - 1; |
1940 | if (Obj.isELF() && !DisassembleAll && Section.isText()) { |
1941 | DisassembleAsELFData = true; // unless we find a code symbol below |
1942 | |
1943 | for (size_t i = 0; i < SymbolsHere.size(); ++i) { |
1944 | uint8_t SymTy = SymbolsHere[i].Type; |
1945 | if (SymTy != ELF::STT_OBJECT && SymTy != ELF::STT_COMMON) { |
1946 | DisassembleAsELFData = false; |
1947 | DisplaySymIndex = i; |
1948 | } |
1949 | } |
1950 | } |
1951 | |
1952 | // Decide which symbol(s) from this collection we're going to print. |
1953 | std::vector<bool> SymsToPrint(SymbolsHere.size(), false); |
1954 | // If the user has given the --disassemble-symbols option, then we must |
1955 | // display every symbol in that set, and no others. |
1956 | if (!DisasmSymbolSet.empty()) { |
1957 | bool FoundAny = false; |
1958 | for (size_t i = 0; i < SymbolsHere.size(); ++i) { |
1959 | if (DisasmSymbolSet.count(Key: SymNamesHere[i])) { |
1960 | SymsToPrint[i] = true; |
1961 | FoundAny = true; |
1962 | } |
1963 | } |
1964 | |
1965 | // And if none of the symbols here is one that the user asked for, skip |
1966 | // disassembling this entire chunk of code. |
1967 | if (!FoundAny) |
1968 | continue; |
1969 | } else if (!SymbolsHere[DisplaySymIndex].IsMappingSymbol) { |
1970 | // Otherwise, print whichever symbol at this location is last in the |
1971 | // Symbols array, because that array is pre-sorted in a way intended to |
1972 | // correlate with priority of which symbol to display. |
1973 | SymsToPrint[DisplaySymIndex] = true; |
1974 | } |
1975 | |
1976 | // Now that we know we're disassembling this section, override the choice |
1977 | // of which symbols to display by printing _all_ of them at this address |
1978 | // if the user asked for all symbols. |
1979 | // |
1980 | // That way, '--show-all-symbols --disassemble-symbol=foo' will print |
1981 | // only the chunk of code headed by 'foo', but also show any other |
1982 | // symbols defined at that address, such as aliases for 'foo', or the ARM |
1983 | // mapping symbol preceding its code. |
1984 | if (ShowAllSymbols) { |
1985 | for (size_t i = 0; i < SymbolsHere.size(); ++i) |
1986 | SymsToPrint[i] = true; |
1987 | } |
1988 | |
1989 | if (Start < SectionAddr || StopAddress <= Start) |
1990 | continue; |
1991 | |
1992 | for (size_t i = 0; i < SymbolsHere.size(); ++i) |
1993 | FoundDisasmSymbolSet.insert(key: SymNamesHere[i]); |
1994 | |
1995 | // The end is the section end, the beginning of the next symbol, or |
1996 | // --stop-address. |
1997 | uint64_t End = std::min<uint64_t>(a: SectionAddr + SectSize, b: StopAddress); |
1998 | if (SI < SE) |
1999 | End = std::min(a: End, b: Symbols[SI].Addr); |
2000 | if (Start >= End || End <= StartAddress) |
2001 | continue; |
2002 | Start -= SectionAddr; |
2003 | End -= SectionAddr; |
2004 | |
2005 | if (!PrintedSection) { |
2006 | PrintedSection = true; |
2007 | outs() << "\nDisassembly of section " ; |
2008 | if (!SegmentName.empty()) |
2009 | outs() << SegmentName << "," ; |
2010 | outs() << SectionName << ":\n" ; |
2011 | } |
2012 | |
2013 | bool PrintedLabel = false; |
2014 | for (size_t i = 0; i < SymbolsHere.size(); ++i) { |
2015 | if (!SymsToPrint[i]) |
2016 | continue; |
2017 | |
2018 | const SymbolInfoTy &Symbol = SymbolsHere[i]; |
2019 | const StringRef SymbolName = SymNamesHere[i]; |
2020 | |
2021 | if (!PrintedLabel) { |
2022 | outs() << '\n'; |
2023 | PrintedLabel = true; |
2024 | } |
2025 | if (LeadingAddr) |
2026 | outs() << format(Fmt: Is64Bits ? "%016" PRIx64 " " : "%08" PRIx64 " " , |
2027 | Vals: SectionAddr + Start + VMAAdjustment); |
2028 | if (Obj.isXCOFF() && SymbolDescription) { |
2029 | outs() << getXCOFFSymbolDescription(SymbolInfo: Symbol, SymbolName) << ":\n" ; |
2030 | } else |
2031 | outs() << '<' << SymbolName << ">:\n" ; |
2032 | } |
2033 | |
2034 | // Don't print raw contents of a virtual section. A virtual section |
2035 | // doesn't have any contents in the file. |
2036 | if (Section.isVirtual()) { |
2037 | outs() << "...\n" ; |
2038 | continue; |
2039 | } |
2040 | |
2041 | // See if any of the symbols defined at this location triggers target- |
2042 | // specific disassembly behavior, e.g. of special descriptors or function |
2043 | // prelude information. |
2044 | // |
2045 | // We stop this loop at the first symbol that triggers some kind of |
2046 | // interesting behavior (if any), on the assumption that if two symbols |
2047 | // defined at the same address trigger two conflicting symbol handlers, |
2048 | // the object file is probably confused anyway, and it would make even |
2049 | // less sense to present the output of _both_ handlers, because that |
2050 | // would describe the same data twice. |
2051 | for (size_t SHI = 0; SHI < SymbolsHere.size(); ++SHI) { |
2052 | SymbolInfoTy Symbol = SymbolsHere[SHI]; |
2053 | |
2054 | Expected<bool> RespondedOrErr = DT->DisAsm->onSymbolStart( |
2055 | Symbol, Size, Bytes: Bytes.slice(N: Start, M: End - Start), Address: SectionAddr + Start); |
2056 | |
2057 | if (RespondedOrErr && !*RespondedOrErr) { |
2058 | // This symbol didn't trigger any interesting handling. Try the other |
2059 | // symbols defined at this address. |
2060 | continue; |
2061 | } |
2062 | |
2063 | // If onSymbolStart returned an Error, that means it identified some |
2064 | // kind of special data at this address, but wasn't able to disassemble |
2065 | // it meaningfully. So we fall back to printing the error out and |
2066 | // disassembling the failed region as bytes, assuming that the target |
2067 | // detected the failure before printing anything. |
2068 | if (!RespondedOrErr) { |
2069 | std::string ErrMsgStr = toString(E: RespondedOrErr.takeError()); |
2070 | StringRef ErrMsg = ErrMsgStr; |
2071 | do { |
2072 | StringRef Line; |
2073 | std::tie(args&: Line, args&: ErrMsg) = ErrMsg.split(Separator: '\n'); |
2074 | outs() << DT->Context->getAsmInfo()->getCommentString() |
2075 | << " error decoding " << SymNamesHere[SHI] << ": " << Line |
2076 | << '\n'; |
2077 | } while (!ErrMsg.empty()); |
2078 | |
2079 | if (Size) { |
2080 | outs() << DT->Context->getAsmInfo()->getCommentString() |
2081 | << " decoding failed region as bytes\n" ; |
2082 | for (uint64_t I = 0; I < Size; ++I) |
2083 | outs() << "\t.byte\t " << format_hex(N: Bytes[I], Width: 1, /*Upper=*/true) |
2084 | << '\n'; |
2085 | } |
2086 | } |
2087 | |
2088 | // Regardless of whether onSymbolStart returned an Error or true, 'Size' |
2089 | // will have been set to the amount of data covered by whatever prologue |
2090 | // the target identified. So we advance our own position to beyond that. |
2091 | // Sometimes that will be the entire distance to the next symbol, and |
2092 | // sometimes it will be just a prologue and we should start |
2093 | // disassembling instructions from where it left off. |
2094 | Start += Size; |
2095 | break; |
2096 | } |
2097 | |
2098 | Index = Start; |
2099 | if (SectionAddr < StartAddress) |
2100 | Index = std::max<uint64_t>(a: Index, b: StartAddress - SectionAddr); |
2101 | |
2102 | if (DisassembleAsELFData) { |
2103 | dumpELFData(SectionAddr, Index, End, Bytes); |
2104 | Index = End; |
2105 | continue; |
2106 | } |
2107 | |
2108 | // Skip relocations from symbols that are not dumped. |
2109 | for (; RelCur != RelEnd; ++RelCur) { |
2110 | uint64_t Offset = RelCur->getOffset() - RelAdjustment; |
2111 | if (Index <= Offset) |
2112 | break; |
2113 | } |
2114 | |
2115 | bool DumpARMELFData = false; |
2116 | bool DumpTracebackTableForXCOFFFunction = |
2117 | Obj.isXCOFF() && Section.isText() && TracebackTable && |
2118 | Symbols[SI - 1].XCOFFSymInfo.StorageMappingClass && |
2119 | (*Symbols[SI - 1].XCOFFSymInfo.StorageMappingClass == XCOFF::XMC_PR); |
2120 | |
2121 | formatted_raw_ostream FOS(outs()); |
2122 | |
2123 | std::unordered_map<uint64_t, std::string> AllLabels; |
2124 | std::unordered_map<uint64_t, std::vector<BBAddrMapLabel>> BBAddrMapLabels; |
2125 | if (SymbolizeOperands) { |
2126 | collectLocalBranchTargets(Bytes, MIA: DT->InstrAnalysis.get(), |
2127 | DisAsm: DT->DisAsm.get(), IP: DT->InstPrinter.get(), |
2128 | STI: PrimaryTarget.SubtargetInfo.get(), |
2129 | SectionAddr, Start: Index, End, Labels&: AllLabels); |
2130 | collectBBAddrMapLabels(FullAddrMap, SectionAddr, Start: Index, End, |
2131 | Labels&: BBAddrMapLabels); |
2132 | } |
2133 | |
2134 | if (DT->InstrAnalysis) |
2135 | DT->InstrAnalysis->resetState(); |
2136 | |
2137 | while (Index < End) { |
2138 | uint64_t RelOffset; |
2139 | |
2140 | // ARM and AArch64 ELF binaries can interleave data and text in the |
2141 | // same section. We rely on the markers introduced to understand what |
2142 | // we need to dump. If the data marker is within a function, it is |
2143 | // denoted as a word/short etc. |
2144 | if (!MappingSymbols.empty()) { |
2145 | char Kind = getMappingSymbolKind(MappingSymbols, Address: Index); |
2146 | DumpARMELFData = Kind == 'd'; |
2147 | if (SecondaryTarget) { |
2148 | if (Kind == 'a') { |
2149 | DT = PrimaryIsThumb ? &*SecondaryTarget : &PrimaryTarget; |
2150 | } else if (Kind == 't') { |
2151 | DT = PrimaryIsThumb ? &PrimaryTarget : &*SecondaryTarget; |
2152 | } |
2153 | } |
2154 | } else if (!CHPECodeMap.empty()) { |
2155 | uint64_t Address = SectionAddr + Index; |
2156 | auto It = partition_point( |
2157 | Range&: CHPECodeMap, |
2158 | P: [Address](const std::pair<uint64_t, uint64_t> &Entry) { |
2159 | return Entry.first <= Address; |
2160 | }); |
2161 | if (It != CHPECodeMap.begin() && Address < (It - 1)->second) { |
2162 | DT = &*SecondaryTarget; |
2163 | } else { |
2164 | DT = &PrimaryTarget; |
2165 | // X64 disassembler range may have left Index unaligned, so |
2166 | // make sure that it's aligned when we switch back to ARM64 |
2167 | // code. |
2168 | Index = llvm::alignTo(Value: Index, Align: 4); |
2169 | if (Index >= End) |
2170 | break; |
2171 | } |
2172 | } |
2173 | |
2174 | auto findRel = [&]() { |
2175 | while (RelCur != RelEnd) { |
2176 | RelOffset = RelCur->getOffset() - RelAdjustment; |
2177 | // If this relocation is hidden, skip it. |
2178 | if (getHidden(RelRef: *RelCur) || SectionAddr + RelOffset < StartAddress) { |
2179 | ++RelCur; |
2180 | continue; |
2181 | } |
2182 | |
2183 | // Stop when RelCur's offset is past the disassembled |
2184 | // instruction/data. |
2185 | if (RelOffset >= Index + Size) |
2186 | return false; |
2187 | if (RelOffset >= Index) |
2188 | return true; |
2189 | ++RelCur; |
2190 | } |
2191 | return false; |
2192 | }; |
2193 | |
2194 | if (DumpARMELFData) { |
2195 | Size = dumpARMELFData(SectionAddr, Index, End, Obj, Bytes, |
2196 | MappingSymbols, STI: *DT->SubtargetInfo, OS&: FOS); |
2197 | } else { |
2198 | // When -z or --disassemble-zeroes are given we always dissasemble |
2199 | // them. Otherwise we might want to skip zero bytes we see. |
2200 | if (!DisassembleZeroes) { |
2201 | uint64_t MaxOffset = End - Index; |
2202 | // For --reloc: print zero blocks patched by relocations, so that |
2203 | // relocations can be shown in the dump. |
2204 | if (InlineRelocs && RelCur != RelEnd) |
2205 | MaxOffset = std::min(a: RelCur->getOffset() - RelAdjustment - Index, |
2206 | b: MaxOffset); |
2207 | |
2208 | if (size_t N = |
2209 | countSkippableZeroBytes(Buf: Bytes.slice(N: Index, M: MaxOffset))) { |
2210 | FOS << "\t\t..." << '\n'; |
2211 | Index += N; |
2212 | continue; |
2213 | } |
2214 | } |
2215 | |
2216 | if (DumpTracebackTableForXCOFFFunction && |
2217 | doesXCOFFTracebackTableBegin(Bytes: Bytes.slice(N: Index, M: 4))) { |
2218 | dumpTracebackTable(Bytes: Bytes.slice(N: Index), |
2219 | Address: SectionAddr + Index + VMAAdjustment, OS&: FOS, |
2220 | End: SectionAddr + End + VMAAdjustment, |
2221 | STI: *DT->SubtargetInfo, Obj: cast<XCOFFObjectFile>(Val: &Obj)); |
2222 | Index = End; |
2223 | continue; |
2224 | } |
2225 | |
2226 | // Print local label if there's any. |
2227 | auto Iter1 = BBAddrMapLabels.find(x: SectionAddr + Index); |
2228 | if (Iter1 != BBAddrMapLabels.end()) { |
2229 | for (const auto &BBLabel : Iter1->second) |
2230 | FOS << "<" << BBLabel.BlockLabel << ">" << BBLabel.PGOAnalysis |
2231 | << ":\n" ; |
2232 | } else { |
2233 | auto Iter2 = AllLabels.find(x: SectionAddr + Index); |
2234 | if (Iter2 != AllLabels.end()) |
2235 | FOS << "<" << Iter2->second << ">:\n" ; |
2236 | } |
2237 | |
2238 | // Disassemble a real instruction or a data when disassemble all is |
2239 | // provided |
2240 | MCInst Inst; |
2241 | ArrayRef<uint8_t> ThisBytes = Bytes.slice(N: Index); |
2242 | uint64_t ThisAddr = SectionAddr + Index; |
2243 | bool Disassembled = DT->DisAsm->getInstruction( |
2244 | Instr&: Inst, Size, Bytes: ThisBytes, Address: ThisAddr, CStream&: CommentStream); |
2245 | if (Size == 0) |
2246 | Size = std::min<uint64_t>( |
2247 | a: ThisBytes.size(), |
2248 | b: DT->DisAsm->suggestBytesToSkip(Bytes: ThisBytes, Address: ThisAddr)); |
2249 | |
2250 | LVP.update(ThisAddr: {.Address: Index, .SectionIndex: Section.getIndex()}, |
2251 | NextAddr: {.Address: Index + Size, .SectionIndex: Section.getIndex()}, IncludeDefinedVars: Index + Size != End); |
2252 | |
2253 | DT->InstPrinter->setCommentStream(CommentStream); |
2254 | |
2255 | DT->Printer->printInst( |
2256 | IP&: *DT->InstPrinter, MI: Disassembled ? &Inst : nullptr, |
2257 | Bytes: Bytes.slice(N: Index, M: Size), |
2258 | Address: {.Address: SectionAddr + Index + VMAAdjustment, .SectionIndex: Section.getIndex()}, OS&: FOS, |
2259 | Annot: "" , STI: *DT->SubtargetInfo, SP: &SP, ObjectFilename: Obj.getFileName(), Rels: &Rels, LVP); |
2260 | |
2261 | DT->InstPrinter->setCommentStream(llvm::nulls()); |
2262 | |
2263 | // If disassembly succeeds, we try to resolve the target address |
2264 | // (jump target or memory operand address) and print it to the |
2265 | // right of the instruction. |
2266 | // |
2267 | // Otherwise, we don't print anything else so that we avoid |
2268 | // analyzing invalid or incomplete instruction information. |
2269 | if (Disassembled && DT->InstrAnalysis) { |
2270 | llvm::raw_ostream *TargetOS = &FOS; |
2271 | uint64_t Target; |
2272 | bool PrintTarget = DT->InstrAnalysis->evaluateBranch( |
2273 | Inst, Addr: SectionAddr + Index, Size, Target); |
2274 | |
2275 | if (!PrintTarget) { |
2276 | if (std::optional<uint64_t> MaybeTarget = |
2277 | DT->InstrAnalysis->evaluateMemoryOperandAddress( |
2278 | Inst, STI: DT->SubtargetInfo.get(), Addr: SectionAddr + Index, |
2279 | Size)) { |
2280 | Target = *MaybeTarget; |
2281 | PrintTarget = true; |
2282 | // Do not print real address when symbolizing. |
2283 | if (!SymbolizeOperands) { |
2284 | // Memory operand addresses are printed as comments. |
2285 | TargetOS = &CommentStream; |
2286 | *TargetOS << "0x" << Twine::utohexstr(Val: Target); |
2287 | } |
2288 | } |
2289 | } |
2290 | |
2291 | if (PrintTarget) { |
2292 | // In a relocatable object, the target's section must reside in |
2293 | // the same section as the call instruction or it is accessed |
2294 | // through a relocation. |
2295 | // |
2296 | // In a non-relocatable object, the target may be in any section. |
2297 | // In that case, locate the section(s) containing the target |
2298 | // address and find the symbol in one of those, if possible. |
2299 | // |
2300 | // N.B. Except for XCOFF, we don't walk the relocations in the |
2301 | // relocatable case yet. |
2302 | std::vector<const SectionSymbolsTy *> TargetSectionSymbols; |
2303 | if (!Obj.isRelocatableObject()) { |
2304 | auto It = llvm::partition_point( |
2305 | Range&: SectionAddresses, |
2306 | P: [=](const std::pair<uint64_t, SectionRef> &O) { |
2307 | return O.first <= Target; |
2308 | }); |
2309 | uint64_t TargetSecAddr = 0; |
2310 | while (It != SectionAddresses.begin()) { |
2311 | --It; |
2312 | if (TargetSecAddr == 0) |
2313 | TargetSecAddr = It->first; |
2314 | if (It->first != TargetSecAddr) |
2315 | break; |
2316 | TargetSectionSymbols.push_back(x: &AllSymbols[It->second]); |
2317 | } |
2318 | } else { |
2319 | TargetSectionSymbols.push_back(x: &Symbols); |
2320 | } |
2321 | TargetSectionSymbols.push_back(x: &AbsoluteSymbols); |
2322 | |
2323 | // Find the last symbol in the first candidate section whose |
2324 | // offset is less than or equal to the target. If there are no |
2325 | // such symbols, try in the next section and so on, before finally |
2326 | // using the nearest preceding absolute symbol (if any), if there |
2327 | // are no other valid symbols. |
2328 | const SymbolInfoTy *TargetSym = nullptr; |
2329 | for (const SectionSymbolsTy *TargetSymbols : |
2330 | TargetSectionSymbols) { |
2331 | auto It = llvm::partition_point( |
2332 | Range: *TargetSymbols, |
2333 | P: [=](const SymbolInfoTy &O) { return O.Addr <= Target; }); |
2334 | while (It != TargetSymbols->begin()) { |
2335 | --It; |
2336 | // Skip mapping symbols to avoid possible ambiguity as they |
2337 | // do not allow uniquely identifying the target address. |
2338 | if (!It->IsMappingSymbol) { |
2339 | TargetSym = &*It; |
2340 | break; |
2341 | } |
2342 | } |
2343 | if (TargetSym) |
2344 | break; |
2345 | } |
2346 | |
2347 | // Branch targets are printed just after the instructions. |
2348 | // Print the labels corresponding to the target if there's any. |
2349 | bool BBAddrMapLabelAvailable = BBAddrMapLabels.count(x: Target); |
2350 | bool LabelAvailable = AllLabels.count(x: Target); |
2351 | |
2352 | if (TargetSym != nullptr) { |
2353 | uint64_t TargetAddress = TargetSym->Addr; |
2354 | uint64_t Disp = Target - TargetAddress; |
2355 | std::string TargetName = Demangle ? demangle(MangledName: TargetSym->Name) |
2356 | : TargetSym->Name.str(); |
2357 | bool RelFixedUp = false; |
2358 | SmallString<32> Val; |
2359 | |
2360 | *TargetOS << " <" ; |
2361 | // On XCOFF, we use relocations, even without -r, so we |
2362 | // can print the correct name for an extern function call. |
2363 | if (Obj.isXCOFF() && findRel()) { |
2364 | // Check for possible branch relocations and |
2365 | // branches to fixup code. |
2366 | bool BranchRelocationType = true; |
2367 | XCOFF::RelocationType RelocType; |
2368 | if (Obj.is64Bit()) { |
2369 | const XCOFFRelocation64 *Reloc = |
2370 | reinterpret_cast<XCOFFRelocation64 *>( |
2371 | RelCur->getRawDataRefImpl().p); |
2372 | RelFixedUp = Reloc->isFixupIndicated(); |
2373 | RelocType = Reloc->Type; |
2374 | } else { |
2375 | const XCOFFRelocation32 *Reloc = |
2376 | reinterpret_cast<XCOFFRelocation32 *>( |
2377 | RelCur->getRawDataRefImpl().p); |
2378 | RelFixedUp = Reloc->isFixupIndicated(); |
2379 | RelocType = Reloc->Type; |
2380 | } |
2381 | BranchRelocationType = |
2382 | RelocType == XCOFF::R_BA || RelocType == XCOFF::R_BR || |
2383 | RelocType == XCOFF::R_RBA || RelocType == XCOFF::R_RBR; |
2384 | |
2385 | // If we have a valid relocation, try to print its |
2386 | // corresponding symbol name. Multiple relocations on the |
2387 | // same instruction are not handled. |
2388 | // Branches to fixup code will have the RelFixedUp flag set in |
2389 | // the RLD. For these instructions, we print the correct |
2390 | // branch target, but print the referenced symbol as a |
2391 | // comment. |
2392 | if (Error E = getRelocationValueString(Rel: *RelCur, SymbolDescription: false, Result&: Val)) { |
2393 | // If -r was used, this error will be printed later. |
2394 | // Otherwise, we ignore the error and print what |
2395 | // would have been printed without using relocations. |
2396 | consumeError(Err: std::move(E)); |
2397 | *TargetOS << TargetName; |
2398 | RelFixedUp = false; // Suppress comment for RLD sym name |
2399 | } else if (BranchRelocationType && !RelFixedUp) |
2400 | *TargetOS << Val; |
2401 | else |
2402 | *TargetOS << TargetName; |
2403 | if (Disp) |
2404 | *TargetOS << "+0x" << Twine::utohexstr(Val: Disp); |
2405 | } else if (!Disp) { |
2406 | *TargetOS << TargetName; |
2407 | } else if (BBAddrMapLabelAvailable) { |
2408 | *TargetOS << BBAddrMapLabels[Target].front().BlockLabel; |
2409 | } else if (LabelAvailable) { |
2410 | *TargetOS << AllLabels[Target]; |
2411 | } else { |
2412 | // Always Print the binary symbol plus an offset if there's no |
2413 | // local label corresponding to the target address. |
2414 | *TargetOS << TargetName << "+0x" << Twine::utohexstr(Val: Disp); |
2415 | } |
2416 | *TargetOS << ">" ; |
2417 | if (RelFixedUp && !InlineRelocs) { |
2418 | // We have fixup code for a relocation. We print the |
2419 | // referenced symbol as a comment. |
2420 | *TargetOS << "\t# " << Val; |
2421 | } |
2422 | |
2423 | } else if (BBAddrMapLabelAvailable) { |
2424 | *TargetOS << " <" << BBAddrMapLabels[Target].front().BlockLabel |
2425 | << ">" ; |
2426 | } else if (LabelAvailable) { |
2427 | *TargetOS << " <" << AllLabels[Target] << ">" ; |
2428 | } |
2429 | // By convention, each record in the comment stream should be |
2430 | // terminated. |
2431 | if (TargetOS == &CommentStream) |
2432 | *TargetOS << "\n" ; |
2433 | } |
2434 | |
2435 | DT->InstrAnalysis->updateState(Inst, Addr: SectionAddr + Index); |
2436 | } else if (!Disassembled && DT->InstrAnalysis) { |
2437 | DT->InstrAnalysis->resetState(); |
2438 | } |
2439 | } |
2440 | |
2441 | assert(DT->Context->getAsmInfo()); |
2442 | emitPostInstructionInfo(FOS, MAI: *DT->Context->getAsmInfo(), |
2443 | STI: *DT->SubtargetInfo, Comments: CommentStream.str(), LVP); |
2444 | Comments.clear(); |
2445 | |
2446 | if (BTF) |
2447 | printBTFRelocation(FOS, BTF&: *BTF, Address: {.Address: Index, .SectionIndex: Section.getIndex()}, LVP); |
2448 | |
2449 | // Hexagon handles relocs in pretty printer |
2450 | if (InlineRelocs && Obj.getArch() != Triple::hexagon) { |
2451 | while (findRel()) { |
2452 | // When --adjust-vma is used, update the address printed. |
2453 | if (RelCur->getSymbol() != Obj.symbol_end()) { |
2454 | Expected<section_iterator> SymSI = |
2455 | RelCur->getSymbol()->getSection(); |
2456 | if (SymSI && *SymSI != Obj.section_end() && |
2457 | shouldAdjustVA(Section: **SymSI)) |
2458 | RelOffset += AdjustVMA; |
2459 | } |
2460 | |
2461 | printRelocation(OS&: FOS, FileName: Obj.getFileName(), Rel: *RelCur, |
2462 | Address: SectionAddr + RelOffset, Is64Bits); |
2463 | LVP.printAfterOtherLine(OS&: FOS, AfterInst: true); |
2464 | ++RelCur; |
2465 | } |
2466 | } |
2467 | |
2468 | Index += Size; |
2469 | } |
2470 | } |
2471 | } |
2472 | StringSet<> MissingDisasmSymbolSet = |
2473 | set_difference(S1: DisasmSymbolSet, S2: FoundDisasmSymbolSet); |
2474 | for (StringRef Sym : MissingDisasmSymbolSet.keys()) |
2475 | reportWarning(Message: "failed to disassemble missing symbol " + Sym, File: FileName); |
2476 | } |
2477 | |
2478 | static void disassembleObject(ObjectFile *Obj, bool InlineRelocs) { |
2479 | // If information useful for showing the disassembly is missing, try to find a |
2480 | // more complete binary and disassemble that instead. |
2481 | OwningBinary<Binary> FetchedBinary; |
2482 | if (Obj->symbols().empty()) { |
2483 | if (std::optional<OwningBinary<Binary>> FetchedBinaryOpt = |
2484 | fetchBinaryByBuildID(Obj: *Obj)) { |
2485 | if (auto *O = dyn_cast<ObjectFile>(Val: FetchedBinaryOpt->getBinary())) { |
2486 | if (!O->symbols().empty() || |
2487 | (!O->sections().empty() && Obj->sections().empty())) { |
2488 | FetchedBinary = std::move(*FetchedBinaryOpt); |
2489 | Obj = O; |
2490 | } |
2491 | } |
2492 | } |
2493 | } |
2494 | |
2495 | const Target *TheTarget = getTarget(Obj); |
2496 | |
2497 | // Package up features to be passed to target/subtarget |
2498 | Expected<SubtargetFeatures> FeaturesValue = Obj->getFeatures(); |
2499 | if (!FeaturesValue) |
2500 | reportError(E: FeaturesValue.takeError(), FileName: Obj->getFileName()); |
2501 | SubtargetFeatures Features = *FeaturesValue; |
2502 | if (!MAttrs.empty()) { |
2503 | for (unsigned I = 0; I != MAttrs.size(); ++I) |
2504 | Features.AddFeature(String: MAttrs[I]); |
2505 | } else if (MCPU.empty() && Obj->getArch() == llvm::Triple::aarch64) { |
2506 | Features.AddFeature(String: "+all" ); |
2507 | } |
2508 | |
2509 | if (MCPU.empty()) |
2510 | MCPU = Obj->tryGetCPUName().value_or(u: "" ).str(); |
2511 | |
2512 | if (isArmElf(Obj: *Obj)) { |
2513 | // When disassembling big-endian Arm ELF, the instruction endianness is |
2514 | // determined in a complex way. In relocatable objects, AAELF32 mandates |
2515 | // that instruction endianness matches the ELF file endianness; in |
2516 | // executable images, that's true unless the file header has the EF_ARM_BE8 |
2517 | // flag, in which case instructions are little-endian regardless of data |
2518 | // endianness. |
2519 | // |
2520 | // We must set the big-endian-instructions SubtargetFeature to make the |
2521 | // disassembler read the instructions the right way round, and also tell |
2522 | // our own prettyprinter to retrieve the encodings the same way to print in |
2523 | // hex. |
2524 | const auto *Elf32BE = dyn_cast<ELF32BEObjectFile>(Val: Obj); |
2525 | |
2526 | if (Elf32BE && (Elf32BE->isRelocatableObject() || |
2527 | !(Elf32BE->getPlatformFlags() & ELF::EF_ARM_BE8))) { |
2528 | Features.AddFeature(String: "+big-endian-instructions" ); |
2529 | ARMPrettyPrinterInst.setInstructionEndianness(llvm::endianness::big); |
2530 | } else { |
2531 | ARMPrettyPrinterInst.setInstructionEndianness(llvm::endianness::little); |
2532 | } |
2533 | } |
2534 | |
2535 | DisassemblerTarget PrimaryTarget(TheTarget, *Obj, TripleName, MCPU, Features); |
2536 | |
2537 | // If we have an ARM object file, we need a second disassembler, because |
2538 | // ARM CPUs have two different instruction sets: ARM mode, and Thumb mode. |
2539 | // We use mapping symbols to switch between the two assemblers, where |
2540 | // appropriate. |
2541 | std::optional<DisassemblerTarget> SecondaryTarget; |
2542 | |
2543 | if (isArmElf(Obj: *Obj)) { |
2544 | if (!PrimaryTarget.SubtargetInfo->checkFeatures(FS: "+mclass" )) { |
2545 | if (PrimaryTarget.SubtargetInfo->checkFeatures(FS: "+thumb-mode" )) |
2546 | Features.AddFeature(String: "-thumb-mode" ); |
2547 | else |
2548 | Features.AddFeature(String: "+thumb-mode" ); |
2549 | SecondaryTarget.emplace(args&: PrimaryTarget, args&: Features); |
2550 | } |
2551 | } else if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Val: Obj)) { |
2552 | const chpe_metadata *CHPEMetadata = COFFObj->getCHPEMetadata(); |
2553 | if (CHPEMetadata && CHPEMetadata->CodeMapCount) { |
2554 | // Set up x86_64 disassembler for ARM64EC binaries. |
2555 | Triple X64Triple(TripleName); |
2556 | X64Triple.setArch(Kind: Triple::ArchType::x86_64); |
2557 | |
2558 | std::string Error; |
2559 | const Target *X64Target = |
2560 | TargetRegistry::lookupTarget(ArchName: "" , TheTriple&: X64Triple, Error); |
2561 | if (X64Target) { |
2562 | SubtargetFeatures X64Features; |
2563 | SecondaryTarget.emplace(args&: X64Target, args&: *Obj, args: X64Triple.getTriple(), args: "" , |
2564 | args&: X64Features); |
2565 | } else { |
2566 | reportWarning(Message: Error, File: Obj->getFileName()); |
2567 | } |
2568 | } |
2569 | } |
2570 | |
2571 | const ObjectFile *DbgObj = Obj; |
2572 | if (!FetchedBinary.getBinary() && !Obj->hasDebugInfo()) { |
2573 | if (std::optional<OwningBinary<Binary>> DebugBinaryOpt = |
2574 | fetchBinaryByBuildID(Obj: *Obj)) { |
2575 | if (auto *FetchedObj = |
2576 | dyn_cast<const ObjectFile>(Val: DebugBinaryOpt->getBinary())) { |
2577 | if (FetchedObj->hasDebugInfo()) { |
2578 | FetchedBinary = std::move(*DebugBinaryOpt); |
2579 | DbgObj = FetchedObj; |
2580 | } |
2581 | } |
2582 | } |
2583 | } |
2584 | |
2585 | std::unique_ptr<object::Binary> DSYMBinary; |
2586 | std::unique_ptr<MemoryBuffer> DSYMBuf; |
2587 | if (!DbgObj->hasDebugInfo()) { |
2588 | if (const MachOObjectFile *MachOOF = dyn_cast<MachOObjectFile>(Val: &*Obj)) { |
2589 | DbgObj = objdump::getMachODSymObject(O: MachOOF, Filename: Obj->getFileName(), |
2590 | DSYMBinary, DSYMBuf); |
2591 | if (!DbgObj) |
2592 | return; |
2593 | } |
2594 | } |
2595 | |
2596 | SourcePrinter SP(DbgObj, TheTarget->getName()); |
2597 | |
2598 | for (StringRef Opt : DisassemblerOptions) |
2599 | if (!PrimaryTarget.InstPrinter->applyTargetSpecificCLOption(Opt)) |
2600 | reportError(File: Obj->getFileName(), |
2601 | Message: "Unrecognized disassembler option: " + Opt); |
2602 | |
2603 | disassembleObject(Obj&: *Obj, DbgObj: *DbgObj, PrimaryTarget, SecondaryTarget, SP, |
2604 | InlineRelocs); |
2605 | } |
2606 | |
2607 | void Dumper::printRelocations() { |
2608 | StringRef Fmt = O.getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64; |
2609 | |
2610 | // Build a mapping from relocation target to a vector of relocation |
2611 | // sections. Usually, there is an only one relocation section for |
2612 | // each relocated section. |
2613 | MapVector<SectionRef, std::vector<SectionRef>> SecToRelSec; |
2614 | uint64_t Ndx; |
2615 | for (const SectionRef &Section : ToolSectionFilter(O, Idx: &Ndx)) { |
2616 | if (O.isELF() && (ELFSectionRef(Section).getFlags() & ELF::SHF_ALLOC)) |
2617 | continue; |
2618 | if (Section.relocation_begin() == Section.relocation_end()) |
2619 | continue; |
2620 | Expected<section_iterator> SecOrErr = Section.getRelocatedSection(); |
2621 | if (!SecOrErr) |
2622 | reportError(File: O.getFileName(), |
2623 | Message: "section (" + Twine(Ndx) + |
2624 | "): unable to get a relocation target: " + |
2625 | toString(E: SecOrErr.takeError())); |
2626 | SecToRelSec[**SecOrErr].push_back(x: Section); |
2627 | } |
2628 | |
2629 | for (std::pair<SectionRef, std::vector<SectionRef>> &P : SecToRelSec) { |
2630 | StringRef SecName = unwrapOrError(EO: P.first.getName(), Args: O.getFileName()); |
2631 | outs() << "\nRELOCATION RECORDS FOR [" << SecName << "]:\n" ; |
2632 | uint32_t OffsetPadding = (O.getBytesInAddress() > 4 ? 16 : 8); |
2633 | uint32_t TypePadding = 24; |
2634 | outs() << left_justify(Str: "OFFSET" , Width: OffsetPadding) << " " |
2635 | << left_justify(Str: "TYPE" , Width: TypePadding) << " " |
2636 | << "VALUE\n" ; |
2637 | |
2638 | for (SectionRef Section : P.second) { |
2639 | for (const RelocationRef &Reloc : Section.relocations()) { |
2640 | uint64_t Address = Reloc.getOffset(); |
2641 | SmallString<32> RelocName; |
2642 | SmallString<32> ValueStr; |
2643 | if (Address < StartAddress || Address > StopAddress || getHidden(RelRef: Reloc)) |
2644 | continue; |
2645 | Reloc.getTypeName(Result&: RelocName); |
2646 | if (Error E = |
2647 | getRelocationValueString(Rel: Reloc, SymbolDescription, Result&: ValueStr)) |
2648 | reportUniqueWarning(Err: std::move(E)); |
2649 | |
2650 | outs() << format(Fmt: Fmt.data(), Vals: Address) << " " |
2651 | << left_justify(Str: RelocName, Width: TypePadding) << " " << ValueStr |
2652 | << "\n" ; |
2653 | } |
2654 | } |
2655 | } |
2656 | } |
2657 | |
2658 | // Returns true if we need to show LMA column when dumping section headers. We |
2659 | // show it only when the platform is ELF and either we have at least one section |
2660 | // whose VMA and LMA are different and/or when --show-lma flag is used. |
2661 | static bool shouldDisplayLMA(const ObjectFile &Obj) { |
2662 | if (!Obj.isELF()) |
2663 | return false; |
2664 | for (const SectionRef &S : ToolSectionFilter(O: Obj)) |
2665 | if (S.getAddress() != getELFSectionLMA(Sec: S)) |
2666 | return true; |
2667 | return ShowLMA; |
2668 | } |
2669 | |
2670 | static size_t getMaxSectionNameWidth(const ObjectFile &Obj) { |
2671 | // Default column width for names is 13 even if no names are that long. |
2672 | size_t MaxWidth = 13; |
2673 | for (const SectionRef &Section : ToolSectionFilter(O: Obj)) { |
2674 | StringRef Name = unwrapOrError(EO: Section.getName(), Args: Obj.getFileName()); |
2675 | MaxWidth = std::max(a: MaxWidth, b: Name.size()); |
2676 | } |
2677 | return MaxWidth; |
2678 | } |
2679 | |
2680 | void objdump::(ObjectFile &Obj) { |
2681 | if (Obj.isELF() && Obj.sections().empty()) |
2682 | createFakeELFSections(Obj); |
2683 | |
2684 | size_t NameWidth = getMaxSectionNameWidth(Obj); |
2685 | size_t AddressWidth = 2 * Obj.getBytesInAddress(); |
2686 | bool HasLMAColumn = shouldDisplayLMA(Obj); |
2687 | outs() << "\nSections:\n" ; |
2688 | if (HasLMAColumn) |
2689 | outs() << "Idx " << left_justify(Str: "Name" , Width: NameWidth) << " Size " |
2690 | << left_justify(Str: "VMA" , Width: AddressWidth) << " " |
2691 | << left_justify(Str: "LMA" , Width: AddressWidth) << " Type\n" ; |
2692 | else |
2693 | outs() << "Idx " << left_justify(Str: "Name" , Width: NameWidth) << " Size " |
2694 | << left_justify(Str: "VMA" , Width: AddressWidth) << " Type\n" ; |
2695 | |
2696 | uint64_t Idx; |
2697 | for (const SectionRef &Section : ToolSectionFilter(O: Obj, Idx: &Idx)) { |
2698 | StringRef Name = unwrapOrError(EO: Section.getName(), Args: Obj.getFileName()); |
2699 | uint64_t VMA = Section.getAddress(); |
2700 | if (shouldAdjustVA(Section)) |
2701 | VMA += AdjustVMA; |
2702 | |
2703 | uint64_t Size = Section.getSize(); |
2704 | |
2705 | std::string Type = Section.isText() ? "TEXT" : "" ; |
2706 | if (Section.isData()) |
2707 | Type += Type.empty() ? "DATA" : ", DATA" ; |
2708 | if (Section.isBSS()) |
2709 | Type += Type.empty() ? "BSS" : ", BSS" ; |
2710 | if (Section.isDebugSection()) |
2711 | Type += Type.empty() ? "DEBUG" : ", DEBUG" ; |
2712 | |
2713 | if (HasLMAColumn) |
2714 | outs() << format(Fmt: "%3" PRIu64 " %-*s %08" PRIx64 " " , Vals: Idx, Vals: NameWidth, |
2715 | Vals: Name.str().c_str(), Vals: Size) |
2716 | << format_hex_no_prefix(N: VMA, Width: AddressWidth) << " " |
2717 | << format_hex_no_prefix(N: getELFSectionLMA(Sec: Section), Width: AddressWidth) |
2718 | << " " << Type << "\n" ; |
2719 | else |
2720 | outs() << format(Fmt: "%3" PRIu64 " %-*s %08" PRIx64 " " , Vals: Idx, Vals: NameWidth, |
2721 | Vals: Name.str().c_str(), Vals: Size) |
2722 | << format_hex_no_prefix(N: VMA, Width: AddressWidth) << " " << Type << "\n" ; |
2723 | } |
2724 | } |
2725 | |
2726 | void objdump::printSectionContents(const ObjectFile *Obj) { |
2727 | const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Val: Obj); |
2728 | |
2729 | for (const SectionRef &Section : ToolSectionFilter(O: *Obj)) { |
2730 | StringRef Name = unwrapOrError(EO: Section.getName(), Args: Obj->getFileName()); |
2731 | uint64_t BaseAddr = Section.getAddress(); |
2732 | uint64_t Size = Section.getSize(); |
2733 | if (!Size) |
2734 | continue; |
2735 | |
2736 | outs() << "Contents of section " ; |
2737 | StringRef SegmentName = getSegmentName(MachO, Section); |
2738 | if (!SegmentName.empty()) |
2739 | outs() << SegmentName << "," ; |
2740 | outs() << Name << ":\n" ; |
2741 | if (Section.isBSS()) { |
2742 | outs() << format(Fmt: "<skipping contents of bss section at [%04" PRIx64 |
2743 | ", %04" PRIx64 ")>\n" , |
2744 | Vals: BaseAddr, Vals: BaseAddr + Size); |
2745 | continue; |
2746 | } |
2747 | |
2748 | StringRef Contents = unwrapOrError(EO: Section.getContents(), Args: Obj->getFileName()); |
2749 | |
2750 | // Dump out the content as hex and printable ascii characters. |
2751 | for (std::size_t Addr = 0, End = Contents.size(); Addr < End; Addr += 16) { |
2752 | outs() << format(Fmt: " %04" PRIx64 " " , Vals: BaseAddr + Addr); |
2753 | // Dump line of hex. |
2754 | for (std::size_t I = 0; I < 16; ++I) { |
2755 | if (I != 0 && I % 4 == 0) |
2756 | outs() << ' '; |
2757 | if (Addr + I < End) |
2758 | outs() << hexdigit(X: (Contents[Addr + I] >> 4) & 0xF, LowerCase: true) |
2759 | << hexdigit(X: Contents[Addr + I] & 0xF, LowerCase: true); |
2760 | else |
2761 | outs() << " " ; |
2762 | } |
2763 | // Print ascii. |
2764 | outs() << " " ; |
2765 | for (std::size_t I = 0; I < 16 && Addr + I < End; ++I) { |
2766 | if (isPrint(C: static_cast<unsigned char>(Contents[Addr + I]) & 0xFF)) |
2767 | outs() << Contents[Addr + I]; |
2768 | else |
2769 | outs() << "." ; |
2770 | } |
2771 | outs() << "\n" ; |
2772 | } |
2773 | } |
2774 | } |
2775 | |
2776 | void Dumper::printSymbolTable(StringRef ArchiveName, StringRef ArchitectureName, |
2777 | bool DumpDynamic) { |
2778 | if (O.isCOFF() && !DumpDynamic) { |
2779 | outs() << "\nSYMBOL TABLE:\n" ; |
2780 | printCOFFSymbolTable(O: cast<const COFFObjectFile>(Val: O)); |
2781 | return; |
2782 | } |
2783 | |
2784 | const StringRef FileName = O.getFileName(); |
2785 | |
2786 | if (!DumpDynamic) { |
2787 | outs() << "\nSYMBOL TABLE:\n" ; |
2788 | for (auto I = O.symbol_begin(); I != O.symbol_end(); ++I) |
2789 | printSymbol(Symbol: *I, SymbolVersions: {}, FileName, ArchiveName, ArchitectureName, DumpDynamic); |
2790 | return; |
2791 | } |
2792 | |
2793 | outs() << "\nDYNAMIC SYMBOL TABLE:\n" ; |
2794 | if (!O.isELF()) { |
2795 | reportWarning( |
2796 | Message: "this operation is not currently supported for this file format" , |
2797 | File: FileName); |
2798 | return; |
2799 | } |
2800 | |
2801 | const ELFObjectFileBase *ELF = cast<const ELFObjectFileBase>(Val: &O); |
2802 | auto Symbols = ELF->getDynamicSymbolIterators(); |
2803 | Expected<std::vector<VersionEntry>> SymbolVersionsOrErr = |
2804 | ELF->readDynsymVersions(); |
2805 | if (!SymbolVersionsOrErr) { |
2806 | reportWarning(Message: toString(E: SymbolVersionsOrErr.takeError()), File: FileName); |
2807 | SymbolVersionsOrErr = std::vector<VersionEntry>(); |
2808 | (void)!SymbolVersionsOrErr; |
2809 | } |
2810 | for (auto &Sym : Symbols) |
2811 | printSymbol(Symbol: Sym, SymbolVersions: *SymbolVersionsOrErr, FileName, ArchiveName, |
2812 | ArchitectureName, DumpDynamic); |
2813 | } |
2814 | |
2815 | void Dumper::printSymbol(const SymbolRef &Symbol, |
2816 | ArrayRef<VersionEntry> SymbolVersions, |
2817 | StringRef FileName, StringRef ArchiveName, |
2818 | StringRef ArchitectureName, bool DumpDynamic) { |
2819 | const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Val: &O); |
2820 | Expected<uint64_t> AddrOrErr = Symbol.getAddress(); |
2821 | if (!AddrOrErr) { |
2822 | reportUniqueWarning(Err: AddrOrErr.takeError()); |
2823 | return; |
2824 | } |
2825 | uint64_t Address = *AddrOrErr; |
2826 | section_iterator SecI = unwrapOrError(EO: Symbol.getSection(), Args&: FileName); |
2827 | if (SecI != O.section_end() && shouldAdjustVA(Section: *SecI)) |
2828 | Address += AdjustVMA; |
2829 | if ((Address < StartAddress) || (Address > StopAddress)) |
2830 | return; |
2831 | SymbolRef::Type Type = |
2832 | unwrapOrError(EO: Symbol.getType(), Args&: FileName, Args&: ArchiveName, Args&: ArchitectureName); |
2833 | uint32_t Flags = |
2834 | unwrapOrError(EO: Symbol.getFlags(), Args&: FileName, Args&: ArchiveName, Args&: ArchitectureName); |
2835 | |
2836 | // Don't ask a Mach-O STAB symbol for its section unless you know that |
2837 | // STAB symbol's section field refers to a valid section index. Otherwise |
2838 | // the symbol may error trying to load a section that does not exist. |
2839 | bool IsSTAB = false; |
2840 | if (MachO) { |
2841 | DataRefImpl SymDRI = Symbol.getRawDataRefImpl(); |
2842 | uint8_t NType = |
2843 | (MachO->is64Bit() ? MachO->getSymbol64TableEntry(DRI: SymDRI).n_type |
2844 | : MachO->getSymbolTableEntry(DRI: SymDRI).n_type); |
2845 | if (NType & MachO::N_STAB) |
2846 | IsSTAB = true; |
2847 | } |
2848 | section_iterator Section = IsSTAB |
2849 | ? O.section_end() |
2850 | : unwrapOrError(EO: Symbol.getSection(), Args&: FileName, |
2851 | Args&: ArchiveName, Args&: ArchitectureName); |
2852 | |
2853 | StringRef Name; |
2854 | if (Type == SymbolRef::ST_Debug && Section != O.section_end()) { |
2855 | if (Expected<StringRef> NameOrErr = Section->getName()) |
2856 | Name = *NameOrErr; |
2857 | else |
2858 | consumeError(Err: NameOrErr.takeError()); |
2859 | |
2860 | } else { |
2861 | Name = unwrapOrError(EO: Symbol.getName(), Args&: FileName, Args&: ArchiveName, |
2862 | Args&: ArchitectureName); |
2863 | } |
2864 | |
2865 | bool Global = Flags & SymbolRef::SF_Global; |
2866 | bool Weak = Flags & SymbolRef::SF_Weak; |
2867 | bool Absolute = Flags & SymbolRef::SF_Absolute; |
2868 | bool Common = Flags & SymbolRef::SF_Common; |
2869 | bool Hidden = Flags & SymbolRef::SF_Hidden; |
2870 | |
2871 | char GlobLoc = ' '; |
2872 | if ((Section != O.section_end() || Absolute) && !Weak) |
2873 | GlobLoc = Global ? 'g' : 'l'; |
2874 | char IFunc = ' '; |
2875 | if (O.isELF()) { |
2876 | if (ELFSymbolRef(Symbol).getELFType() == ELF::STT_GNU_IFUNC) |
2877 | IFunc = 'i'; |
2878 | if (ELFSymbolRef(Symbol).getBinding() == ELF::STB_GNU_UNIQUE) |
2879 | GlobLoc = 'u'; |
2880 | } |
2881 | |
2882 | char Debug = ' '; |
2883 | if (DumpDynamic) |
2884 | Debug = 'D'; |
2885 | else if (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File) |
2886 | Debug = 'd'; |
2887 | |
2888 | char FileFunc = ' '; |
2889 | if (Type == SymbolRef::ST_File) |
2890 | FileFunc = 'f'; |
2891 | else if (Type == SymbolRef::ST_Function) |
2892 | FileFunc = 'F'; |
2893 | else if (Type == SymbolRef::ST_Data) |
2894 | FileFunc = 'O'; |
2895 | |
2896 | const char *Fmt = O.getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64; |
2897 | |
2898 | outs() << format(Fmt, Vals: Address) << " " |
2899 | << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' ' |
2900 | << (Weak ? 'w' : ' ') // Weak? |
2901 | << ' ' // Constructor. Not supported yet. |
2902 | << ' ' // Warning. Not supported yet. |
2903 | << IFunc // Indirect reference to another symbol. |
2904 | << Debug // Debugging (d) or dynamic (D) symbol. |
2905 | << FileFunc // Name of function (F), file (f) or object (O). |
2906 | << ' '; |
2907 | if (Absolute) { |
2908 | outs() << "*ABS*" ; |
2909 | } else if (Common) { |
2910 | outs() << "*COM*" ; |
2911 | } else if (Section == O.section_end()) { |
2912 | if (O.isXCOFF()) { |
2913 | XCOFFSymbolRef XCOFFSym = cast<const XCOFFObjectFile>(Val: O).toSymbolRef( |
2914 | Ref: Symbol.getRawDataRefImpl()); |
2915 | if (XCOFF::N_DEBUG == XCOFFSym.getSectionNumber()) |
2916 | outs() << "*DEBUG*" ; |
2917 | else |
2918 | outs() << "*UND*" ; |
2919 | } else |
2920 | outs() << "*UND*" ; |
2921 | } else { |
2922 | StringRef SegmentName = getSegmentName(MachO, Section: *Section); |
2923 | if (!SegmentName.empty()) |
2924 | outs() << SegmentName << "," ; |
2925 | StringRef SectionName = unwrapOrError(EO: Section->getName(), Args&: FileName); |
2926 | outs() << SectionName; |
2927 | if (O.isXCOFF()) { |
2928 | std::optional<SymbolRef> SymRef = |
2929 | getXCOFFSymbolContainingSymbolRef(Obj: cast<XCOFFObjectFile>(Val: O), Sym: Symbol); |
2930 | if (SymRef) { |
2931 | |
2932 | Expected<StringRef> NameOrErr = SymRef->getName(); |
2933 | |
2934 | if (NameOrErr) { |
2935 | outs() << " (csect:" ; |
2936 | std::string SymName = |
2937 | Demangle ? demangle(MangledName: *NameOrErr) : NameOrErr->str(); |
2938 | |
2939 | if (SymbolDescription) |
2940 | SymName = getXCOFFSymbolDescription(SymbolInfo: createSymbolInfo(Obj: O, Symbol: *SymRef), |
2941 | SymbolName: SymName); |
2942 | |
2943 | outs() << ' ' << SymName; |
2944 | outs() << ") " ; |
2945 | } else |
2946 | reportWarning(Message: toString(E: NameOrErr.takeError()), File: FileName); |
2947 | } |
2948 | } |
2949 | } |
2950 | |
2951 | if (Common) |
2952 | outs() << '\t' << format(Fmt, Vals: static_cast<uint64_t>(Symbol.getAlignment())); |
2953 | else if (O.isXCOFF()) |
2954 | outs() << '\t' |
2955 | << format(Fmt, Vals: cast<XCOFFObjectFile>(Val: O).getSymbolSize( |
2956 | Symb: Symbol.getRawDataRefImpl())); |
2957 | else if (O.isELF()) |
2958 | outs() << '\t' << format(Fmt, Vals: ELFSymbolRef(Symbol).getSize()); |
2959 | else if (O.isWasm()) |
2960 | outs() << '\t' |
2961 | << format(Fmt, Vals: static_cast<uint64_t>( |
2962 | cast<WasmObjectFile>(Val: O).getSymbolSize(Sym: Symbol))); |
2963 | |
2964 | if (O.isELF()) { |
2965 | if (!SymbolVersions.empty()) { |
2966 | const VersionEntry &Ver = |
2967 | SymbolVersions[Symbol.getRawDataRefImpl().d.b - 1]; |
2968 | std::string Str; |
2969 | if (!Ver.Name.empty()) |
2970 | Str = Ver.IsVerDef ? ' ' + Ver.Name : '(' + Ver.Name + ')'; |
2971 | outs() << ' ' << left_justify(Str, Width: 12); |
2972 | } |
2973 | |
2974 | uint8_t Other = ELFSymbolRef(Symbol).getOther(); |
2975 | switch (Other) { |
2976 | case ELF::STV_DEFAULT: |
2977 | break; |
2978 | case ELF::STV_INTERNAL: |
2979 | outs() << " .internal" ; |
2980 | break; |
2981 | case ELF::STV_HIDDEN: |
2982 | outs() << " .hidden" ; |
2983 | break; |
2984 | case ELF::STV_PROTECTED: |
2985 | outs() << " .protected" ; |
2986 | break; |
2987 | default: |
2988 | outs() << format(Fmt: " 0x%02x" , Vals: Other); |
2989 | break; |
2990 | } |
2991 | } else if (Hidden) { |
2992 | outs() << " .hidden" ; |
2993 | } |
2994 | |
2995 | std::string SymName = Demangle ? demangle(MangledName: Name) : Name.str(); |
2996 | if (O.isXCOFF() && SymbolDescription) |
2997 | SymName = getXCOFFSymbolDescription(SymbolInfo: createSymbolInfo(Obj: O, Symbol), SymbolName: SymName); |
2998 | |
2999 | outs() << ' ' << SymName << '\n'; |
3000 | } |
3001 | |
3002 | static void printUnwindInfo(const ObjectFile *O) { |
3003 | outs() << "Unwind info:\n\n" ; |
3004 | |
3005 | if (const COFFObjectFile *Coff = dyn_cast<COFFObjectFile>(Val: O)) |
3006 | printCOFFUnwindInfo(O: Coff); |
3007 | else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(Val: O)) |
3008 | printMachOUnwindInfo(O: MachO); |
3009 | else |
3010 | // TODO: Extract DWARF dump tool to objdump. |
3011 | WithColor::error(OS&: errs(), Prefix: ToolName) |
3012 | << "This operation is only currently supported " |
3013 | "for COFF and MachO object files.\n" ; |
3014 | } |
3015 | |
3016 | /// Dump the raw contents of the __clangast section so the output can be piped |
3017 | /// into llvm-bcanalyzer. |
3018 | static void printRawClangAST(const ObjectFile *Obj) { |
3019 | if (outs().is_displayed()) { |
3020 | WithColor::error(OS&: errs(), Prefix: ToolName) |
3021 | << "The -raw-clang-ast option will dump the raw binary contents of " |
3022 | "the clang ast section.\n" |
3023 | "Please redirect the output to a file or another program such as " |
3024 | "llvm-bcanalyzer.\n" ; |
3025 | return; |
3026 | } |
3027 | |
3028 | StringRef ClangASTSectionName("__clangast" ); |
3029 | if (Obj->isCOFF()) { |
3030 | ClangASTSectionName = "clangast" ; |
3031 | } |
3032 | |
3033 | std::optional<object::SectionRef> ClangASTSection; |
3034 | for (auto Sec : ToolSectionFilter(O: *Obj)) { |
3035 | StringRef Name; |
3036 | if (Expected<StringRef> NameOrErr = Sec.getName()) |
3037 | Name = *NameOrErr; |
3038 | else |
3039 | consumeError(Err: NameOrErr.takeError()); |
3040 | |
3041 | if (Name == ClangASTSectionName) { |
3042 | ClangASTSection = Sec; |
3043 | break; |
3044 | } |
3045 | } |
3046 | if (!ClangASTSection) |
3047 | return; |
3048 | |
3049 | StringRef ClangASTContents = |
3050 | unwrapOrError(EO: ClangASTSection->getContents(), Args: Obj->getFileName()); |
3051 | outs().write(Ptr: ClangASTContents.data(), Size: ClangASTContents.size()); |
3052 | } |
3053 | |
3054 | static void printFaultMaps(const ObjectFile *Obj) { |
3055 | StringRef FaultMapSectionName; |
3056 | |
3057 | if (Obj->isELF()) { |
3058 | FaultMapSectionName = ".llvm_faultmaps" ; |
3059 | } else if (Obj->isMachO()) { |
3060 | FaultMapSectionName = "__llvm_faultmaps" ; |
3061 | } else { |
3062 | WithColor::error(OS&: errs(), Prefix: ToolName) |
3063 | << "This operation is only currently supported " |
3064 | "for ELF and Mach-O executable files.\n" ; |
3065 | return; |
3066 | } |
3067 | |
3068 | std::optional<object::SectionRef> FaultMapSection; |
3069 | |
3070 | for (auto Sec : ToolSectionFilter(O: *Obj)) { |
3071 | StringRef Name; |
3072 | if (Expected<StringRef> NameOrErr = Sec.getName()) |
3073 | Name = *NameOrErr; |
3074 | else |
3075 | consumeError(Err: NameOrErr.takeError()); |
3076 | |
3077 | if (Name == FaultMapSectionName) { |
3078 | FaultMapSection = Sec; |
3079 | break; |
3080 | } |
3081 | } |
3082 | |
3083 | outs() << "FaultMap table:\n" ; |
3084 | |
3085 | if (!FaultMapSection) { |
3086 | outs() << "<not found>\n" ; |
3087 | return; |
3088 | } |
3089 | |
3090 | StringRef FaultMapContents = |
3091 | unwrapOrError(EO: FaultMapSection->getContents(), Args: Obj->getFileName()); |
3092 | FaultMapParser FMP(FaultMapContents.bytes_begin(), |
3093 | FaultMapContents.bytes_end()); |
3094 | |
3095 | outs() << FMP; |
3096 | } |
3097 | |
3098 | void Dumper::() { |
3099 | reportError(File: O.getFileName(), Message: "Invalid/Unsupported object file format" ); |
3100 | } |
3101 | |
3102 | static void (const ObjectFile *O) { |
3103 | if (!O->isELF() && !O->isCOFF()) |
3104 | reportError(File: O->getFileName(), Message: "Invalid/Unsupported object file format" ); |
3105 | |
3106 | Triple::ArchType AT = O->getArch(); |
3107 | outs() << "architecture: " << Triple::getArchTypeName(Kind: AT) << "\n" ; |
3108 | uint64_t Address = unwrapOrError(EO: O->getStartAddress(), Args: O->getFileName()); |
3109 | |
3110 | StringRef Fmt = O->getBytesInAddress() > 4 ? "%016" PRIx64 : "%08" PRIx64; |
3111 | outs() << "start address: " |
3112 | << "0x" << format(Fmt: Fmt.data(), Vals: Address) << "\n" ; |
3113 | } |
3114 | |
3115 | static void printArchiveChild(StringRef Filename, const Archive::Child &C) { |
3116 | Expected<sys::fs::perms> ModeOrErr = C.getAccessMode(); |
3117 | if (!ModeOrErr) { |
3118 | WithColor::error(OS&: errs(), Prefix: ToolName) << "ill-formed archive entry.\n" ; |
3119 | consumeError(Err: ModeOrErr.takeError()); |
3120 | return; |
3121 | } |
3122 | sys::fs::perms Mode = ModeOrErr.get(); |
3123 | outs() << ((Mode & sys::fs::owner_read) ? "r" : "-" ); |
3124 | outs() << ((Mode & sys::fs::owner_write) ? "w" : "-" ); |
3125 | outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-" ); |
3126 | outs() << ((Mode & sys::fs::group_read) ? "r" : "-" ); |
3127 | outs() << ((Mode & sys::fs::group_write) ? "w" : "-" ); |
3128 | outs() << ((Mode & sys::fs::group_exe) ? "x" : "-" ); |
3129 | outs() << ((Mode & sys::fs::others_read) ? "r" : "-" ); |
3130 | outs() << ((Mode & sys::fs::others_write) ? "w" : "-" ); |
3131 | outs() << ((Mode & sys::fs::others_exe) ? "x" : "-" ); |
3132 | |
3133 | outs() << " " ; |
3134 | |
3135 | outs() << format(Fmt: "%d/%d %6" PRId64 " " , Vals: unwrapOrError(EO: C.getUID(), Args&: Filename), |
3136 | Vals: unwrapOrError(EO: C.getGID(), Args&: Filename), |
3137 | Vals: unwrapOrError(EO: C.getRawSize(), Args&: Filename)); |
3138 | |
3139 | StringRef RawLastModified = C.getRawLastModified(); |
3140 | unsigned Seconds; |
3141 | if (RawLastModified.getAsInteger(Radix: 10, Result&: Seconds)) |
3142 | outs() << "(date: \"" << RawLastModified |
3143 | << "\" contains non-decimal chars) " ; |
3144 | else { |
3145 | // Since ctime(3) returns a 26 character string of the form: |
3146 | // "Sun Sep 16 01:03:52 1973\n\0" |
3147 | // just print 24 characters. |
3148 | time_t t = Seconds; |
3149 | outs() << format(Fmt: "%.24s " , Vals: ctime(timer: &t)); |
3150 | } |
3151 | |
3152 | StringRef Name = "" ; |
3153 | Expected<StringRef> NameOrErr = C.getName(); |
3154 | if (!NameOrErr) { |
3155 | consumeError(Err: NameOrErr.takeError()); |
3156 | Name = unwrapOrError(EO: C.getRawName(), Args&: Filename); |
3157 | } else { |
3158 | Name = NameOrErr.get(); |
3159 | } |
3160 | outs() << Name << "\n" ; |
3161 | } |
3162 | |
3163 | // For ELF only now. |
3164 | static bool shouldWarnForInvalidStartStopAddress(ObjectFile *Obj) { |
3165 | if (const auto *Elf = dyn_cast<ELFObjectFileBase>(Val: Obj)) { |
3166 | if (Elf->getEType() != ELF::ET_REL) |
3167 | return true; |
3168 | } |
3169 | return false; |
3170 | } |
3171 | |
3172 | static void checkForInvalidStartStopAddress(ObjectFile *Obj, |
3173 | uint64_t Start, uint64_t Stop) { |
3174 | if (!shouldWarnForInvalidStartStopAddress(Obj)) |
3175 | return; |
3176 | |
3177 | for (const SectionRef &Section : Obj->sections()) |
3178 | if (ELFSectionRef(Section).getFlags() & ELF::SHF_ALLOC) { |
3179 | uint64_t BaseAddr = Section.getAddress(); |
3180 | uint64_t Size = Section.getSize(); |
3181 | if ((Start < BaseAddr + Size) && Stop > BaseAddr) |
3182 | return; |
3183 | } |
3184 | |
3185 | if (!HasStartAddressFlag) |
3186 | reportWarning(Message: "no section has address less than 0x" + |
3187 | Twine::utohexstr(Val: Stop) + " specified by --stop-address" , |
3188 | File: Obj->getFileName()); |
3189 | else if (!HasStopAddressFlag) |
3190 | reportWarning(Message: "no section has address greater than or equal to 0x" + |
3191 | Twine::utohexstr(Val: Start) + " specified by --start-address" , |
3192 | File: Obj->getFileName()); |
3193 | else |
3194 | reportWarning(Message: "no section overlaps the range [0x" + |
3195 | Twine::utohexstr(Val: Start) + ",0x" + Twine::utohexstr(Val: Stop) + |
3196 | ") specified by --start-address/--stop-address" , |
3197 | File: Obj->getFileName()); |
3198 | } |
3199 | |
3200 | static void dumpObject(ObjectFile *O, const Archive *A = nullptr, |
3201 | const Archive::Child *C = nullptr) { |
3202 | Expected<std::unique_ptr<Dumper>> DumperOrErr = createDumper(Obj: *O); |
3203 | if (!DumperOrErr) { |
3204 | reportError(E: DumperOrErr.takeError(), FileName: O->getFileName(), |
3205 | ArchiveName: A ? A->getFileName() : "" ); |
3206 | return; |
3207 | } |
3208 | Dumper &D = **DumperOrErr; |
3209 | |
3210 | // Avoid other output when using a raw option. |
3211 | if (!RawClangAST) { |
3212 | outs() << '\n'; |
3213 | if (A) |
3214 | outs() << A->getFileName() << "(" << O->getFileName() << ")" ; |
3215 | else |
3216 | outs() << O->getFileName(); |
3217 | outs() << ":\tfile format " << O->getFileFormatName().lower() << "\n" ; |
3218 | } |
3219 | |
3220 | if (HasStartAddressFlag || HasStopAddressFlag) |
3221 | checkForInvalidStartStopAddress(Obj: O, Start: StartAddress, Stop: StopAddress); |
3222 | |
3223 | // TODO: Change print* free functions to Dumper member functions to utilitize |
3224 | // stateful functions like reportUniqueWarning. |
3225 | |
3226 | // Note: the order here matches GNU objdump for compatability. |
3227 | StringRef ArchiveName = A ? A->getFileName() : "" ; |
3228 | if (ArchiveHeaders && !MachOOpt && C) |
3229 | printArchiveChild(Filename: ArchiveName, C: *C); |
3230 | if (FileHeaders) |
3231 | printFileHeaders(O); |
3232 | if (PrivateHeaders || FirstPrivateHeader) |
3233 | D.printPrivateHeaders(); |
3234 | if (SectionHeaders) |
3235 | printSectionHeaders(Obj&: *O); |
3236 | if (SymbolTable) |
3237 | D.printSymbolTable(ArchiveName); |
3238 | if (DynamicSymbolTable) |
3239 | D.printSymbolTable(ArchiveName, /*ArchitectureName=*/"" , |
3240 | /*DumpDynamic=*/true); |
3241 | if (DwarfDumpType != DIDT_Null) { |
3242 | std::unique_ptr<DIContext> DICtx = DWARFContext::create(Obj: *O); |
3243 | // Dump the complete DWARF structure. |
3244 | DIDumpOptions DumpOpts; |
3245 | DumpOpts.DumpType = DwarfDumpType; |
3246 | DICtx->dump(OS&: outs(), DumpOpts); |
3247 | } |
3248 | if (Relocations && !Disassemble) |
3249 | D.printRelocations(); |
3250 | if (DynamicRelocations) |
3251 | D.printDynamicRelocations(); |
3252 | if (SectionContents) |
3253 | printSectionContents(Obj: O); |
3254 | if (Disassemble) |
3255 | disassembleObject(Obj: O, InlineRelocs: Relocations); |
3256 | if (UnwindInfo) |
3257 | printUnwindInfo(O); |
3258 | |
3259 | // Mach-O specific options: |
3260 | if (ExportsTrie) |
3261 | printExportsTrie(O); |
3262 | if (Rebase) |
3263 | printRebaseTable(O); |
3264 | if (Bind) |
3265 | printBindTable(O); |
3266 | if (LazyBind) |
3267 | printLazyBindTable(O); |
3268 | if (WeakBind) |
3269 | printWeakBindTable(O); |
3270 | |
3271 | // Other special sections: |
3272 | if (RawClangAST) |
3273 | printRawClangAST(Obj: O); |
3274 | if (FaultMapSection) |
3275 | printFaultMaps(Obj: O); |
3276 | if (Offloading) |
3277 | dumpOffloadBinary(O: *O); |
3278 | } |
3279 | |
3280 | static void dumpObject(const COFFImportFile *I, const Archive *A, |
3281 | const Archive::Child *C = nullptr) { |
3282 | StringRef ArchiveName = A ? A->getFileName() : "" ; |
3283 | |
3284 | // Avoid other output when using a raw option. |
3285 | if (!RawClangAST) |
3286 | outs() << '\n' |
3287 | << ArchiveName << "(" << I->getFileName() << ")" |
3288 | << ":\tfile format COFF-import-file" |
3289 | << "\n\n" ; |
3290 | |
3291 | if (ArchiveHeaders && !MachOOpt && C) |
3292 | printArchiveChild(Filename: ArchiveName, C: *C); |
3293 | if (SymbolTable) |
3294 | printCOFFSymbolTable(I: *I); |
3295 | } |
3296 | |
3297 | /// Dump each object file in \a a; |
3298 | static void dumpArchive(const Archive *A) { |
3299 | Error Err = Error::success(); |
3300 | unsigned I = -1; |
3301 | for (auto &C : A->children(Err)) { |
3302 | ++I; |
3303 | Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary(); |
3304 | if (!ChildOrErr) { |
3305 | if (auto E = isNotObjectErrorInvalidFileType(Err: ChildOrErr.takeError())) |
3306 | reportError(E: std::move(E), FileName: getFileNameForError(C, Index: I), ArchiveName: A->getFileName()); |
3307 | continue; |
3308 | } |
3309 | if (ObjectFile *O = dyn_cast<ObjectFile>(Val: &*ChildOrErr.get())) |
3310 | dumpObject(O, A, C: &C); |
3311 | else if (COFFImportFile *I = dyn_cast<COFFImportFile>(Val: &*ChildOrErr.get())) |
3312 | dumpObject(I, A, C: &C); |
3313 | else |
3314 | reportError(E: errorCodeToError(EC: object_error::invalid_file_type), |
3315 | FileName: A->getFileName()); |
3316 | } |
3317 | if (Err) |
3318 | reportError(E: std::move(Err), FileName: A->getFileName()); |
3319 | } |
3320 | |
3321 | /// Open file and figure out how to dump it. |
3322 | static void dumpInput(StringRef file) { |
3323 | // If we are using the Mach-O specific object file parser, then let it parse |
3324 | // the file and process the command line options. So the -arch flags can |
3325 | // be used to select specific slices, etc. |
3326 | if (MachOOpt) { |
3327 | parseInputMachO(Filename: file); |
3328 | return; |
3329 | } |
3330 | |
3331 | // Attempt to open the binary. |
3332 | OwningBinary<Binary> OBinary = unwrapOrError(EO: createBinary(Path: file), Args&: file); |
3333 | Binary &Binary = *OBinary.getBinary(); |
3334 | |
3335 | if (Archive *A = dyn_cast<Archive>(Val: &Binary)) |
3336 | dumpArchive(A); |
3337 | else if (ObjectFile *O = dyn_cast<ObjectFile>(Val: &Binary)) |
3338 | dumpObject(O); |
3339 | else if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(Val: &Binary)) |
3340 | parseInputMachO(UB); |
3341 | else if (OffloadBinary *OB = dyn_cast<OffloadBinary>(Val: &Binary)) |
3342 | dumpOffloadSections(OB: *OB); |
3343 | else |
3344 | reportError(E: errorCodeToError(EC: object_error::invalid_file_type), FileName: file); |
3345 | } |
3346 | |
3347 | template <typename T> |
3348 | static void parseIntArg(const llvm::opt::InputArgList &InputArgs, int ID, |
3349 | T &Value) { |
3350 | if (const opt::Arg *A = InputArgs.getLastArg(Ids: ID)) { |
3351 | StringRef V(A->getValue()); |
3352 | if (!llvm::to_integer(V, Value, 0)) { |
3353 | reportCmdLineError(Message: A->getSpelling() + |
3354 | ": expected a non-negative integer, but got '" + V + |
3355 | "'" ); |
3356 | } |
3357 | } |
3358 | } |
3359 | |
3360 | static object::BuildID parseBuildIDArg(const opt::Arg *A) { |
3361 | StringRef V(A->getValue()); |
3362 | object::BuildID BID = parseBuildID(Str: V); |
3363 | if (BID.empty()) |
3364 | reportCmdLineError(Message: A->getSpelling() + ": expected a build ID, but got '" + |
3365 | V + "'" ); |
3366 | return BID; |
3367 | } |
3368 | |
3369 | void objdump::invalidArgValue(const opt::Arg *A) { |
3370 | reportCmdLineError(Message: "'" + StringRef(A->getValue()) + |
3371 | "' is not a valid value for '" + A->getSpelling() + "'" ); |
3372 | } |
3373 | |
3374 | static std::vector<std::string> |
3375 | commaSeparatedValues(const llvm::opt::InputArgList &InputArgs, int ID) { |
3376 | std::vector<std::string> Values; |
3377 | for (StringRef Value : InputArgs.getAllArgValues(Id: ID)) { |
3378 | llvm::SmallVector<StringRef, 2> SplitValues; |
3379 | llvm::SplitString(Source: Value, OutFragments&: SplitValues, Delimiters: "," ); |
3380 | for (StringRef SplitValue : SplitValues) |
3381 | Values.push_back(x: SplitValue.str()); |
3382 | } |
3383 | return Values; |
3384 | } |
3385 | |
3386 | static void parseOtoolOptions(const llvm::opt::InputArgList &InputArgs) { |
3387 | MachOOpt = true; |
3388 | FullLeadingAddr = true; |
3389 | PrintImmHex = true; |
3390 | |
3391 | ArchName = InputArgs.getLastArgValue(Id: OTOOL_arch).str(); |
3392 | LinkOptHints = InputArgs.hasArg(OTOOL_C); |
3393 | if (InputArgs.hasArg(OTOOL_d)) |
3394 | FilterSections.push_back(x: "__DATA,__data" ); |
3395 | DylibId = InputArgs.hasArg(OTOOL_D); |
3396 | UniversalHeaders = InputArgs.hasArg(OTOOL_f); |
3397 | DataInCode = InputArgs.hasArg(OTOOL_G); |
3398 | FirstPrivateHeader = InputArgs.hasArg(OTOOL_h); |
3399 | IndirectSymbols = InputArgs.hasArg(OTOOL_I); |
3400 | ShowRawInsn = InputArgs.hasArg(OTOOL_j); |
3401 | PrivateHeaders = InputArgs.hasArg(OTOOL_l); |
3402 | DylibsUsed = InputArgs.hasArg(OTOOL_L); |
3403 | MCPU = InputArgs.getLastArgValue(Id: OTOOL_mcpu_EQ).str(); |
3404 | ObjcMetaData = InputArgs.hasArg(OTOOL_o); |
3405 | DisSymName = InputArgs.getLastArgValue(Id: OTOOL_p).str(); |
3406 | InfoPlist = InputArgs.hasArg(OTOOL_P); |
3407 | Relocations = InputArgs.hasArg(OTOOL_r); |
3408 | if (const Arg *A = InputArgs.getLastArg(OTOOL_s)) { |
3409 | auto Filter = (A->getValue(N: 0) + StringRef("," ) + A->getValue(N: 1)).str(); |
3410 | FilterSections.push_back(Filter); |
3411 | } |
3412 | if (InputArgs.hasArg(OTOOL_t)) |
3413 | FilterSections.push_back(x: "__TEXT,__text" ); |
3414 | Verbose = InputArgs.hasArg(OTOOL_v) || InputArgs.hasArg(OTOOL_V) || |
3415 | InputArgs.hasArg(OTOOL_o); |
3416 | SymbolicOperands = InputArgs.hasArg(OTOOL_V); |
3417 | if (InputArgs.hasArg(OTOOL_x)) |
3418 | FilterSections.push_back(x: ",__text" ); |
3419 | LeadingAddr = LeadingHeaders = !InputArgs.hasArg(OTOOL_X); |
3420 | |
3421 | ChainedFixups = InputArgs.hasArg(OTOOL_chained_fixups); |
3422 | DyldInfo = InputArgs.hasArg(OTOOL_dyld_info); |
3423 | |
3424 | InputFilenames = InputArgs.getAllArgValues(Id: OTOOL_INPUT); |
3425 | if (InputFilenames.empty()) |
3426 | reportCmdLineError(Message: "no input file" ); |
3427 | |
3428 | for (const Arg *A : InputArgs) { |
3429 | const Option &O = A->getOption(); |
3430 | if (O.getGroup().isValid() && O.getGroup().getID() == OTOOL_grp_obsolete) { |
3431 | reportCmdLineWarning(Message: O.getPrefixedName() + |
3432 | " is obsolete and not implemented" ); |
3433 | } |
3434 | } |
3435 | } |
3436 | |
3437 | static void parseObjdumpOptions(const llvm::opt::InputArgList &InputArgs) { |
3438 | parseIntArg(InputArgs, OBJDUMP_adjust_vma_EQ, AdjustVMA); |
3439 | AllHeaders = InputArgs.hasArg(OBJDUMP_all_headers); |
3440 | ArchName = InputArgs.getLastArgValue(Id: OBJDUMP_arch_name_EQ).str(); |
3441 | ArchiveHeaders = InputArgs.hasArg(OBJDUMP_archive_headers); |
3442 | Demangle = InputArgs.hasArg(OBJDUMP_demangle); |
3443 | Disassemble = InputArgs.hasArg(OBJDUMP_disassemble); |
3444 | DisassembleAll = InputArgs.hasArg(OBJDUMP_disassemble_all); |
3445 | SymbolDescription = InputArgs.hasArg(OBJDUMP_symbol_description); |
3446 | TracebackTable = InputArgs.hasArg(OBJDUMP_traceback_table); |
3447 | DisassembleSymbols = |
3448 | commaSeparatedValues(InputArgs, OBJDUMP_disassemble_symbols_EQ); |
3449 | DisassembleZeroes = InputArgs.hasArg(OBJDUMP_disassemble_zeroes); |
3450 | if (const opt::Arg *A = InputArgs.getLastArg(OBJDUMP_dwarf_EQ)) { |
3451 | DwarfDumpType = StringSwitch<DIDumpType>(A->getValue()) |
3452 | .Case(S: "frames" , Value: DIDT_DebugFrame) |
3453 | .Default(Value: DIDT_Null); |
3454 | if (DwarfDumpType == DIDT_Null) |
3455 | invalidArgValue(A); |
3456 | } |
3457 | DynamicRelocations = InputArgs.hasArg(OBJDUMP_dynamic_reloc); |
3458 | FaultMapSection = InputArgs.hasArg(OBJDUMP_fault_map_section); |
3459 | Offloading = InputArgs.hasArg(OBJDUMP_offloading); |
3460 | FileHeaders = InputArgs.hasArg(OBJDUMP_file_headers); |
3461 | SectionContents = InputArgs.hasArg(OBJDUMP_full_contents); |
3462 | PrintLines = InputArgs.hasArg(OBJDUMP_line_numbers); |
3463 | InputFilenames = InputArgs.getAllArgValues(Id: OBJDUMP_INPUT); |
3464 | MachOOpt = InputArgs.hasArg(OBJDUMP_macho); |
3465 | MCPU = InputArgs.getLastArgValue(Id: OBJDUMP_mcpu_EQ).str(); |
3466 | MAttrs = commaSeparatedValues(InputArgs, OBJDUMP_mattr_EQ); |
3467 | ShowRawInsn = !InputArgs.hasArg(OBJDUMP_no_show_raw_insn); |
3468 | LeadingAddr = !InputArgs.hasArg(OBJDUMP_no_leading_addr); |
3469 | RawClangAST = InputArgs.hasArg(OBJDUMP_raw_clang_ast); |
3470 | Relocations = InputArgs.hasArg(OBJDUMP_reloc); |
3471 | PrintImmHex = |
3472 | InputArgs.hasFlag(OBJDUMP_print_imm_hex, OBJDUMP_no_print_imm_hex, true); |
3473 | PrivateHeaders = InputArgs.hasArg(OBJDUMP_private_headers); |
3474 | FilterSections = InputArgs.getAllArgValues(OBJDUMP_section_EQ); |
3475 | SectionHeaders = InputArgs.hasArg(OBJDUMP_section_headers); |
3476 | ShowAllSymbols = InputArgs.hasArg(OBJDUMP_show_all_symbols); |
3477 | ShowLMA = InputArgs.hasArg(OBJDUMP_show_lma); |
3478 | PrintSource = InputArgs.hasArg(OBJDUMP_source); |
3479 | parseIntArg(InputArgs, OBJDUMP_start_address_EQ, StartAddress); |
3480 | HasStartAddressFlag = InputArgs.hasArg(OBJDUMP_start_address_EQ); |
3481 | parseIntArg(InputArgs, OBJDUMP_stop_address_EQ, StopAddress); |
3482 | HasStopAddressFlag = InputArgs.hasArg(OBJDUMP_stop_address_EQ); |
3483 | SymbolTable = InputArgs.hasArg(OBJDUMP_syms); |
3484 | SymbolizeOperands = InputArgs.hasArg(OBJDUMP_symbolize_operands); |
3485 | PrettyPGOAnalysisMap = InputArgs.hasArg(OBJDUMP_pretty_pgo_analysis_map); |
3486 | if (PrettyPGOAnalysisMap && !SymbolizeOperands) |
3487 | reportCmdLineWarning(Message: "--symbolize-operands must be enabled for " |
3488 | "--pretty-pgo-analysis-map to have an effect" ); |
3489 | DynamicSymbolTable = InputArgs.hasArg(OBJDUMP_dynamic_syms); |
3490 | TripleName = InputArgs.getLastArgValue(OBJDUMP_triple_EQ).str(); |
3491 | UnwindInfo = InputArgs.hasArg(OBJDUMP_unwind_info); |
3492 | Wide = InputArgs.hasArg(OBJDUMP_wide); |
3493 | Prefix = InputArgs.getLastArgValue(OBJDUMP_prefix).str(); |
3494 | parseIntArg(InputArgs, OBJDUMP_prefix_strip, PrefixStrip); |
3495 | if (const opt::Arg *A = InputArgs.getLastArg(OBJDUMP_debug_vars_EQ)) { |
3496 | DbgVariables = StringSwitch<DebugVarsFormat>(A->getValue()) |
3497 | .Case(S: "ascii" , Value: DVASCII) |
3498 | .Case(S: "unicode" , Value: DVUnicode) |
3499 | .Default(Value: DVInvalid); |
3500 | if (DbgVariables == DVInvalid) |
3501 | invalidArgValue(A); |
3502 | } |
3503 | if (const opt::Arg *A = InputArgs.getLastArg(OBJDUMP_disassembler_color_EQ)) { |
3504 | DisassemblyColor = StringSwitch<ColorOutput>(A->getValue()) |
3505 | .Case(S: "on" , Value: ColorOutput::Enable) |
3506 | .Case(S: "off" , Value: ColorOutput::Disable) |
3507 | .Case(S: "terminal" , Value: ColorOutput::Auto) |
3508 | .Default(Value: ColorOutput::Invalid); |
3509 | if (DisassemblyColor == ColorOutput::Invalid) |
3510 | invalidArgValue(A); |
3511 | } |
3512 | |
3513 | parseIntArg(InputArgs, OBJDUMP_debug_vars_indent_EQ, DbgIndent); |
3514 | |
3515 | parseMachOOptions(InputArgs); |
3516 | |
3517 | // Parse -M (--disassembler-options) and deprecated |
3518 | // --x86-asm-syntax={att,intel}. |
3519 | // |
3520 | // Note, for x86, the asm dialect (AssemblerDialect) is initialized when the |
3521 | // MCAsmInfo is constructed. MCInstPrinter::applyTargetSpecificCLOption is |
3522 | // called too late. For now we have to use the internal cl::opt option. |
3523 | const char *AsmSyntax = nullptr; |
3524 | for (const auto *A : InputArgs.filtered(OBJDUMP_disassembler_options_EQ, |
3525 | OBJDUMP_x86_asm_syntax_att, |
3526 | OBJDUMP_x86_asm_syntax_intel)) { |
3527 | switch (A->getOption().getID()) { |
3528 | case OBJDUMP_x86_asm_syntax_att: |
3529 | AsmSyntax = "--x86-asm-syntax=att" ; |
3530 | continue; |
3531 | case OBJDUMP_x86_asm_syntax_intel: |
3532 | AsmSyntax = "--x86-asm-syntax=intel" ; |
3533 | continue; |
3534 | } |
3535 | |
3536 | SmallVector<StringRef, 2> Values; |
3537 | llvm::SplitString(A->getValue(), Values, "," ); |
3538 | for (StringRef V : Values) { |
3539 | if (V == "att" ) |
3540 | AsmSyntax = "--x86-asm-syntax=att" ; |
3541 | else if (V == "intel" ) |
3542 | AsmSyntax = "--x86-asm-syntax=intel" ; |
3543 | else |
3544 | DisassemblerOptions.push_back(V.str()); |
3545 | } |
3546 | } |
3547 | SmallVector<const char *> Args = {"llvm-objdump" }; |
3548 | for (const opt::Arg *A : InputArgs.filtered(OBJDUMP_mllvm)) |
3549 | Args.push_back(A->getValue()); |
3550 | if (AsmSyntax) |
3551 | Args.push_back(Elt: AsmSyntax); |
3552 | if (Args.size() > 1) |
3553 | llvm::cl::ParseCommandLineOptions(argc: Args.size(), argv: Args.data()); |
3554 | |
3555 | // Look up any provided build IDs, then append them to the input filenames. |
3556 | for (const opt::Arg *A : InputArgs.filtered(OBJDUMP_build_id)) { |
3557 | object::BuildID BuildID = parseBuildIDArg(A); |
3558 | std::optional<std::string> Path = BIDFetcher->fetch(BuildID); |
3559 | if (!Path) { |
3560 | reportCmdLineError(A->getSpelling() + ": could not find build ID '" + |
3561 | A->getValue() + "'" ); |
3562 | } |
3563 | InputFilenames.push_back(std::move(*Path)); |
3564 | } |
3565 | |
3566 | // objdump defaults to a.out if no filenames specified. |
3567 | if (InputFilenames.empty()) |
3568 | InputFilenames.push_back(x: "a.out" ); |
3569 | } |
3570 | |
3571 | int llvm_objdump_main(int argc, char **argv, const llvm::ToolContext &) { |
3572 | using namespace llvm; |
3573 | |
3574 | ToolName = argv[0]; |
3575 | std::unique_ptr<CommonOptTable> T; |
3576 | OptSpecifier Unknown, HelpFlag, HelpHiddenFlag, VersionFlag; |
3577 | |
3578 | StringRef Stem = sys::path::stem(path: ToolName); |
3579 | auto Is = [=](StringRef Tool) { |
3580 | // We need to recognize the following filenames: |
3581 | // |
3582 | // llvm-objdump -> objdump |
3583 | // llvm-otool-10.exe -> otool |
3584 | // powerpc64-unknown-freebsd13-objdump -> objdump |
3585 | auto I = Stem.rfind_insensitive(Str: Tool); |
3586 | return I != StringRef::npos && |
3587 | (I + Tool.size() == Stem.size() || !isAlnum(C: Stem[I + Tool.size()])); |
3588 | }; |
3589 | if (Is("otool" )) { |
3590 | T = std::make_unique<OtoolOptTable>(); |
3591 | Unknown = OTOOL_UNKNOWN; |
3592 | HelpFlag = OTOOL_help; |
3593 | HelpHiddenFlag = OTOOL_help_hidden; |
3594 | VersionFlag = OTOOL_version; |
3595 | } else { |
3596 | T = std::make_unique<ObjdumpOptTable>(); |
3597 | Unknown = OBJDUMP_UNKNOWN; |
3598 | HelpFlag = OBJDUMP_help; |
3599 | HelpHiddenFlag = OBJDUMP_help_hidden; |
3600 | VersionFlag = OBJDUMP_version; |
3601 | } |
3602 | |
3603 | BumpPtrAllocator A; |
3604 | StringSaver Saver(A); |
3605 | opt::InputArgList InputArgs = |
3606 | T->parseArgs(Argc: argc, Argv: argv, Unknown, Saver, |
3607 | ErrorFn: [&](StringRef Msg) { reportCmdLineError(Message: Msg); }); |
3608 | |
3609 | if (InputArgs.size() == 0 || InputArgs.hasArg(Ids: HelpFlag)) { |
3610 | T->printHelp(Argv0: ToolName); |
3611 | return 0; |
3612 | } |
3613 | if (InputArgs.hasArg(Ids: HelpHiddenFlag)) { |
3614 | T->printHelp(Argv0: ToolName, /*ShowHidden=*/true); |
3615 | return 0; |
3616 | } |
3617 | |
3618 | // Initialize targets and assembly printers/parsers. |
3619 | InitializeAllTargetInfos(); |
3620 | InitializeAllTargetMCs(); |
3621 | InitializeAllDisassemblers(); |
3622 | |
3623 | if (InputArgs.hasArg(Ids: VersionFlag)) { |
3624 | cl::PrintVersionMessage(); |
3625 | if (!Is("otool" )) { |
3626 | outs() << '\n'; |
3627 | TargetRegistry::printRegisteredTargetsForVersion(OS&: outs()); |
3628 | } |
3629 | return 0; |
3630 | } |
3631 | |
3632 | // Initialize debuginfod. |
3633 | const bool ShouldUseDebuginfodByDefault = |
3634 | InputArgs.hasArg(OBJDUMP_build_id) || canUseDebuginfod(); |
3635 | std::vector<std::string> DebugFileDirectories = |
3636 | InputArgs.getAllArgValues(OBJDUMP_debug_file_directory); |
3637 | if (InputArgs.hasFlag(OBJDUMP_debuginfod, OBJDUMP_no_debuginfod, |
3638 | ShouldUseDebuginfodByDefault)) { |
3639 | HTTPClient::initialize(); |
3640 | BIDFetcher = |
3641 | std::make_unique<DebuginfodFetcher>(args: std::move(DebugFileDirectories)); |
3642 | } else { |
3643 | BIDFetcher = |
3644 | std::make_unique<BuildIDFetcher>(args: std::move(DebugFileDirectories)); |
3645 | } |
3646 | |
3647 | if (Is("otool" )) |
3648 | parseOtoolOptions(InputArgs); |
3649 | else |
3650 | parseObjdumpOptions(InputArgs); |
3651 | |
3652 | if (StartAddress >= StopAddress) |
3653 | reportCmdLineError(Message: "start address should be less than stop address" ); |
3654 | |
3655 | // Removes trailing separators from prefix. |
3656 | while (!Prefix.empty() && sys::path::is_separator(value: Prefix.back())) |
3657 | Prefix.pop_back(); |
3658 | |
3659 | if (AllHeaders) |
3660 | ArchiveHeaders = FileHeaders = PrivateHeaders = Relocations = |
3661 | SectionHeaders = SymbolTable = true; |
3662 | |
3663 | if (DisassembleAll || PrintSource || PrintLines || TracebackTable || |
3664 | !DisassembleSymbols.empty()) |
3665 | Disassemble = true; |
3666 | |
3667 | if (!ArchiveHeaders && !Disassemble && DwarfDumpType == DIDT_Null && |
3668 | !DynamicRelocations && !FileHeaders && !PrivateHeaders && !RawClangAST && |
3669 | !Relocations && !SectionHeaders && !SectionContents && !SymbolTable && |
3670 | !DynamicSymbolTable && !UnwindInfo && !FaultMapSection && !Offloading && |
3671 | !(MachOOpt && |
3672 | (Bind || DataInCode || ChainedFixups || DyldInfo || DylibId || |
3673 | DylibsUsed || ExportsTrie || FirstPrivateHeader || |
3674 | FunctionStartsType != FunctionStartsMode::None || IndirectSymbols || |
3675 | InfoPlist || LazyBind || LinkOptHints || ObjcMetaData || Rebase || |
3676 | Rpaths || UniversalHeaders || WeakBind || !FilterSections.empty()))) { |
3677 | T->printHelp(Argv0: ToolName); |
3678 | return 2; |
3679 | } |
3680 | |
3681 | DisasmSymbolSet.insert(begin: DisassembleSymbols.begin(), end: DisassembleSymbols.end()); |
3682 | |
3683 | llvm::for_each(Range&: InputFilenames, F: dumpInput); |
3684 | |
3685 | warnOnNoMatchForSections(); |
3686 | |
3687 | return EXIT_SUCCESS; |
3688 | } |
3689 | |