1//===- llvm-readobj.cpp - Dump contents of an Object File -----------------===//
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 is a tool similar to readelf, except it works on multiple object file
10// formats. The main purpose of this tool is to provide detailed output suitable
11// for FileCheck.
12//
13// Flags should be similar to readelf where supported, but the output format
14// does not need to be identical. The point is to not make users learn yet
15// another set of flags.
16//
17// Output should be specialized for each format where appropriate.
18//
19//===----------------------------------------------------------------------===//
20
21#include "llvm-readobj.h"
22#include "ObjDumper.h"
23#include "WindowsResourceDumper.h"
24#include "llvm/DebugInfo/CodeView/GlobalTypeTableBuilder.h"
25#include "llvm/DebugInfo/CodeView/MergingTypeTableBuilder.h"
26#include "llvm/MC/TargetRegistry.h"
27#include "llvm/Object/Archive.h"
28#include "llvm/Object/COFFImportFile.h"
29#include "llvm/Object/ELFObjectFile.h"
30#include "llvm/Object/MachOUniversal.h"
31#include "llvm/Object/ObjectFile.h"
32#include "llvm/Object/Wasm.h"
33#include "llvm/Object/WindowsResource.h"
34#include "llvm/Object/XCOFFObjectFile.h"
35#include "llvm/Option/Arg.h"
36#include "llvm/Option/ArgList.h"
37#include "llvm/Option/Option.h"
38#include "llvm/Support/Casting.h"
39#include "llvm/Support/CommandLine.h"
40#include "llvm/Support/Debug.h"
41#include "llvm/Support/Driver.h"
42#include "llvm/Support/Errc.h"
43#include "llvm/Support/Path.h"
44#include "llvm/Support/ScopedPrinter.h"
45#include "llvm/Support/WithColor.h"
46
47using namespace llvm;
48using namespace llvm::object;
49
50namespace {
51using namespace llvm::opt; // for HelpHidden in Opts.inc
52enum ID {
53 OPT_INVALID = 0, // This is not an option ID.
54#define OPTION(...) LLVM_MAKE_OPT_ID(__VA_ARGS__),
55#include "Opts.inc"
56#undef OPTION
57};
58
59#define OPTTABLE_CODE
60#include "Opts.inc"
61
62class ReadobjOptTable : public opt::OptTable {
63public:
64 ReadobjOptTable() : opt::OptTable(optionTables()) {
65 setGroupedShortOptions(true);
66 }
67};
68
69enum OutputFormatTy { bsd, sysv, posix, darwin, just_symbols };
70
71enum SortSymbolKeyTy {
72 NAME = 0,
73 TYPE = 1,
74 UNKNOWN = 100,
75 // TODO: add ADDRESS, SIZE as needed.
76};
77
78} // namespace
79
80namespace opts {
81static bool Addrsig;
82static bool All;
83static bool ArchSpecificInfo;
84static bool BBAddrMap;
85static bool PrettyPGOAnalysisMap;
86bool ExpandRelocs;
87static bool CallGraphInfo;
88static bool CGProfile;
89static bool Decompress;
90bool Demangle;
91static bool DependentLibraries;
92static bool DynRelocs;
93static bool DynamicSymbols;
94static bool ExtraSymInfo;
95static bool FileHeaders;
96static bool Headers;
97static std::vector<std::string> HexDump;
98static bool PrettyPrint;
99static bool PrintStackMap;
100static bool PrintStackSizes;
101static bool Relocations;
102bool SectionData;
103static bool SectionDetails;
104static bool SectionHeaders;
105bool SectionRelocations;
106bool SectionSymbols;
107static std::vector<std::string> StringDump;
108static bool StringTable;
109static bool Symbols;
110static bool UnwindInfo;
111bool UnwindShowWODPool;
112static cl::boolOrDefault SectionMapping;
113static SmallVector<SortSymbolKeyTy> SortKeys;
114
115// ELF specific options.
116static bool DynamicTable;
117static bool ELFLinkerOptions;
118static bool GnuHashTable;
119static bool HashSymbols;
120static bool HashTable;
121static bool HashHistogram;
122static bool Memtag;
123static bool NeededLibraries;
124static bool Notes;
125static bool Offloading;
126static bool ProgramHeaders;
127static bool SectionGroups;
128static std::vector<std::string> SFrame;
129static bool VersionInfo;
130
131// Mach-O specific options.
132static bool MachODataInCode;
133static bool MachODysymtab;
134static bool MachOIndirectSymbols;
135static bool MachOLinkerOptions;
136static bool MachOSegment;
137static bool MachOVersionMin;
138static bool MachOTargetTriple;
139
140// PE/COFF specific options.
141static bool CodeView;
142static bool CodeViewEnableGHash;
143static bool CodeViewMergedTypes;
144bool CodeViewSubsectionBytes;
145static bool COFFBaseRelocs;
146static bool COFFPseudoRelocs;
147static bool COFFDebugDirectory;
148static bool COFFDirectives;
149static bool COFFExports;
150static bool COFFImports;
151static bool COFFLoadConfig;
152static bool COFFResources;
153static bool COFFTLSDirectory;
154
155// XCOFF specific options.
156static bool XCOFFAuxiliaryHeader;
157static bool XCOFFLoaderSectionHeader;
158static bool XCOFFLoaderSectionSymbol;
159static bool XCOFFLoaderSectionRelocation;
160static bool XCOFFExceptionSection;
161
162OutputStyleTy Output = OutputStyleTy::LLVM;
163static std::vector<std::string> InputFilenames;
164} // namespace opts
165
166static StringRef ToolName;
167
168namespace llvm {
169
170[[noreturn]] static void error(Twine Msg) {
171 // Flush the standard output to print the error at a
172 // proper place.
173 fouts().flush();
174 WithColor::error(OS&: errs(), Prefix: ToolName) << Msg << "\n";
175 exit(status: 1);
176}
177
178[[noreturn]] void reportError(Error Err, StringRef Input) {
179 assert(Err);
180 if (Input == "-")
181 Input = "<stdin>";
182 handleAllErrors(E: createFileError(F: Input, E: std::move(Err)),
183 Handlers: [&](const ErrorInfoBase &EI) { error(Msg: EI.message()); });
184 llvm_unreachable("error() call should never return");
185}
186
187void reportWarning(Error Err, StringRef Input) {
188 assert(Err);
189 if (Input == "-")
190 Input = "<stdin>";
191
192 // Flush the standard output to print the warning at a
193 // proper place.
194 fouts().flush();
195 handleAllErrors(
196 E: createFileError(F: Input, E: std::move(Err)), Handlers: [&](const ErrorInfoBase &EI) {
197 WithColor::warning(OS&: errs(), Prefix: ToolName) << EI.message() << "\n";
198 });
199}
200
201} // namespace llvm
202
203static void parseOptions(const opt::InputArgList &Args) {
204 opts::Addrsig = Args.hasArg(Ids: OPT_addrsig);
205 opts::All = Args.hasArg(Ids: OPT_all);
206 opts::ArchSpecificInfo = Args.hasArg(Ids: OPT_arch_specific);
207 opts::BBAddrMap = Args.hasArg(Ids: OPT_bb_addr_map);
208 opts::PrettyPGOAnalysisMap = Args.hasArg(Ids: OPT_pretty_pgo_analysis_map);
209 if (opts::PrettyPGOAnalysisMap && !opts::BBAddrMap)
210 WithColor::warning(OS&: errs(), Prefix: ToolName)
211 << "--bb-addr-map must be enabled for --pretty-pgo-analysis-map to "
212 "have an effect\n";
213 opts::CallGraphInfo = Args.hasArg(Ids: OPT_call_graph_info);
214 opts::CGProfile = Args.hasArg(Ids: OPT_cg_profile);
215 opts::Decompress = Args.hasArg(Ids: OPT_decompress);
216 opts::Demangle = Args.hasFlag(Pos: OPT_demangle, Neg: OPT_no_demangle, Default: false);
217 opts::DependentLibraries = Args.hasArg(Ids: OPT_dependent_libraries);
218 opts::DynRelocs = Args.hasArg(Ids: OPT_dyn_relocations);
219 opts::DynamicSymbols = Args.hasArg(Ids: OPT_dyn_syms);
220 opts::ExpandRelocs = Args.hasArg(Ids: OPT_expand_relocs);
221 opts::ExtraSymInfo = Args.hasArg(Ids: OPT_extra_sym_info);
222 opts::FileHeaders = Args.hasArg(Ids: OPT_file_header);
223 opts::Headers = Args.hasArg(Ids: OPT_headers);
224 opts::HexDump = Args.getAllArgValues(Id: OPT_hex_dump_EQ);
225 opts::Relocations = Args.hasArg(Ids: OPT_relocs);
226 opts::SectionData = Args.hasArg(Ids: OPT_section_data);
227 opts::SectionDetails = Args.hasArg(Ids: OPT_section_details);
228 opts::SectionHeaders = Args.hasArg(Ids: OPT_section_headers);
229 opts::SectionRelocations = Args.hasArg(Ids: OPT_section_relocations);
230 opts::SectionSymbols = Args.hasArg(Ids: OPT_section_symbols);
231 if (Args.hasArg(Ids: OPT_section_mapping))
232 opts::SectionMapping = cl::boolOrDefault::BOU_TRUE;
233 else if (Args.hasArg(Ids: OPT_section_mapping_EQ_false))
234 opts::SectionMapping = cl::boolOrDefault::BOU_FALSE;
235 else
236 opts::SectionMapping = cl::boolOrDefault::BOU_UNSET;
237 opts::PrintStackSizes = Args.hasArg(Ids: OPT_stack_sizes);
238 opts::PrintStackMap = Args.hasArg(Ids: OPT_stackmap);
239 opts::StringDump = Args.getAllArgValues(Id: OPT_string_dump_EQ);
240 opts::StringTable = Args.hasArg(Ids: OPT_string_table);
241 opts::Symbols = Args.hasArg(Ids: OPT_symbols);
242 opts::UnwindInfo = Args.hasArg(Ids: OPT_unwind);
243 opts::UnwindShowWODPool = Args.hasArg(Ids: OPT_unwind_show_wod_pool);
244
245 // ELF specific options.
246 opts::DynamicTable = Args.hasArg(Ids: OPT_dynamic_table);
247 opts::ELFLinkerOptions = Args.hasArg(Ids: OPT_elf_linker_options);
248 if (Arg *A = Args.getLastArg(Ids: OPT_elf_output_style_EQ)) {
249 std::string OutputStyleChoice = A->getValue();
250 opts::Output = StringSwitch<opts::OutputStyleTy>(OutputStyleChoice)
251 .Case(S: "LLVM", Value: opts::OutputStyleTy::LLVM)
252 .Case(S: "GNU", Value: opts::OutputStyleTy::GNU)
253 .Case(S: "JSON", Value: opts::OutputStyleTy::JSON)
254 .Default(Value: opts::OutputStyleTy::UNKNOWN);
255 if (opts::Output == opts::OutputStyleTy::UNKNOWN) {
256 error(Msg: "--elf-output-style value should be either 'LLVM', 'GNU', or "
257 "'JSON', but was '" +
258 OutputStyleChoice + "'");
259 }
260 }
261 opts::GnuHashTable = Args.hasArg(Ids: OPT_gnu_hash_table);
262 opts::HashSymbols = Args.hasArg(Ids: OPT_hash_symbols);
263 opts::HashTable = Args.hasArg(Ids: OPT_hash_table);
264 opts::HashHistogram = Args.hasArg(Ids: OPT_histogram);
265 opts::Memtag = Args.hasArg(Ids: OPT_memtag);
266 opts::NeededLibraries = Args.hasArg(Ids: OPT_needed_libs);
267 opts::Notes = Args.hasArg(Ids: OPT_notes);
268 opts::Offloading = Args.hasArg(Ids: OPT_offloading);
269 opts::PrettyPrint = Args.hasArg(Ids: OPT_pretty_print);
270 opts::ProgramHeaders = Args.hasArg(Ids: OPT_program_headers);
271 opts::SectionGroups = Args.hasArg(Ids: OPT_section_groups);
272 opts::SFrame = Args.getAllArgValues(Id: OPT_sframe_EQ);
273 if (Arg *A = Args.getLastArg(Ids: OPT_sort_symbols_EQ)) {
274 for (StringRef KeyStr : llvm::split(Str: A->getValue(), Separator: ",")) {
275 SortSymbolKeyTy KeyType = StringSwitch<SortSymbolKeyTy>(KeyStr)
276 .Case(S: "name", Value: SortSymbolKeyTy::NAME)
277 .Case(S: "type", Value: SortSymbolKeyTy::TYPE)
278 .Default(Value: SortSymbolKeyTy::UNKNOWN);
279 if (KeyType == SortSymbolKeyTy::UNKNOWN)
280 error(Msg: "--sort-symbols value should be 'name' or 'type', but was '" +
281 Twine(KeyStr) + "'");
282 opts::SortKeys.push_back(Elt: KeyType);
283 }
284 }
285 opts::VersionInfo = Args.hasArg(Ids: OPT_version_info);
286
287 // Mach-O specific options.
288 opts::MachODataInCode = Args.hasArg(Ids: OPT_macho_data_in_code);
289 opts::MachODysymtab = Args.hasArg(Ids: OPT_macho_dysymtab);
290 opts::MachOIndirectSymbols = Args.hasArg(Ids: OPT_macho_indirect_symbols);
291 opts::MachOLinkerOptions = Args.hasArg(Ids: OPT_macho_linker_options);
292 opts::MachOSegment = Args.hasArg(Ids: OPT_macho_segment);
293 opts::MachOVersionMin = Args.hasArg(Ids: OPT_macho_version_min);
294 opts::MachOTargetTriple = Args.hasArg(Ids: OPT_macho_target_triple);
295
296 // PE/COFF specific options.
297 opts::CodeView = Args.hasArg(Ids: OPT_codeview);
298 opts::CodeViewEnableGHash = Args.hasArg(Ids: OPT_codeview_ghash);
299 opts::CodeViewMergedTypes = Args.hasArg(Ids: OPT_codeview_merged_types);
300 opts::CodeViewSubsectionBytes = Args.hasArg(Ids: OPT_codeview_subsection_bytes);
301 opts::COFFBaseRelocs = Args.hasArg(Ids: OPT_coff_basereloc);
302 opts::COFFPseudoRelocs = Args.hasArg(Ids: OPT_coff_pseudoreloc);
303 opts::COFFDebugDirectory = Args.hasArg(Ids: OPT_coff_debug_directory);
304 opts::COFFDirectives = Args.hasArg(Ids: OPT_coff_directives);
305 opts::COFFExports = Args.hasArg(Ids: OPT_coff_exports);
306 opts::COFFImports = Args.hasArg(Ids: OPT_coff_imports);
307 opts::COFFLoadConfig = Args.hasArg(Ids: OPT_coff_load_config);
308 opts::COFFResources = Args.hasArg(Ids: OPT_coff_resources);
309 opts::COFFTLSDirectory = Args.hasArg(Ids: OPT_coff_tls_directory);
310
311 // XCOFF specific options.
312 opts::XCOFFAuxiliaryHeader = Args.hasArg(Ids: OPT_auxiliary_header);
313 opts::XCOFFLoaderSectionHeader = Args.hasArg(Ids: OPT_loader_section_header);
314 opts::XCOFFLoaderSectionSymbol = Args.hasArg(Ids: OPT_loader_section_symbols);
315 opts::XCOFFLoaderSectionRelocation =
316 Args.hasArg(Ids: OPT_loader_section_relocations);
317 opts::XCOFFExceptionSection = Args.hasArg(Ids: OPT_exception_section);
318
319 opts::InputFilenames = Args.getAllArgValues(Id: OPT_INPUT);
320}
321
322namespace {
323struct ReadObjTypeTableBuilder {
324 ReadObjTypeTableBuilder()
325 : IDTable(Allocator), TypeTable(Allocator), GlobalIDTable(Allocator),
326 GlobalTypeTable(Allocator) {}
327
328 llvm::BumpPtrAllocator Allocator;
329 llvm::codeview::MergingTypeTableBuilder IDTable;
330 llvm::codeview::MergingTypeTableBuilder TypeTable;
331 llvm::codeview::GlobalTypeTableBuilder GlobalIDTable;
332 llvm::codeview::GlobalTypeTableBuilder GlobalTypeTable;
333 std::vector<OwningBinary<Binary>> Binaries;
334};
335} // namespace
336static ReadObjTypeTableBuilder CVTypes;
337
338/// Creates an format-specific object file dumper.
339static Expected<std::unique_ptr<ObjDumper>>
340createDumper(const ObjectFile &Obj, ScopedPrinter &Writer) {
341 if (const COFFObjectFile *COFFObj = dyn_cast<COFFObjectFile>(Val: &Obj))
342 return createCOFFDumper(Obj: *COFFObj, Writer);
343
344 if (const ELFObjectFileBase *ELFObj = dyn_cast<ELFObjectFileBase>(Val: &Obj))
345 return createELFDumper(Obj: *ELFObj, Writer);
346
347 if (const MachOObjectFile *MachOObj = dyn_cast<MachOObjectFile>(Val: &Obj))
348 return createMachODumper(Obj: *MachOObj, Writer);
349
350 if (const WasmObjectFile *WasmObj = dyn_cast<WasmObjectFile>(Val: &Obj))
351 return createWasmDumper(Obj: *WasmObj, Writer);
352
353 if (const XCOFFObjectFile *XObj = dyn_cast<XCOFFObjectFile>(Val: &Obj))
354 return createXCOFFDumper(Obj: *XObj, Writer);
355
356 return createStringError(EC: errc::invalid_argument,
357 S: "unsupported object file format");
358}
359
360/// Dumps the specified object file.
361static void dumpObject(ObjectFile &Obj, ScopedPrinter &Writer,
362 const Archive *A = nullptr) {
363 std::string FileStr =
364 A ? Twine(A->getFileName() + "(" + Obj.getFileName() + ")").str()
365 : Obj.getFileName().str();
366
367 std::string ContentErrString;
368 if (Error ContentErr = Obj.initContent())
369 ContentErrString = "unable to continue dumping, the file is corrupt: " +
370 toString(E: std::move(ContentErr));
371
372 ObjDumper *Dumper;
373 std::optional<SymbolComparator> SymComp;
374 Expected<std::unique_ptr<ObjDumper>> DumperOrErr = createDumper(Obj, Writer);
375 if (!DumperOrErr)
376 reportError(Err: DumperOrErr.takeError(), Input: FileStr);
377 Dumper = (*DumperOrErr).get();
378
379 if (!opts::SortKeys.empty()) {
380 if (Dumper->canCompareSymbols()) {
381 SymComp = SymbolComparator();
382 for (SortSymbolKeyTy Key : opts::SortKeys) {
383 switch (Key) {
384 case NAME:
385 SymComp->addPredicate(Pred: [Dumper](SymbolRef LHS, SymbolRef RHS) {
386 return Dumper->compareSymbolsByName(LHS, RHS);
387 });
388 break;
389 case TYPE:
390 SymComp->addPredicate(Pred: [Dumper](SymbolRef LHS, SymbolRef RHS) {
391 return Dumper->compareSymbolsByType(LHS, RHS);
392 });
393 break;
394 case UNKNOWN:
395 llvm_unreachable("Unsupported sort key");
396 }
397 }
398
399 } else {
400 reportWarning(Err: createStringError(
401 EC: errc::invalid_argument,
402 S: "--sort-symbols is not supported yet for this format"),
403 Input: FileStr);
404 }
405 }
406 Dumper->printFileSummary(FileStr, Obj, InputFilenames: opts::InputFilenames, A);
407
408 if (opts::FileHeaders)
409 Dumper->printFileHeaders();
410
411 // Auxiliary header in XOCFF is right after the file header, so print the data
412 // here.
413 if (Obj.isXCOFF() && opts::XCOFFAuxiliaryHeader)
414 Dumper->printAuxiliaryHeader();
415
416 // This is only used for ELF currently. In some cases, when an object is
417 // corrupt (e.g. truncated), we can't dump anything except the file header.
418 if (!ContentErrString.empty())
419 reportError(Err: createError(Err: ContentErrString), Input: FileStr);
420
421 if (opts::SectionDetails || opts::SectionHeaders) {
422 if (opts::Output == opts::GNU && opts::SectionDetails)
423 Dumper->printSectionDetails();
424 else
425 Dumper->printSectionHeaders();
426 }
427
428 if (opts::HashSymbols)
429 Dumper->printHashSymbols();
430 if (opts::ProgramHeaders ||
431 opts::SectionMapping == cl::boolOrDefault::BOU_TRUE)
432 Dumper->printProgramHeaders(PrintProgramHeaders: opts::ProgramHeaders, PrintSectionMapping: opts::SectionMapping);
433 if (opts::DynamicTable)
434 Dumper->printDynamicTable();
435 if (opts::NeededLibraries)
436 Dumper->printNeededLibraries();
437 if (opts::Relocations)
438 Dumper->printRelocations();
439 if (opts::DynRelocs)
440 Dumper->printDynamicRelocations();
441 if (opts::UnwindInfo)
442 Dumper->printUnwindInfo();
443 if (opts::Symbols || opts::DynamicSymbols)
444 Dumper->printSymbols(PrintSymbols: opts::Symbols, PrintDynamicSymbols: opts::DynamicSymbols,
445 ExtraSymInfo: opts::ExtraSymInfo, SymComp);
446 if (!opts::StringDump.empty())
447 Dumper->printSectionsAsString(Obj, Sections: opts::StringDump, Decompress: opts::Decompress);
448 if (!opts::HexDump.empty())
449 Dumper->printSectionsAsHex(Obj, Sections: opts::HexDump, Decompress: opts::Decompress);
450 if (opts::HashTable)
451 Dumper->printHashTable();
452 if (opts::GnuHashTable)
453 Dumper->printGnuHashTable();
454 if (opts::VersionInfo)
455 Dumper->printVersionInfo();
456 if (opts::Offloading)
457 Dumper->printOffloading(Obj);
458 if (opts::StringTable)
459 Dumper->printStringTable();
460 if (Obj.isELF()) {
461 if (opts::DependentLibraries)
462 Dumper->printDependentLibs();
463 if (opts::ELFLinkerOptions)
464 Dumper->printELFLinkerOptions();
465 if (opts::ArchSpecificInfo)
466 Dumper->printArchSpecificInfo();
467 if (opts::SectionGroups)
468 Dumper->printGroupSections();
469 if (opts::HashHistogram)
470 Dumper->printHashHistograms();
471 if (opts::CGProfile)
472 Dumper->printCGProfile();
473 if (opts::CallGraphInfo)
474 Dumper->printCallGraphInfo();
475 if (opts::BBAddrMap)
476 Dumper->printBBAddrMaps(PrettyPGOAnalysis: opts::PrettyPGOAnalysisMap);
477 if (opts::Addrsig)
478 Dumper->printAddrsig();
479 if (opts::Notes)
480 Dumper->printNotes();
481 if (opts::Memtag)
482 Dumper->printMemtag();
483 if (!opts::SFrame.empty())
484 Dumper->printSectionsAsSFrame(Sections: opts::SFrame);
485 }
486 if (Obj.isCOFF()) {
487 if (opts::COFFImports)
488 Dumper->printCOFFImports();
489 if (opts::COFFExports)
490 Dumper->printCOFFExports();
491 if (opts::COFFDirectives)
492 Dumper->printCOFFDirectives();
493 if (opts::COFFBaseRelocs)
494 Dumper->printCOFFBaseReloc();
495 if (opts::COFFPseudoRelocs)
496 Dumper->printCOFFPseudoReloc();
497 if (opts::COFFDebugDirectory)
498 Dumper->printCOFFDebugDirectory();
499 if (opts::COFFTLSDirectory)
500 Dumper->printCOFFTLSDirectory();
501 if (opts::COFFResources)
502 Dumper->printCOFFResources();
503 if (opts::COFFLoadConfig)
504 Dumper->printCOFFLoadConfig();
505 if (opts::CGProfile)
506 Dumper->printCGProfile();
507 if (opts::Addrsig)
508 Dumper->printAddrsig();
509 if (opts::CodeView)
510 Dumper->printCodeViewDebugInfo();
511 if (opts::CodeViewMergedTypes)
512 Dumper->mergeCodeViewTypes(CVIDs&: CVTypes.IDTable, CVTypes&: CVTypes.TypeTable,
513 GlobalCVIDs&: CVTypes.GlobalIDTable, GlobalCVTypes&: CVTypes.GlobalTypeTable,
514 GHash: opts::CodeViewEnableGHash);
515 }
516 if (Obj.isMachO()) {
517 if (opts::MachODataInCode)
518 Dumper->printMachODataInCode();
519 if (opts::MachOIndirectSymbols)
520 Dumper->printMachOIndirectSymbols();
521 if (opts::MachOLinkerOptions)
522 Dumper->printMachOLinkerOptions();
523 if (opts::MachOSegment)
524 Dumper->printMachOSegment();
525 if (opts::MachOVersionMin)
526 Dumper->printMachOVersionMin();
527 if (opts::MachOTargetTriple)
528 Dumper->printMachOTargetTriple();
529 if (opts::MachODysymtab)
530 Dumper->printMachODysymtab();
531 if (opts::CGProfile)
532 Dumper->printCGProfile();
533 }
534
535 if (Obj.isXCOFF()) {
536 if (opts::XCOFFLoaderSectionHeader || opts::XCOFFLoaderSectionSymbol ||
537 opts::XCOFFLoaderSectionRelocation)
538 Dumper->printLoaderSection(PrintHeader: opts::XCOFFLoaderSectionHeader,
539 PrintSymbols: opts::XCOFFLoaderSectionSymbol,
540 PrintRelocations: opts::XCOFFLoaderSectionRelocation);
541
542 if (opts::XCOFFExceptionSection)
543 Dumper->printExceptionSection();
544 }
545
546 if (opts::PrintStackMap)
547 Dumper->printStackMap();
548 if (opts::PrintStackSizes)
549 Dumper->printStackSizes();
550}
551
552/// Dumps each object file in \a Arc;
553static void dumpArchive(const Archive *Arc, ScopedPrinter &Writer) {
554 Error Err = Error::success();
555 for (auto &Child : Arc->children(Err)) {
556 Expected<std::unique_ptr<Binary>> ChildOrErr = Child.getAsBinary();
557 if (!ChildOrErr) {
558 if (auto E = isNotObjectErrorInvalidFileType(Err: ChildOrErr.takeError()))
559 reportError(Err: std::move(E), Input: Arc->getFileName());
560 continue;
561 }
562
563 Binary *Bin = ChildOrErr->get();
564 if (ObjectFile *Obj = dyn_cast<ObjectFile>(Val: Bin))
565 dumpObject(Obj&: *Obj, Writer, A: Arc);
566 else if (COFFImportFile *Imp = dyn_cast<COFFImportFile>(Val: Bin))
567 dumpCOFFImportFile(File: Imp, Writer);
568 else
569 reportWarning(Err: createStringError(EC: errc::invalid_argument,
570 S: Bin->getFileName() +
571 " has an unsupported file type"),
572 Input: Arc->getFileName());
573 }
574 if (Err)
575 reportError(Err: std::move(Err), Input: Arc->getFileName());
576}
577
578/// Dumps each object file in \a MachO Universal Binary;
579static void dumpMachOUniversalBinary(const MachOUniversalBinary *UBinary,
580 ScopedPrinter &Writer) {
581 for (const MachOUniversalBinary::ObjectForArch &Obj : UBinary->objects()) {
582 Expected<std::unique_ptr<MachOObjectFile>> ObjOrErr = Obj.getAsObjectFile();
583 if (ObjOrErr)
584 dumpObject(Obj&: *ObjOrErr.get(), Writer);
585 else if (auto E = isNotObjectErrorInvalidFileType(Err: ObjOrErr.takeError()))
586 reportError(Err: ObjOrErr.takeError(), Input: UBinary->getFileName());
587 else if (Expected<std::unique_ptr<Archive>> AOrErr = Obj.getAsArchive())
588 dumpArchive(Arc: &*AOrErr.get(), Writer);
589 }
590}
591
592/// Dumps \a COFF file;
593static void dumpCOFFObject(COFFObjectFile *Obj, ScopedPrinter &Writer) {
594 dumpObject(Obj&: *Obj, Writer);
595
596 // Dump a hybrid object when available.
597 MemoryBufferRef HybridView;
598 std::unique_ptr<MemoryBuffer> HybridViewBuf;
599 if (std::optional<MemoryBufferRef> HybridSec = Obj->findHybridObjectSection())
600 HybridView = *HybridSec;
601 else if ((HybridViewBuf = Obj->getHybridObjectView()))
602 HybridView = HybridViewBuf->getMemBufferRef();
603 else
604 return;
605 Expected<std::unique_ptr<COFFObjectFile>> HybridObjOrErr =
606 COFFObjectFile::create(Object: HybridView);
607 if (!HybridObjOrErr)
608 reportError(Err: HybridObjOrErr.takeError(), Input: Obj->getFileName().str());
609 DictScope D(Writer, "HybridObject");
610 dumpObject(Obj&: **HybridObjOrErr, Writer);
611}
612
613/// Dumps \a WinRes, Windows Resource (.res) file;
614static void dumpWindowsResourceFile(WindowsResource *WinRes,
615 ScopedPrinter &Printer) {
616 WindowsRes::Dumper Dumper(WinRes, Printer);
617 if (auto Err = Dumper.printData())
618 reportError(Err: std::move(Err), Input: WinRes->getFileName());
619}
620
621
622/// Opens \a File and dumps it.
623static void dumpInput(StringRef File, ScopedPrinter &Writer) {
624 ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
625 MemoryBuffer::getFileOrSTDIN(Filename: File, /*IsText=*/false,
626 /*RequiresNullTerminator=*/false);
627 if (std::error_code EC = FileOrErr.getError())
628 return reportError(Err: errorCodeToError(EC), Input: File);
629
630 std::unique_ptr<MemoryBuffer> &Buffer = FileOrErr.get();
631 file_magic Type = identify_magic(magic: Buffer->getBuffer());
632 if (Type == file_magic::bitcode) {
633 reportWarning(Err: createStringError(EC: errc::invalid_argument,
634 S: "bitcode files are not supported"),
635 Input: File);
636 return;
637 }
638
639 Expected<std::unique_ptr<Binary>> BinaryOrErr = createBinary(
640 Source: Buffer->getMemBufferRef(), /*Context=*/nullptr, /*InitContent=*/false);
641 if (!BinaryOrErr)
642 reportError(Err: BinaryOrErr.takeError(), Input: File);
643
644 std::unique_ptr<Binary> Bin = std::move(*BinaryOrErr);
645 if (Archive *Arc = dyn_cast<Archive>(Val: Bin.get()))
646 dumpArchive(Arc, Writer);
647 else if (MachOUniversalBinary *UBinary =
648 dyn_cast<MachOUniversalBinary>(Val: Bin.get()))
649 dumpMachOUniversalBinary(UBinary, Writer);
650 else if (COFFObjectFile *Obj = dyn_cast<COFFObjectFile>(Val: Bin.get()))
651 dumpCOFFObject(Obj, Writer);
652 else if (ObjectFile *Obj = dyn_cast<ObjectFile>(Val: Bin.get()))
653 dumpObject(Obj&: *Obj, Writer);
654 else if (COFFImportFile *Import = dyn_cast<COFFImportFile>(Val: Bin.get()))
655 dumpCOFFImportFile(File: Import, Writer);
656 else if (WindowsResource *WinRes = dyn_cast<WindowsResource>(Val: Bin.get()))
657 dumpWindowsResourceFile(WinRes, Printer&: Writer);
658 else
659 llvm_unreachable("unrecognized file type");
660
661 CVTypes.Binaries.push_back(
662 x: OwningBinary<Binary>(std::move(Bin), std::move(Buffer)));
663}
664
665std::unique_ptr<ScopedPrinter> createWriter() {
666 if (opts::Output == opts::JSON)
667 return std::make_unique<JSONScopedPrinter>(
668 args&: fouts(), args: opts::PrettyPrint ? 2 : 0, args: std::make_unique<ListScope>());
669 return std::make_unique<ScopedPrinter>(args&: fouts());
670}
671
672int llvm_readobj_main(int argc, char **argv, const llvm::ToolContext &) {
673 BumpPtrAllocator A;
674 StringSaver Saver(A);
675 ReadobjOptTable Tbl;
676 ToolName = argv[0];
677 opt::InputArgList Args =
678 Tbl.parseArgs(Argc: argc, Argv: argv, Unknown: OPT_UNKNOWN, Saver, ErrorFn: [&](StringRef Msg) {
679 error(Msg);
680 exit(status: 1);
681 });
682 if (Args.hasArg(Ids: OPT_help)) {
683 Tbl.printHelp(
684 OS&: outs(),
685 Usage: (Twine(ToolName) + " [options] <input object files>").str().c_str(),
686 Title: "LLVM Object Reader");
687 // TODO Replace this with OptTable API once it adds extrahelp support.
688 outs() << "\nPass @FILE as argument to read options from FILE.\n";
689 return 0;
690 }
691 if (Args.hasArg(Ids: OPT_version)) {
692 cl::PrintVersionMessage();
693 return 0;
694 }
695
696 if (sys::path::stem(path: argv[0]).contains(Other: "readelf"))
697 opts::Output = opts::GNU;
698 parseOptions(Args);
699
700 // Default to print error if no filename is specified.
701 if (opts::InputFilenames.empty()) {
702 error(Msg: "no input files specified");
703 }
704
705 if (opts::All) {
706 opts::FileHeaders = true;
707 opts::XCOFFAuxiliaryHeader = true;
708 opts::ProgramHeaders = true;
709 opts::SectionHeaders = true;
710 opts::Symbols = true;
711 opts::Relocations = true;
712 opts::DynamicTable = true;
713 opts::Notes = true;
714 opts::VersionInfo = true;
715 opts::Offloading = true;
716 opts::UnwindInfo = true;
717 opts::SectionGroups = true;
718 opts::HashHistogram = true;
719 if (opts::Output == opts::LLVM) {
720 opts::Addrsig = true;
721 opts::PrintStackSizes = true;
722 }
723 opts::Memtag = true;
724 }
725
726 if (opts::Headers) {
727 opts::FileHeaders = true;
728 opts::XCOFFAuxiliaryHeader = true;
729 opts::ProgramHeaders = true;
730 opts::SectionHeaders = true;
731 }
732
733 std::unique_ptr<ScopedPrinter> Writer = createWriter();
734
735 for (const std::string &I : opts::InputFilenames)
736 dumpInput(File: I, Writer&: *Writer);
737
738 if (opts::CodeViewMergedTypes) {
739 if (opts::CodeViewEnableGHash)
740 dumpCodeViewMergedTypes(Writer&: *Writer, IpiRecords: CVTypes.GlobalIDTable.records(),
741 TpiRecords: CVTypes.GlobalTypeTable.records());
742 else
743 dumpCodeViewMergedTypes(Writer&: *Writer, IpiRecords: CVTypes.IDTable.records(),
744 TpiRecords: CVTypes.TypeTable.records());
745 }
746
747 return 0;
748}
749