Bug Summary

File:include/llvm/Support/Error.h
Warning:line 201, column 5
Potential leak of memory pointed to by 'Payload._M_t._M_head_impl'

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name llvm-objdump.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -mrelocation-model pic -pic-level 2 -mthread-model posix -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-8/lib/clang/8.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-8~svn345461/build-llvm/tools/llvm-objdump -I /build/llvm-toolchain-snapshot-8~svn345461/tools/llvm-objdump -I /build/llvm-toolchain-snapshot-8~svn345461/build-llvm/include -I /build/llvm-toolchain-snapshot-8~svn345461/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/include/clang/8.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-8/lib/clang/8.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-8~svn345461/build-llvm/tools/llvm-objdump -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-10-27-211344-32123-1 -x c++ /build/llvm-toolchain-snapshot-8~svn345461/tools/llvm-objdump/llvm-objdump.cpp -faddrsig

/build/llvm-toolchain-snapshot-8~svn345461/tools/llvm-objdump/llvm-objdump.cpp

1//===-- llvm-objdump.cpp - Object file dumping utility for llvm -----------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This program is a utility that works like binutils "objdump", that is, it
11// dumps out a plethora of information about an object file depending on the
12// flags.
13//
14// The flags and output of this program should be near identical to those of
15// binutils objdump.
16//
17//===----------------------------------------------------------------------===//
18
19#include "llvm-objdump.h"
20#include "llvm/ADT/Optional.h"
21#include "llvm/ADT/STLExtras.h"
22#include "llvm/ADT/StringExtras.h"
23#include "llvm/ADT/StringSet.h"
24#include "llvm/ADT/Triple.h"
25#include "llvm/CodeGen/FaultMaps.h"
26#include "llvm/DebugInfo/DWARF/DWARFContext.h"
27#include "llvm/DebugInfo/Symbolize/Symbolize.h"
28#include "llvm/Demangle/Demangle.h"
29#include "llvm/MC/MCAsmInfo.h"
30#include "llvm/MC/MCContext.h"
31#include "llvm/MC/MCDisassembler/MCDisassembler.h"
32#include "llvm/MC/MCDisassembler/MCRelocationInfo.h"
33#include "llvm/MC/MCInst.h"
34#include "llvm/MC/MCInstPrinter.h"
35#include "llvm/MC/MCInstrAnalysis.h"
36#include "llvm/MC/MCInstrInfo.h"
37#include "llvm/MC/MCObjectFileInfo.h"
38#include "llvm/MC/MCRegisterInfo.h"
39#include "llvm/MC/MCSubtargetInfo.h"
40#include "llvm/Object/Archive.h"
41#include "llvm/Object/COFF.h"
42#include "llvm/Object/COFFImportFile.h"
43#include "llvm/Object/ELFObjectFile.h"
44#include "llvm/Object/MachO.h"
45#include "llvm/Object/MachOUniversal.h"
46#include "llvm/Object/ObjectFile.h"
47#include "llvm/Object/Wasm.h"
48#include "llvm/Support/Casting.h"
49#include "llvm/Support/CommandLine.h"
50#include "llvm/Support/Debug.h"
51#include "llvm/Support/Errc.h"
52#include "llvm/Support/FileSystem.h"
53#include "llvm/Support/Format.h"
54#include "llvm/Support/GraphWriter.h"
55#include "llvm/Support/Host.h"
56#include "llvm/Support/InitLLVM.h"
57#include "llvm/Support/MemoryBuffer.h"
58#include "llvm/Support/SourceMgr.h"
59#include "llvm/Support/StringSaver.h"
60#include "llvm/Support/TargetRegistry.h"
61#include "llvm/Support/TargetSelect.h"
62#include "llvm/Support/raw_ostream.h"
63#include <algorithm>
64#include <cctype>
65#include <cstring>
66#include <system_error>
67#include <unordered_map>
68#include <utility>
69
70using namespace llvm;
71using namespace object;
72
73cl::opt<bool>
74 llvm::AllHeaders("all-headers",
75 cl::desc("Display all available header information"));
76static cl::alias AllHeadersShort("x", cl::desc("Alias for --all-headers"),
77 cl::aliasopt(AllHeaders));
78
79static cl::list<std::string>
80InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
81
82cl::opt<bool>
83llvm::Disassemble("disassemble",
84 cl::desc("Display assembler mnemonics for the machine instructions"));
85static cl::alias
86Disassembled("d", cl::desc("Alias for --disassemble"),
87 cl::aliasopt(Disassemble));
88
89cl::opt<bool>
90llvm::DisassembleAll("disassemble-all",
91 cl::desc("Display assembler mnemonics for the machine instructions"));
92static cl::alias
93DisassembleAlld("D", cl::desc("Alias for --disassemble-all"),
94 cl::aliasopt(DisassembleAll));
95
96cl::opt<bool> llvm::Demangle("demangle", cl::desc("Demangle symbols names"),
97 cl::init(false));
98
99static cl::alias DemangleShort("C", cl::desc("Alias for --demangle"),
100 cl::aliasopt(llvm::Demangle));
101
102static cl::list<std::string>
103DisassembleFunctions("df",
104 cl::CommaSeparated,
105 cl::desc("List of functions to disassemble"));
106static StringSet<> DisasmFuncsSet;
107
108cl::opt<bool>
109llvm::Relocations("r", cl::desc("Display the relocation entries in the file"));
110
111cl::opt<bool>
112llvm::DynamicRelocations("dynamic-reloc",
113 cl::desc("Display the dynamic relocation entries in the file"));
114static cl::alias
115DynamicRelocationsd("R", cl::desc("Alias for --dynamic-reloc"),
116 cl::aliasopt(DynamicRelocations));
117
118cl::opt<bool>
119llvm::SectionContents("s", cl::desc("Display the content of each section"));
120
121cl::opt<bool>
122llvm::SymbolTable("t", cl::desc("Display the symbol table"));
123
124cl::opt<bool>
125llvm::ExportsTrie("exports-trie", cl::desc("Display mach-o exported symbols"));
126
127cl::opt<bool>
128llvm::Rebase("rebase", cl::desc("Display mach-o rebasing info"));
129
130cl::opt<bool>
131llvm::Bind("bind", cl::desc("Display mach-o binding info"));
132
133cl::opt<bool>
134llvm::LazyBind("lazy-bind", cl::desc("Display mach-o lazy binding info"));
135
136cl::opt<bool>
137llvm::WeakBind("weak-bind", cl::desc("Display mach-o weak binding info"));
138
139cl::opt<bool>
140llvm::RawClangAST("raw-clang-ast",
141 cl::desc("Dump the raw binary contents of the clang AST section"));
142
143static cl::opt<bool>
144MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
145static cl::alias
146MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt));
147
148cl::opt<std::string>
149llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
150 "see -version for available targets"));
151
152cl::opt<std::string>
153llvm::MCPU("mcpu",
154 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
155 cl::value_desc("cpu-name"),
156 cl::init(""));
157
158cl::opt<std::string>
159llvm::ArchName("arch-name", cl::desc("Target arch to disassemble for, "
160 "see -version for available targets"));
161
162cl::opt<bool>
163llvm::SectionHeaders("section-headers", cl::desc("Display summaries of the "
164 "headers for each section."));
165static cl::alias
166SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
167 cl::aliasopt(SectionHeaders));
168static cl::alias
169SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
170 cl::aliasopt(SectionHeaders));
171
172cl::list<std::string>
173llvm::FilterSections("section", cl::desc("Operate on the specified sections only. "
174 "With -macho dump segment,section"));
175cl::alias
176static FilterSectionsj("j", cl::desc("Alias for --section"),
177 cl::aliasopt(llvm::FilterSections));
178
179cl::list<std::string>
180llvm::MAttrs("mattr",
181 cl::CommaSeparated,
182 cl::desc("Target specific attributes"),
183 cl::value_desc("a1,+a2,-a3,..."));
184
185cl::opt<bool>
186llvm::NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling "
187 "instructions, do not print "
188 "the instruction bytes."));
189cl::opt<bool>
190llvm::NoLeadingAddr("no-leading-addr", cl::desc("Print no leading address"));
191
192cl::opt<bool>
193llvm::UnwindInfo("unwind-info", cl::desc("Display unwind information"));
194
195static cl::alias
196UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
197 cl::aliasopt(UnwindInfo));
198
199cl::opt<bool>
200llvm::PrivateHeaders("private-headers",
201 cl::desc("Display format specific file headers"));
202
203cl::opt<bool>
204llvm::FirstPrivateHeader("private-header",
205 cl::desc("Display only the first format specific file "
206 "header"));
207
208static cl::alias
209PrivateHeadersShort("p", cl::desc("Alias for --private-headers"),
210 cl::aliasopt(PrivateHeaders));
211
212cl::opt<bool> llvm::FileHeaders(
213 "file-headers",
214 cl::desc("Display the contents of the overall file header"));
215
216static cl::alias FileHeadersShort("f", cl::desc("Alias for --file-headers"),
217 cl::aliasopt(FileHeaders));
218
219cl::opt<bool>
220 llvm::ArchiveHeaders("archive-headers",
221 cl::desc("Display archive header information"));
222
223cl::alias
224ArchiveHeadersShort("a", cl::desc("Alias for --archive-headers"),
225 cl::aliasopt(ArchiveHeaders));
226
227cl::opt<bool>
228 llvm::PrintImmHex("print-imm-hex",
229 cl::desc("Use hex format for immediate values"));
230
231cl::opt<bool> PrintFaultMaps("fault-map-section",
232 cl::desc("Display contents of faultmap section"));
233
234cl::opt<DIDumpType> llvm::DwarfDumpType(
235 "dwarf", cl::init(DIDT_Null), cl::desc("Dump of dwarf debug sections:"),
236 cl::values(clEnumValN(DIDT_DebugFrame, "frames", ".debug_frame")llvm::cl::OptionEnumValue { "frames", int(DIDT_DebugFrame), ".debug_frame"
}
));
237
238cl::opt<bool> PrintSource(
239 "source",
240 cl::desc(
241 "Display source inlined with disassembly. Implies disassemble object"));
242
243cl::alias PrintSourceShort("S", cl::desc("Alias for -source"),
244 cl::aliasopt(PrintSource));
245
246cl::opt<bool> PrintLines("line-numbers",
247 cl::desc("Display source line numbers with "
248 "disassembly. Implies disassemble object"));
249
250cl::alias PrintLinesShort("l", cl::desc("Alias for -line-numbers"),
251 cl::aliasopt(PrintLines));
252
253cl::opt<unsigned long long>
254 StartAddress("start-address", cl::desc("Disassemble beginning at address"),
255 cl::value_desc("address"), cl::init(0));
256cl::opt<unsigned long long>
257 StopAddress("stop-address", cl::desc("Stop disassembly at address"),
258 cl::value_desc("address"), cl::init(UINT64_MAX(18446744073709551615UL)));
259static StringRef ToolName;
260
261typedef std::vector<std::tuple<uint64_t, StringRef, uint8_t>> SectionSymbolsTy;
262
263namespace {
264typedef std::function<bool(llvm::object::SectionRef const &)> FilterPredicate;
265
266class SectionFilterIterator {
267public:
268 SectionFilterIterator(FilterPredicate P,
269 llvm::object::section_iterator const &I,
270 llvm::object::section_iterator const &E)
271 : Predicate(std::move(P)), Iterator(I), End(E) {
272 ScanPredicate();
273 }
274 const llvm::object::SectionRef &operator*() const { return *Iterator; }
275 SectionFilterIterator &operator++() {
276 ++Iterator;
277 ScanPredicate();
278 return *this;
279 }
280 bool operator!=(SectionFilterIterator const &Other) const {
281 return Iterator != Other.Iterator;
282 }
283
284private:
285 void ScanPredicate() {
286 while (Iterator != End && !Predicate(*Iterator)) {
287 ++Iterator;
288 }
289 }
290 FilterPredicate Predicate;
291 llvm::object::section_iterator Iterator;
292 llvm::object::section_iterator End;
293};
294
295class SectionFilter {
296public:
297 SectionFilter(FilterPredicate P, llvm::object::ObjectFile const &O)
298 : Predicate(std::move(P)), Object(O) {}
299 SectionFilterIterator begin() {
300 return SectionFilterIterator(Predicate, Object.section_begin(),
301 Object.section_end());
302 }
303 SectionFilterIterator end() {
304 return SectionFilterIterator(Predicate, Object.section_end(),
305 Object.section_end());
306 }
307
308private:
309 FilterPredicate Predicate;
310 llvm::object::ObjectFile const &Object;
311};
312SectionFilter ToolSectionFilter(llvm::object::ObjectFile const &O) {
313 return SectionFilter(
314 [](llvm::object::SectionRef const &S) {
315 if (FilterSections.empty())
316 return true;
317 llvm::StringRef String;
318 std::error_code error = S.getName(String);
319 if (error)
320 return false;
321 return is_contained(FilterSections, String);
322 },
323 O);
324}
325}
326
327void llvm::error(std::error_code EC) {
328 if (!EC)
329 return;
330
331 errs() << ToolName << ": error reading file: " << EC.message() << ".\n";
332 errs().flush();
333 exit(1);
334}
335
336LLVM_ATTRIBUTE_NORETURN__attribute__((noreturn)) void llvm::error(Twine Message) {
337 errs() << ToolName << ": " << Message << ".\n";
338 errs().flush();
339 exit(1);
340}
341
342void llvm::warn(StringRef Message) {
343 errs() << ToolName << ": warning: " << Message << ".\n";
344 errs().flush();
345}
346
347LLVM_ATTRIBUTE_NORETURN__attribute__((noreturn)) void llvm::report_error(StringRef File,
348 Twine Message) {
349 errs() << ToolName << ": '" << File << "': " << Message << ".\n";
350 exit(1);
351}
352
353LLVM_ATTRIBUTE_NORETURN__attribute__((noreturn)) void llvm::report_error(StringRef File,
354 std::error_code EC) {
355 assert(EC)((EC) ? static_cast<void> (0) : __assert_fail ("EC", "/build/llvm-toolchain-snapshot-8~svn345461/tools/llvm-objdump/llvm-objdump.cpp"
, 355, __PRETTY_FUNCTION__))
;
356 errs() << ToolName << ": '" << File << "': " << EC.message() << ".\n";
357 exit(1);
358}
359
360LLVM_ATTRIBUTE_NORETURN__attribute__((noreturn)) void llvm::report_error(StringRef File,
361 llvm::Error E) {
362 assert(E)((E) ? static_cast<void> (0) : __assert_fail ("E", "/build/llvm-toolchain-snapshot-8~svn345461/tools/llvm-objdump/llvm-objdump.cpp"
, 362, __PRETTY_FUNCTION__))
;
363 std::string Buf;
364 raw_string_ostream OS(Buf);
365 logAllUnhandledErrors(std::move(E), OS, "");
366 OS.flush();
367 errs() << ToolName << ": '" << File << "': " << Buf;
368 exit(1);
369}
370
371LLVM_ATTRIBUTE_NORETURN__attribute__((noreturn)) void llvm::report_error(StringRef ArchiveName,
372 StringRef FileName,
373 llvm::Error E,
374 StringRef ArchitectureName) {
375 assert(E)((E) ? static_cast<void> (0) : __assert_fail ("E", "/build/llvm-toolchain-snapshot-8~svn345461/tools/llvm-objdump/llvm-objdump.cpp"
, 375, __PRETTY_FUNCTION__))
;
376 errs() << ToolName << ": ";
377 if (ArchiveName != "")
378 errs() << ArchiveName << "(" << FileName << ")";
379 else
380 errs() << "'" << FileName << "'";
381 if (!ArchitectureName.empty())
382 errs() << " (for architecture " << ArchitectureName << ")";
383 std::string Buf;
384 raw_string_ostream OS(Buf);
385 logAllUnhandledErrors(std::move(E), OS, "");
386 OS.flush();
387 errs() << ": " << Buf;
388 exit(1);
389}
390
391LLVM_ATTRIBUTE_NORETURN__attribute__((noreturn)) void llvm::report_error(StringRef ArchiveName,
392 const object::Archive::Child &C,
393 llvm::Error E,
394 StringRef ArchitectureName) {
395 Expected<StringRef> NameOrErr = C.getName();
396 // TODO: if we have a error getting the name then it would be nice to print
397 // the index of which archive member this is and or its offset in the
398 // archive instead of "???" as the name.
399 if (!NameOrErr) {
400 consumeError(NameOrErr.takeError());
401 llvm::report_error(ArchiveName, "???", std::move(E), ArchitectureName);
402 } else
403 llvm::report_error(ArchiveName, NameOrErr.get(), std::move(E),
404 ArchitectureName);
405}
406
407static const Target *getTarget(const ObjectFile *Obj = nullptr) {
408 // Figure out the target triple.
409 llvm::Triple TheTriple("unknown-unknown-unknown");
410 if (TripleName.empty()) {
411 if (Obj) {
412 TheTriple = Obj->makeTriple();
413 }
414 } else {
415 TheTriple.setTriple(Triple::normalize(TripleName));
416
417 // Use the triple, but also try to combine with ARM build attributes.
418 if (Obj) {
419 auto Arch = Obj->getArch();
420 if (Arch == Triple::arm || Arch == Triple::armeb) {
421 Obj->setARMSubArch(TheTriple);
422 }
423 }
424 }
425
426 // Get the target specific parser.
427 std::string Error;
428 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
429 Error);
430 if (!TheTarget) {
431 if (Obj)
432 report_error(Obj->getFileName(), "can't find target: " + Error);
433 else
434 error("can't find target: " + Error);
435 }
436
437 // Update the triple name and return the found target.
438 TripleName = TheTriple.getTriple();
439 return TheTarget;
440}
441
442bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
443 return a.getOffset() < b.getOffset();
444}
445
446template <class ELFT>
447static std::error_code getRelocationValueString(const ELFObjectFile<ELFT> *Obj,
448 const RelocationRef &RelRef,
449 SmallVectorImpl<char> &Result) {
450 DataRefImpl Rel = RelRef.getRawDataRefImpl();
451
452 typedef typename ELFObjectFile<ELFT>::Elf_Sym Elf_Sym;
453 typedef typename ELFObjectFile<ELFT>::Elf_Shdr Elf_Shdr;
454 typedef typename ELFObjectFile<ELFT>::Elf_Rela Elf_Rela;
455
456 const ELFFile<ELFT> &EF = *Obj->getELFFile();
457
458 auto SecOrErr = EF.getSection(Rel.d.a);
459 if (!SecOrErr)
460 return errorToErrorCode(SecOrErr.takeError());
461 const Elf_Shdr *Sec = *SecOrErr;
462 auto SymTabOrErr = EF.getSection(Sec->sh_link);
463 if (!SymTabOrErr)
464 return errorToErrorCode(SymTabOrErr.takeError());
465 const Elf_Shdr *SymTab = *SymTabOrErr;
466 assert(SymTab->sh_type == ELF::SHT_SYMTAB ||((SymTab->sh_type == ELF::SHT_SYMTAB || SymTab->sh_type
== ELF::SHT_DYNSYM) ? static_cast<void> (0) : __assert_fail
("SymTab->sh_type == ELF::SHT_SYMTAB || SymTab->sh_type == ELF::SHT_DYNSYM"
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/llvm-objdump/llvm-objdump.cpp"
, 467, __PRETTY_FUNCTION__))
467 SymTab->sh_type == ELF::SHT_DYNSYM)((SymTab->sh_type == ELF::SHT_SYMTAB || SymTab->sh_type
== ELF::SHT_DYNSYM) ? static_cast<void> (0) : __assert_fail
("SymTab->sh_type == ELF::SHT_SYMTAB || SymTab->sh_type == ELF::SHT_DYNSYM"
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/llvm-objdump/llvm-objdump.cpp"
, 467, __PRETTY_FUNCTION__))
;
468 auto StrTabSec = EF.getSection(SymTab->sh_link);
469 if (!StrTabSec)
470 return errorToErrorCode(StrTabSec.takeError());
471 auto StrTabOrErr = EF.getStringTable(*StrTabSec);
472 if (!StrTabOrErr)
473 return errorToErrorCode(StrTabOrErr.takeError());
474 StringRef StrTab = *StrTabOrErr;
475 int64_t addend = 0;
476 // If there is no Symbol associated with the relocation, we set the undef
477 // boolean value to 'true'. This will prevent us from calling functions that
478 // requires the relocation to be associated with a symbol.
479 bool undef = false;
480 switch (Sec->sh_type) {
481 default:
482 return object_error::parse_failed;
483 case ELF::SHT_REL: {
484 // TODO: Read implicit addend from section data.
485 break;
486 }
487 case ELF::SHT_RELA: {
488 const Elf_Rela *ERela = Obj->getRela(Rel);
489 addend = ERela->r_addend;
490 undef = ERela->getSymbol(false) == 0;
491 break;
492 }
493 }
494 StringRef Target;
495 if (!undef) {
496 symbol_iterator SI = RelRef.getSymbol();
497 const Elf_Sym *symb = Obj->getSymbol(SI->getRawDataRefImpl());
498 if (symb->getType() == ELF::STT_SECTION) {
499 Expected<section_iterator> SymSI = SI->getSection();
500 if (!SymSI)
501 return errorToErrorCode(SymSI.takeError());
502 const Elf_Shdr *SymSec = Obj->getSection((*SymSI)->getRawDataRefImpl());
503 auto SecName = EF.getSectionName(SymSec);
504 if (!SecName)
505 return errorToErrorCode(SecName.takeError());
506 Target = *SecName;
507 } else {
508 Expected<StringRef> SymName = symb->getName(StrTab);
509 if (!SymName)
510 return errorToErrorCode(SymName.takeError());
511 Target = *SymName;
512 }
513 } else
514 Target = "*ABS*";
515
516 // Default scheme is to print Target, as well as "+ <addend>" for nonzero
517 // addend. Should be acceptable for all normal purposes.
518 std::string fmtbuf;
519 raw_string_ostream fmt(fmtbuf);
520 fmt << Target;
521 if (addend != 0)
522 fmt << (addend < 0 ? "" : "+") << addend;
523 fmt.flush();
524 Result.append(fmtbuf.begin(), fmtbuf.end());
525 return std::error_code();
526}
527
528static std::error_code getRelocationValueString(const ELFObjectFileBase *Obj,
529 const RelocationRef &Rel,
530 SmallVectorImpl<char> &Result) {
531 if (auto *ELF32LE = dyn_cast<ELF32LEObjectFile>(Obj))
532 return getRelocationValueString(ELF32LE, Rel, Result);
533 if (auto *ELF64LE = dyn_cast<ELF64LEObjectFile>(Obj))
534 return getRelocationValueString(ELF64LE, Rel, Result);
535 if (auto *ELF32BE = dyn_cast<ELF32BEObjectFile>(Obj))
536 return getRelocationValueString(ELF32BE, Rel, Result);
537 auto *ELF64BE = cast<ELF64BEObjectFile>(Obj);
538 return getRelocationValueString(ELF64BE, Rel, Result);
539}
540
541static std::error_code getRelocationValueString(const COFFObjectFile *Obj,
542 const RelocationRef &Rel,
543 SmallVectorImpl<char> &Result) {
544 symbol_iterator SymI = Rel.getSymbol();
545 Expected<StringRef> SymNameOrErr = SymI->getName();
546 if (!SymNameOrErr)
547 return errorToErrorCode(SymNameOrErr.takeError());
548 StringRef SymName = *SymNameOrErr;
549 Result.append(SymName.begin(), SymName.end());
550 return std::error_code();
551}
552
553static void printRelocationTargetName(const MachOObjectFile *O,
554 const MachO::any_relocation_info &RE,
555 raw_string_ostream &fmt) {
556 bool IsScattered = O->isRelocationScattered(RE);
557
558 // Target of a scattered relocation is an address. In the interest of
559 // generating pretty output, scan through the symbol table looking for a
560 // symbol that aligns with that address. If we find one, print it.
561 // Otherwise, we just print the hex address of the target.
562 if (IsScattered) {
563 uint32_t Val = O->getPlainRelocationSymbolNum(RE);
564
565 for (const SymbolRef &Symbol : O->symbols()) {
566 std::error_code ec;
567 Expected<uint64_t> Addr = Symbol.getAddress();
568 if (!Addr)
569 report_error(O->getFileName(), Addr.takeError());
570 if (*Addr != Val)
571 continue;
572 Expected<StringRef> Name = Symbol.getName();
573 if (!Name)
574 report_error(O->getFileName(), Name.takeError());
575 fmt << *Name;
576 return;
577 }
578
579 // If we couldn't find a symbol that this relocation refers to, try
580 // to find a section beginning instead.
581 for (const SectionRef &Section : ToolSectionFilter(*O)) {
582 std::error_code ec;
583
584 StringRef Name;
585 uint64_t Addr = Section.getAddress();
586 if (Addr != Val)
587 continue;
588 if ((ec = Section.getName(Name)))
589 report_error(O->getFileName(), ec);
590 fmt << Name;
591 return;
592 }
593
594 fmt << format("0x%x", Val);
595 return;
596 }
597
598 StringRef S;
599 bool isExtern = O->getPlainRelocationExternal(RE);
600 uint64_t Val = O->getPlainRelocationSymbolNum(RE);
601
602 if (O->getAnyRelocationType(RE) == MachO::ARM64_RELOC_ADDEND) {
603 fmt << format("0x%0" PRIx64"l" "x", Val);
604 return;
605 } else if (isExtern) {
606 symbol_iterator SI = O->symbol_begin();
607 advance(SI, Val);
608 Expected<StringRef> SOrErr = SI->getName();
609 if (!SOrErr)
610 report_error(O->getFileName(), SOrErr.takeError());
611 S = *SOrErr;
612 } else {
613 section_iterator SI = O->section_begin();
614 // Adjust for the fact that sections are 1-indexed.
615 if (Val == 0) {
616 fmt << "0 (?,?)";
617 return;
618 }
619 uint32_t i = Val - 1;
620 while (i != 0 && SI != O->section_end()) {
621 i--;
622 advance(SI, 1);
623 }
624 if (SI == O->section_end())
625 fmt << Val << " (?,?)";
626 else
627 SI->getName(S);
628 }
629
630 fmt << S;
631}
632
633static std::error_code getRelocationValueString(const WasmObjectFile *Obj,
634 const RelocationRef &RelRef,
635 SmallVectorImpl<char> &Result) {
636 const wasm::WasmRelocation& Rel = Obj->getWasmRelocation(RelRef);
637 symbol_iterator SI = RelRef.getSymbol();
638 std::string fmtbuf;
639 raw_string_ostream fmt(fmtbuf);
640 if (SI == Obj->symbol_end()) {
641 // Not all wasm relocations have symbols associated with them.
642 // In particular R_WEBASSEMBLY_TYPE_INDEX_LEB.
643 fmt << Rel.Index;
644 } else {
645 Expected<StringRef> SymNameOrErr = SI->getName();
646 if (!SymNameOrErr)
647 return errorToErrorCode(SymNameOrErr.takeError());
648 StringRef SymName = *SymNameOrErr;
649 Result.append(SymName.begin(), SymName.end());
650 }
651 fmt << (Rel.Addend < 0 ? "" : "+") << Rel.Addend;
652 fmt.flush();
653 Result.append(fmtbuf.begin(), fmtbuf.end());
654 return std::error_code();
655}
656
657static std::error_code getRelocationValueString(const MachOObjectFile *Obj,
658 const RelocationRef &RelRef,
659 SmallVectorImpl<char> &Result) {
660 DataRefImpl Rel = RelRef.getRawDataRefImpl();
661 MachO::any_relocation_info RE = Obj->getRelocation(Rel);
662
663 unsigned Arch = Obj->getArch();
664
665 std::string fmtbuf;
666 raw_string_ostream fmt(fmtbuf);
667 unsigned Type = Obj->getAnyRelocationType(RE);
668 bool IsPCRel = Obj->getAnyRelocationPCRel(RE);
669
670 // Determine any addends that should be displayed with the relocation.
671 // These require decoding the relocation type, which is triple-specific.
672
673 // X86_64 has entirely custom relocation types.
674 if (Arch == Triple::x86_64) {
675 bool isPCRel = Obj->getAnyRelocationPCRel(RE);
676
677 switch (Type) {
678 case MachO::X86_64_RELOC_GOT_LOAD:
679 case MachO::X86_64_RELOC_GOT: {
680 printRelocationTargetName(Obj, RE, fmt);
681 fmt << "@GOT";
682 if (isPCRel)
683 fmt << "PCREL";
684 break;
685 }
686 case MachO::X86_64_RELOC_SUBTRACTOR: {
687 DataRefImpl RelNext = Rel;
688 Obj->moveRelocationNext(RelNext);
689 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
690
691 // X86_64_RELOC_SUBTRACTOR must be followed by a relocation of type
692 // X86_64_RELOC_UNSIGNED.
693 // NOTE: Scattered relocations don't exist on x86_64.
694 unsigned RType = Obj->getAnyRelocationType(RENext);
695 if (RType != MachO::X86_64_RELOC_UNSIGNED)
696 report_error(Obj->getFileName(), "Expected X86_64_RELOC_UNSIGNED after "
697 "X86_64_RELOC_SUBTRACTOR.");
698
699 // The X86_64_RELOC_UNSIGNED contains the minuend symbol;
700 // X86_64_RELOC_SUBTRACTOR contains the subtrahend.
701 printRelocationTargetName(Obj, RENext, fmt);
702 fmt << "-";
703 printRelocationTargetName(Obj, RE, fmt);
704 break;
705 }
706 case MachO::X86_64_RELOC_TLV:
707 printRelocationTargetName(Obj, RE, fmt);
708 fmt << "@TLV";
709 if (isPCRel)
710 fmt << "P";
711 break;
712 case MachO::X86_64_RELOC_SIGNED_1:
713 printRelocationTargetName(Obj, RE, fmt);
714 fmt << "-1";
715 break;
716 case MachO::X86_64_RELOC_SIGNED_2:
717 printRelocationTargetName(Obj, RE, fmt);
718 fmt << "-2";
719 break;
720 case MachO::X86_64_RELOC_SIGNED_4:
721 printRelocationTargetName(Obj, RE, fmt);
722 fmt << "-4";
723 break;
724 default:
725 printRelocationTargetName(Obj, RE, fmt);
726 break;
727 }
728 // X86 and ARM share some relocation types in common.
729 } else if (Arch == Triple::x86 || Arch == Triple::arm ||
730 Arch == Triple::ppc) {
731 // Generic relocation types...
732 switch (Type) {
733 case MachO::GENERIC_RELOC_PAIR: // prints no info
734 return std::error_code();
735 case MachO::GENERIC_RELOC_SECTDIFF: {
736 DataRefImpl RelNext = Rel;
737 Obj->moveRelocationNext(RelNext);
738 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
739
740 // X86 sect diff's must be followed by a relocation of type
741 // GENERIC_RELOC_PAIR.
742 unsigned RType = Obj->getAnyRelocationType(RENext);
743
744 if (RType != MachO::GENERIC_RELOC_PAIR)
745 report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
746 "GENERIC_RELOC_SECTDIFF.");
747
748 printRelocationTargetName(Obj, RE, fmt);
749 fmt << "-";
750 printRelocationTargetName(Obj, RENext, fmt);
751 break;
752 }
753 }
754
755 if (Arch == Triple::x86 || Arch == Triple::ppc) {
756 switch (Type) {
757 case MachO::GENERIC_RELOC_LOCAL_SECTDIFF: {
758 DataRefImpl RelNext = Rel;
759 Obj->moveRelocationNext(RelNext);
760 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
761
762 // X86 sect diff's must be followed by a relocation of type
763 // GENERIC_RELOC_PAIR.
764 unsigned RType = Obj->getAnyRelocationType(RENext);
765 if (RType != MachO::GENERIC_RELOC_PAIR)
766 report_error(Obj->getFileName(), "Expected GENERIC_RELOC_PAIR after "
767 "GENERIC_RELOC_LOCAL_SECTDIFF.");
768
769 printRelocationTargetName(Obj, RE, fmt);
770 fmt << "-";
771 printRelocationTargetName(Obj, RENext, fmt);
772 break;
773 }
774 case MachO::GENERIC_RELOC_TLV: {
775 printRelocationTargetName(Obj, RE, fmt);
776 fmt << "@TLV";
777 if (IsPCRel)
778 fmt << "P";
779 break;
780 }
781 default:
782 printRelocationTargetName(Obj, RE, fmt);
783 }
784 } else { // ARM-specific relocations
785 switch (Type) {
786 case MachO::ARM_RELOC_HALF:
787 case MachO::ARM_RELOC_HALF_SECTDIFF: {
788 // Half relocations steal a bit from the length field to encode
789 // whether this is an upper16 or a lower16 relocation.
790 bool isUpper = (Obj->getAnyRelocationLength(RE) & 0x1) == 1;
791
792 if (isUpper)
793 fmt << ":upper16:(";
794 else
795 fmt << ":lower16:(";
796 printRelocationTargetName(Obj, RE, fmt);
797
798 DataRefImpl RelNext = Rel;
799 Obj->moveRelocationNext(RelNext);
800 MachO::any_relocation_info RENext = Obj->getRelocation(RelNext);
801
802 // ARM half relocs must be followed by a relocation of type
803 // ARM_RELOC_PAIR.
804 unsigned RType = Obj->getAnyRelocationType(RENext);
805 if (RType != MachO::ARM_RELOC_PAIR)
806 report_error(Obj->getFileName(), "Expected ARM_RELOC_PAIR after "
807 "ARM_RELOC_HALF");
808
809 // NOTE: The half of the target virtual address is stashed in the
810 // address field of the secondary relocation, but we can't reverse
811 // engineer the constant offset from it without decoding the movw/movt
812 // instruction to find the other half in its immediate field.
813
814 // ARM_RELOC_HALF_SECTDIFF encodes the second section in the
815 // symbol/section pointer of the follow-on relocation.
816 if (Type == MachO::ARM_RELOC_HALF_SECTDIFF) {
817 fmt << "-";
818 printRelocationTargetName(Obj, RENext, fmt);
819 }
820
821 fmt << ")";
822 break;
823 }
824 default: { printRelocationTargetName(Obj, RE, fmt); }
825 }
826 }
827 } else
828 printRelocationTargetName(Obj, RE, fmt);
829
830 fmt.flush();
831 Result.append(fmtbuf.begin(), fmtbuf.end());
832 return std::error_code();
833}
834
835static std::error_code getRelocationValueString(const RelocationRef &Rel,
836 SmallVectorImpl<char> &Result) {
837 const ObjectFile *Obj = Rel.getObject();
838 if (auto *ELF = dyn_cast<ELFObjectFileBase>(Obj))
839 return getRelocationValueString(ELF, Rel, Result);
840 if (auto *COFF = dyn_cast<COFFObjectFile>(Obj))
841 return getRelocationValueString(COFF, Rel, Result);
842 if (auto *Wasm = dyn_cast<WasmObjectFile>(Obj))
843 return getRelocationValueString(Wasm, Rel, Result);
844 if (auto *MachO = dyn_cast<MachOObjectFile>(Obj))
845 return getRelocationValueString(MachO, Rel, Result);
846 llvm_unreachable("unknown object file format")::llvm::llvm_unreachable_internal("unknown object file format"
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/llvm-objdump/llvm-objdump.cpp"
, 846)
;
847}
848
849/// Indicates whether this relocation should hidden when listing
850/// relocations, usually because it is the trailing part of a multipart
851/// relocation that will be printed as part of the leading relocation.
852static bool getHidden(RelocationRef RelRef) {
853 const ObjectFile *Obj = RelRef.getObject();
854 auto *MachO = dyn_cast<MachOObjectFile>(Obj);
855 if (!MachO)
856 return false;
857
858 unsigned Arch = MachO->getArch();
859 DataRefImpl Rel = RelRef.getRawDataRefImpl();
860 uint64_t Type = MachO->getRelocationType(Rel);
861
862 // On arches that use the generic relocations, GENERIC_RELOC_PAIR
863 // is always hidden.
864 if (Arch == Triple::x86 || Arch == Triple::arm || Arch == Triple::ppc) {
865 if (Type == MachO::GENERIC_RELOC_PAIR)
866 return true;
867 } else if (Arch == Triple::x86_64) {
868 // On x86_64, X86_64_RELOC_UNSIGNED is hidden only when it follows
869 // an X86_64_RELOC_SUBTRACTOR.
870 if (Type == MachO::X86_64_RELOC_UNSIGNED && Rel.d.a > 0) {
871 DataRefImpl RelPrev = Rel;
872 RelPrev.d.a--;
873 uint64_t PrevType = MachO->getRelocationType(RelPrev);
874 if (PrevType == MachO::X86_64_RELOC_SUBTRACTOR)
875 return true;
876 }
877 }
878
879 return false;
880}
881
882namespace {
883class SourcePrinter {
884protected:
885 DILineInfo OldLineInfo;
886 const ObjectFile *Obj = nullptr;
887 std::unique_ptr<symbolize::LLVMSymbolizer> Symbolizer;
888 // File name to file contents of source
889 std::unordered_map<std::string, std::unique_ptr<MemoryBuffer>> SourceCache;
890 // Mark the line endings of the cached source
891 std::unordered_map<std::string, std::vector<StringRef>> LineCache;
892
893private:
894 bool cacheSource(const DILineInfo& LineInfoFile);
895
896public:
897 SourcePrinter() = default;
898 SourcePrinter(const ObjectFile *Obj, StringRef DefaultArch) : Obj(Obj) {
899 symbolize::LLVMSymbolizer::Options SymbolizerOpts(
900 DILineInfoSpecifier::FunctionNameKind::None, true, false, false,
901 DefaultArch);
902 Symbolizer.reset(new symbolize::LLVMSymbolizer(SymbolizerOpts));
903 }
904 virtual ~SourcePrinter() = default;
905 virtual void printSourceLine(raw_ostream &OS, uint64_t Address,
906 StringRef Delimiter = "; ");
907};
908
909bool SourcePrinter::cacheSource(const DILineInfo &LineInfo) {
910 std::unique_ptr<MemoryBuffer> Buffer;
911 if (LineInfo.Source) {
912 Buffer = MemoryBuffer::getMemBuffer(*LineInfo.Source);
913 } else {
914 auto BufferOrError = MemoryBuffer::getFile(LineInfo.FileName);
915 if (!BufferOrError)
916 return false;
917 Buffer = std::move(*BufferOrError);
918 }
919 // Chomp the file to get lines
920 size_t BufferSize = Buffer->getBufferSize();
921 const char *BufferStart = Buffer->getBufferStart();
922 for (const char *Start = BufferStart, *End = BufferStart;
923 End < BufferStart + BufferSize; End++)
924 if (*End == '\n' || End == BufferStart + BufferSize - 1 ||
925 (*End == '\r' && *(End + 1) == '\n')) {
926 LineCache[LineInfo.FileName].push_back(StringRef(Start, End - Start));
927 if (*End == '\r')
928 End++;
929 Start = End + 1;
930 }
931 SourceCache[LineInfo.FileName] = std::move(Buffer);
932 return true;
933}
934
935void SourcePrinter::printSourceLine(raw_ostream &OS, uint64_t Address,
936 StringRef Delimiter) {
937 if (!Symbolizer)
938 return;
939 DILineInfo LineInfo = DILineInfo();
940 auto ExpectecLineInfo =
941 Symbolizer->symbolizeCode(Obj->getFileName(), Address);
942 if (!ExpectecLineInfo)
943 consumeError(ExpectecLineInfo.takeError());
944 else
945 LineInfo = *ExpectecLineInfo;
946
947 if ((LineInfo.FileName == "<invalid>") || OldLineInfo.Line == LineInfo.Line ||
948 LineInfo.Line == 0)
949 return;
950
951 if (PrintLines)
952 OS << Delimiter << LineInfo.FileName << ":" << LineInfo.Line << "\n";
953 if (PrintSource) {
954 if (SourceCache.find(LineInfo.FileName) == SourceCache.end())
955 if (!cacheSource(LineInfo))
956 return;
957 auto FileBuffer = SourceCache.find(LineInfo.FileName);
958 if (FileBuffer != SourceCache.end()) {
959 auto LineBuffer = LineCache.find(LineInfo.FileName);
960 if (LineBuffer != LineCache.end()) {
961 if (LineInfo.Line > LineBuffer->second.size())
962 return;
963 // Vector begins at 0, line numbers are non-zero
964 OS << Delimiter << LineBuffer->second[LineInfo.Line - 1].ltrim()
965 << "\n";
966 }
967 }
968 }
969 OldLineInfo = LineInfo;
970}
971
972static bool isArmElf(const ObjectFile *Obj) {
973 return (Obj->isELF() &&
974 (Obj->getArch() == Triple::aarch64 ||
975 Obj->getArch() == Triple::aarch64_be ||
976 Obj->getArch() == Triple::arm || Obj->getArch() == Triple::armeb ||
977 Obj->getArch() == Triple::thumb ||
978 Obj->getArch() == Triple::thumbeb));
979}
980
981class PrettyPrinter {
982public:
983 virtual ~PrettyPrinter() = default;
984 virtual void printInst(MCInstPrinter &IP, const MCInst *MI,
985 ArrayRef<uint8_t> Bytes, uint64_t Address,
986 raw_ostream &OS, StringRef Annot,
987 MCSubtargetInfo const &STI, SourcePrinter *SP,
988 std::vector<RelocationRef> *Rels = nullptr) {
989 if (SP && (PrintSource || PrintLines))
990 SP->printSourceLine(OS, Address);
991 if (!NoLeadingAddr)
992 OS << format("%8" PRIx64"l" "x" ":", Address);
993 if (!NoShowRawInsn) {
994 OS << "\t";
995 dumpBytes(Bytes, OS);
996 }
997 if (MI)
998 IP.printInst(MI, OS, "", STI);
999 else
1000 OS << " <unknown>";
1001 }
1002};
1003PrettyPrinter PrettyPrinterInst;
1004class HexagonPrettyPrinter : public PrettyPrinter {
1005public:
1006 void printLead(ArrayRef<uint8_t> Bytes, uint64_t Address,
1007 raw_ostream &OS) {
1008 uint32_t opcode =
1009 (Bytes[3] << 24) | (Bytes[2] << 16) | (Bytes[1] << 8) | Bytes[0];
1010 if (!NoLeadingAddr)
1011 OS << format("%8" PRIx64"l" "x" ":", Address);
1012 if (!NoShowRawInsn) {
1013 OS << "\t";
1014 dumpBytes(Bytes.slice(0, 4), OS);
1015 OS << format("%08" PRIx32"x", opcode);
1016 }
1017 }
1018 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
1019 uint64_t Address, raw_ostream &OS, StringRef Annot,
1020 MCSubtargetInfo const &STI, SourcePrinter *SP,
1021 std::vector<RelocationRef> *Rels) override {
1022 if (SP && (PrintSource || PrintLines))
1023 SP->printSourceLine(OS, Address, "");
1024 if (!MI) {
1025 printLead(Bytes, Address, OS);
1026 OS << " <unknown>";
1027 return;
1028 }
1029 std::string Buffer;
1030 {
1031 raw_string_ostream TempStream(Buffer);
1032 IP.printInst(MI, TempStream, "", STI);
1033 }
1034 StringRef Contents(Buffer);
1035 // Split off bundle attributes
1036 auto PacketBundle = Contents.rsplit('\n');
1037 // Split off first instruction from the rest
1038 auto HeadTail = PacketBundle.first.split('\n');
1039 auto Preamble = " { ";
1040 auto Separator = "";
1041 StringRef Fmt = "\t\t\t%08" PRIx64"l" "x" ": ";
1042 std::vector<RelocationRef>::const_iterator rel_cur = Rels->begin();
1043 std::vector<RelocationRef>::const_iterator rel_end = Rels->end();
1044
1045 // Hexagon's packets require relocations to be inline rather than
1046 // clustered at the end of the packet.
1047 auto PrintReloc = [&]() -> void {
1048 while ((rel_cur != rel_end) && (rel_cur->getOffset() <= Address)) {
1049 if (rel_cur->getOffset() == Address) {
1050 SmallString<16> name;
1051 SmallString<32> val;
1052 rel_cur->getTypeName(name);
1053 error(getRelocationValueString(*rel_cur, val));
1054 OS << Separator << format(Fmt.data(), Address) << name << "\t" << val
1055 << "\n";
1056 return;
1057 }
1058 rel_cur++;
1059 }
1060 };
1061
1062 while(!HeadTail.first.empty()) {
1063 OS << Separator;
1064 Separator = "\n";
1065 if (SP && (PrintSource || PrintLines))
1066 SP->printSourceLine(OS, Address, "");
1067 printLead(Bytes, Address, OS);
1068 OS << Preamble;
1069 Preamble = " ";
1070 StringRef Inst;
1071 auto Duplex = HeadTail.first.split('\v');
1072 if(!Duplex.second.empty()){
1073 OS << Duplex.first;
1074 OS << "; ";
1075 Inst = Duplex.second;
1076 }
1077 else
1078 Inst = HeadTail.first;
1079 OS << Inst;
1080 HeadTail = HeadTail.second.split('\n');
1081 if (HeadTail.first.empty())
1082 OS << " } " << PacketBundle.second;
1083 PrintReloc();
1084 Bytes = Bytes.slice(4);
1085 Address += 4;
1086 }
1087 }
1088};
1089HexagonPrettyPrinter HexagonPrettyPrinterInst;
1090
1091class AMDGCNPrettyPrinter : public PrettyPrinter {
1092public:
1093 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
1094 uint64_t Address, raw_ostream &OS, StringRef Annot,
1095 MCSubtargetInfo const &STI, SourcePrinter *SP,
1096 std::vector<RelocationRef> *Rels) override {
1097 if (SP && (PrintSource || PrintLines))
1098 SP->printSourceLine(OS, Address);
1099
1100 typedef support::ulittle32_t U32;
1101
1102 if (MI) {
1103 SmallString<40> InstStr;
1104 raw_svector_ostream IS(InstStr);
1105
1106 IP.printInst(MI, IS, "", STI);
1107
1108 OS << left_justify(IS.str(), 60);
1109 } else {
1110 // an unrecognized encoding - this is probably data so represent it
1111 // using the .long directive, or .byte directive if fewer than 4 bytes
1112 // remaining
1113 if (Bytes.size() >= 4) {
1114 OS << format("\t.long 0x%08" PRIx32"x" " ",
1115 static_cast<uint32_t>(*reinterpret_cast<const U32*>(Bytes.data())));
1116 OS.indent(42);
1117 } else {
1118 OS << format("\t.byte 0x%02" PRIx8"x", Bytes[0]);
1119 for (unsigned int i = 1; i < Bytes.size(); i++)
1120 OS << format(", 0x%02" PRIx8"x", Bytes[i]);
1121 OS.indent(55 - (6 * Bytes.size()));
1122 }
1123 }
1124
1125 OS << format("// %012" PRIX64"l" "X" ": ", Address);
1126 if (Bytes.size() >=4) {
1127 for (auto D : makeArrayRef(reinterpret_cast<const U32*>(Bytes.data()),
1128 Bytes.size() / sizeof(U32)))
1129 // D should be explicitly casted to uint32_t here as it is passed
1130 // by format to snprintf as vararg.
1131 OS << format("%08" PRIX32"X" " ", static_cast<uint32_t>(D));
1132 } else {
1133 for (unsigned int i = 0; i < Bytes.size(); i++)
1134 OS << format("%02" PRIX8"X" " ", Bytes[i]);
1135 }
1136
1137 if (!Annot.empty())
1138 OS << "// " << Annot;
1139 }
1140};
1141AMDGCNPrettyPrinter AMDGCNPrettyPrinterInst;
1142
1143class BPFPrettyPrinter : public PrettyPrinter {
1144public:
1145 void printInst(MCInstPrinter &IP, const MCInst *MI, ArrayRef<uint8_t> Bytes,
1146 uint64_t Address, raw_ostream &OS, StringRef Annot,
1147 MCSubtargetInfo const &STI, SourcePrinter *SP,
1148 std::vector<RelocationRef> *Rels) override {
1149 if (SP && (PrintSource || PrintLines))
1150 SP->printSourceLine(OS, Address);
1151 if (!NoLeadingAddr)
1152 OS << format("%8" PRId64"l" "d" ":", Address / 8);
1153 if (!NoShowRawInsn) {
1154 OS << "\t";
1155 dumpBytes(Bytes, OS);
1156 }
1157 if (MI)
1158 IP.printInst(MI, OS, "", STI);
1159 else
1160 OS << " <unknown>";
1161 }
1162};
1163BPFPrettyPrinter BPFPrettyPrinterInst;
1164
1165PrettyPrinter &selectPrettyPrinter(Triple const &Triple) {
1166 switch(Triple.getArch()) {
1167 default:
1168 return PrettyPrinterInst;
1169 case Triple::hexagon:
1170 return HexagonPrettyPrinterInst;
1171 case Triple::amdgcn:
1172 return AMDGCNPrettyPrinterInst;
1173 case Triple::bpfel:
1174 case Triple::bpfeb:
1175 return BPFPrettyPrinterInst;
1176 }
1177}
1178}
1179
1180static uint8_t getElfSymbolType(const ObjectFile *Obj, const SymbolRef &Sym) {
1181 assert(Obj->isELF())((Obj->isELF()) ? static_cast<void> (0) : __assert_fail
("Obj->isELF()", "/build/llvm-toolchain-snapshot-8~svn345461/tools/llvm-objdump/llvm-objdump.cpp"
, 1181, __PRETTY_FUNCTION__))
;
1182 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
1
Taking true branch
1183 return Elf32LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
2
Calling 'ELFObjectFile::getSymbol'
1184 if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
1185 return Elf64LEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1186 if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
1187 return Elf32BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1188 if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
1189 return Elf64BEObj->getSymbol(Sym.getRawDataRefImpl())->getType();
1190 llvm_unreachable("Unsupported binary format")::llvm::llvm_unreachable_internal("Unsupported binary format"
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/llvm-objdump/llvm-objdump.cpp"
, 1190)
;
1191}
1192
1193template <class ELFT> static void
1194addDynamicElfSymbols(const ELFObjectFile<ELFT> *Obj,
1195 std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
1196 for (auto Symbol : Obj->getDynamicSymbolIterators()) {
1197 uint8_t SymbolType = Symbol.getELFType();
1198 if (SymbolType != ELF::STT_FUNC || Symbol.getSize() == 0)
1199 continue;
1200
1201 Expected<uint64_t> AddressOrErr = Symbol.getAddress();
1202 if (!AddressOrErr)
1203 report_error(Obj->getFileName(), AddressOrErr.takeError());
1204 uint64_t Address = *AddressOrErr;
1205
1206 Expected<StringRef> Name = Symbol.getName();
1207 if (!Name)
1208 report_error(Obj->getFileName(), Name.takeError());
1209 if (Name->empty())
1210 continue;
1211
1212 Expected<section_iterator> SectionOrErr = Symbol.getSection();
1213 if (!SectionOrErr)
1214 report_error(Obj->getFileName(), SectionOrErr.takeError());
1215 section_iterator SecI = *SectionOrErr;
1216 if (SecI == Obj->section_end())
1217 continue;
1218
1219 AllSymbols[*SecI].emplace_back(Address, *Name, SymbolType);
1220 }
1221}
1222
1223static void
1224addDynamicElfSymbols(const ObjectFile *Obj,
1225 std::map<SectionRef, SectionSymbolsTy> &AllSymbols) {
1226 assert(Obj->isELF())((Obj->isELF()) ? static_cast<void> (0) : __assert_fail
("Obj->isELF()", "/build/llvm-toolchain-snapshot-8~svn345461/tools/llvm-objdump/llvm-objdump.cpp"
, 1226, __PRETTY_FUNCTION__))
;
1227 if (auto *Elf32LEObj = dyn_cast<ELF32LEObjectFile>(Obj))
1228 addDynamicElfSymbols(Elf32LEObj, AllSymbols);
1229 else if (auto *Elf64LEObj = dyn_cast<ELF64LEObjectFile>(Obj))
1230 addDynamicElfSymbols(Elf64LEObj, AllSymbols);
1231 else if (auto *Elf32BEObj = dyn_cast<ELF32BEObjectFile>(Obj))
1232 addDynamicElfSymbols(Elf32BEObj, AllSymbols);
1233 else if (auto *Elf64BEObj = cast<ELF64BEObjectFile>(Obj))
1234 addDynamicElfSymbols(Elf64BEObj, AllSymbols);
1235 else
1236 llvm_unreachable("Unsupported binary format")::llvm::llvm_unreachable_internal("Unsupported binary format"
, "/build/llvm-toolchain-snapshot-8~svn345461/tools/llvm-objdump/llvm-objdump.cpp"
, 1236)
;
1237}
1238
1239static void addPltEntries(const ObjectFile *Obj,
1240 std::map<SectionRef, SectionSymbolsTy> &AllSymbols,
1241 StringSaver &Saver) {
1242 Optional<SectionRef> Plt = None;
1243 for (const SectionRef &Section : Obj->sections()) {
1244 StringRef Name;
1245 if (Section.getName(Name))
1246 continue;
1247 if (Name == ".plt")
1248 Plt = Section;
1249 }
1250 if (!Plt)
1251 return;
1252 if (auto *ElfObj = dyn_cast<ELFObjectFileBase>(Obj)) {
1253 for (auto PltEntry : ElfObj->getPltAddresses()) {
1254 SymbolRef Symbol(PltEntry.first, ElfObj);
1255
1256 uint8_t SymbolType = getElfSymbolType(Obj, Symbol);
1257
1258 Expected<StringRef> NameOrErr = Symbol.getName();
1259 if (!NameOrErr)
1260 report_error(Obj->getFileName(), NameOrErr.takeError());
1261 if (NameOrErr->empty())
1262 continue;
1263 StringRef Name = Saver.save((*NameOrErr + "@plt").str());
1264
1265 AllSymbols[*Plt].emplace_back(PltEntry.second, Name, SymbolType);
1266 }
1267 }
1268}
1269
1270static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
1271 if (StartAddress > StopAddress)
1272 error("Start address should be less than stop address");
1273
1274 const Target *TheTarget = getTarget(Obj);
1275
1276 // Package up features to be passed to target/subtarget
1277 SubtargetFeatures Features = Obj->getFeatures();
1278 if (MAttrs.size()) {
1279 for (unsigned i = 0; i != MAttrs.size(); ++i)
1280 Features.AddFeature(MAttrs[i]);
1281 }
1282
1283 std::unique_ptr<const MCRegisterInfo> MRI(
1284 TheTarget->createMCRegInfo(TripleName));
1285 if (!MRI)
1286 report_error(Obj->getFileName(), "no register info for target " +
1287 TripleName);
1288
1289 // Set up disassembler.
1290 std::unique_ptr<const MCAsmInfo> AsmInfo(
1291 TheTarget->createMCAsmInfo(*MRI, TripleName));
1292 if (!AsmInfo)
1293 report_error(Obj->getFileName(), "no assembly info for target " +
1294 TripleName);
1295 std::unique_ptr<const MCSubtargetInfo> STI(
1296 TheTarget->createMCSubtargetInfo(TripleName, MCPU, Features.getString()));
1297 if (!STI)
1298 report_error(Obj->getFileName(), "no subtarget info for target " +
1299 TripleName);
1300 std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
1301 if (!MII)
1302 report_error(Obj->getFileName(), "no instruction info for target " +
1303 TripleName);
1304 MCObjectFileInfo MOFI;
1305 MCContext Ctx(AsmInfo.get(), MRI.get(), &MOFI);
1306 // FIXME: for now initialize MCObjectFileInfo with default values
1307 MOFI.InitMCObjectFileInfo(Triple(TripleName), false, Ctx);
1308
1309 std::unique_ptr<MCDisassembler> DisAsm(
1310 TheTarget->createMCDisassembler(*STI, Ctx));
1311 if (!DisAsm)
1312 report_error(Obj->getFileName(), "no disassembler for target " +
1313 TripleName);
1314
1315 std::unique_ptr<const MCInstrAnalysis> MIA(
1316 TheTarget->createMCInstrAnalysis(MII.get()));
1317
1318 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
1319 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
1320 Triple(TripleName), AsmPrinterVariant, *AsmInfo, *MII, *MRI));
1321 if (!IP)
1322 report_error(Obj->getFileName(), "no instruction printer for target " +
1323 TripleName);
1324 IP->setPrintImmHex(PrintImmHex);
1325 PrettyPrinter &PIP = selectPrettyPrinter(Triple(TripleName));
1326
1327 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64"l" "x" ": " :
1328 "\t\t\t%08" PRIx64"l" "x" ": ";
1329
1330 SourcePrinter SP(Obj, TheTarget->getName());
1331
1332 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
1333 // in RelocSecs contain the relocations for section S.
1334 std::error_code EC;
1335 std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
1336 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1337 section_iterator Sec2 = Section.getRelocatedSection();
1338 if (Sec2 != Obj->section_end())
1339 SectionRelocMap[*Sec2].push_back(Section);
1340 }
1341
1342 // Create a mapping from virtual address to symbol name. This is used to
1343 // pretty print the symbols while disassembling.
1344 std::map<SectionRef, SectionSymbolsTy> AllSymbols;
1345 SectionSymbolsTy AbsoluteSymbols;
1346 for (const SymbolRef &Symbol : Obj->symbols()) {
1347 Expected<uint64_t> AddressOrErr = Symbol.getAddress();
1348 if (!AddressOrErr)
1349 report_error(Obj->getFileName(), AddressOrErr.takeError());
1350 uint64_t Address = *AddressOrErr;
1351
1352 Expected<StringRef> Name = Symbol.getName();
1353 if (!Name)
1354 report_error(Obj->getFileName(), Name.takeError());
1355 if (Name->empty())
1356 continue;
1357
1358 Expected<section_iterator> SectionOrErr = Symbol.getSection();
1359 if (!SectionOrErr)
1360 report_error(Obj->getFileName(), SectionOrErr.takeError());
1361
1362 uint8_t SymbolType = ELF::STT_NOTYPE;
1363 if (Obj->isELF())
1364 SymbolType = getElfSymbolType(Obj, Symbol);
1365
1366 section_iterator SecI = *SectionOrErr;
1367 if (SecI != Obj->section_end())
1368 AllSymbols[*SecI].emplace_back(Address, *Name, SymbolType);
1369 else
1370 AbsoluteSymbols.emplace_back(Address, *Name, SymbolType);
1371
1372
1373 }
1374 if (AllSymbols.empty() && Obj->isELF())
1375 addDynamicElfSymbols(Obj, AllSymbols);
1376
1377 BumpPtrAllocator A;
1378 StringSaver Saver(A);
1379 addPltEntries(Obj, AllSymbols, Saver);
1380
1381 // Create a mapping from virtual address to section.
1382 std::vector<std::pair<uint64_t, SectionRef>> SectionAddresses;
1383 for (SectionRef Sec : Obj->sections())
1384 SectionAddresses.emplace_back(Sec.getAddress(), Sec);
1385 array_pod_sort(SectionAddresses.begin(), SectionAddresses.end());
1386
1387 // Linked executables (.exe and .dll files) typically don't include a real
1388 // symbol table but they might contain an export table.
1389 if (const auto *COFFObj = dyn_cast<COFFObjectFile>(Obj)) {
1390 for (const auto &ExportEntry : COFFObj->export_directories()) {
1391 StringRef Name;
1392 error(ExportEntry.getSymbolName(Name));
1393 if (Name.empty())
1394 continue;
1395 uint32_t RVA;
1396 error(ExportEntry.getExportRVA(RVA));
1397
1398 uint64_t VA = COFFObj->getImageBase() + RVA;
1399 auto Sec = std::upper_bound(
1400 SectionAddresses.begin(), SectionAddresses.end(), VA,
1401 [](uint64_t LHS, const std::pair<uint64_t, SectionRef> &RHS) {
1402 return LHS < RHS.first;
1403 });
1404 if (Sec != SectionAddresses.begin())
1405 --Sec;
1406 else
1407 Sec = SectionAddresses.end();
1408
1409 if (Sec != SectionAddresses.end())
1410 AllSymbols[Sec->second].emplace_back(VA, Name, ELF::STT_NOTYPE);
1411 else
1412 AbsoluteSymbols.emplace_back(VA, Name, ELF::STT_NOTYPE);
1413 }
1414 }
1415
1416 // Sort all the symbols, this allows us to use a simple binary search to find
1417 // a symbol near an address.
1418 for (std::pair<const SectionRef, SectionSymbolsTy> &SecSyms : AllSymbols)
1419 array_pod_sort(SecSyms.second.begin(), SecSyms.second.end());
1420 array_pod_sort(AbsoluteSymbols.begin(), AbsoluteSymbols.end());
1421
1422 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1423 if (!DisassembleAll && (!Section.isText() || Section.isVirtual()))
1424 continue;
1425
1426 uint64_t SectionAddr = Section.getAddress();
1427 uint64_t SectSize = Section.getSize();
1428 if (!SectSize)
1429 continue;
1430
1431 // Get the list of all the symbols in this section.
1432 SectionSymbolsTy &Symbols = AllSymbols[Section];
1433 std::vector<uint64_t> DataMappingSymsAddr;
1434 std::vector<uint64_t> TextMappingSymsAddr;
1435 if (isArmElf(Obj)) {
1436 for (const auto &Symb : Symbols) {
1437 uint64_t Address = std::get<0>(Symb);
1438 StringRef Name = std::get<1>(Symb);
1439 if (Name.startswith("$d"))
1440 DataMappingSymsAddr.push_back(Address - SectionAddr);
1441 if (Name.startswith("$x"))
1442 TextMappingSymsAddr.push_back(Address - SectionAddr);
1443 if (Name.startswith("$a"))
1444 TextMappingSymsAddr.push_back(Address - SectionAddr);
1445 if (Name.startswith("$t"))
1446 TextMappingSymsAddr.push_back(Address - SectionAddr);
1447 }
1448 }
1449
1450 llvm::sort(DataMappingSymsAddr);
1451 llvm::sort(TextMappingSymsAddr);
1452
1453 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1454 // AMDGPU disassembler uses symbolizer for printing labels
1455 std::unique_ptr<MCRelocationInfo> RelInfo(
1456 TheTarget->createMCRelocationInfo(TripleName, Ctx));
1457 if (RelInfo) {
1458 std::unique_ptr<MCSymbolizer> Symbolizer(
1459 TheTarget->createMCSymbolizer(
1460 TripleName, nullptr, nullptr, &Symbols, &Ctx, std::move(RelInfo)));
1461 DisAsm->setSymbolizer(std::move(Symbolizer));
1462 }
1463 }
1464
1465 // Make a list of all the relocations for this section.
1466 std::vector<RelocationRef> Rels;
1467 if (InlineRelocs) {
1468 for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
1469 for (const RelocationRef &Reloc : RelocSec.relocations()) {
1470 Rels.push_back(Reloc);
1471 }
1472 }
1473 }
1474
1475 // Sort relocations by address.
1476 llvm::sort(Rels, RelocAddressLess);
1477
1478 StringRef SegmentName = "";
1479 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
1480 DataRefImpl DR = Section.getRawDataRefImpl();
1481 SegmentName = MachO->getSectionFinalSegmentName(DR);
1482 }
1483 StringRef SectionName;
1484 error(Section.getName(SectionName));
1485
1486 // If the section has no symbol at the start, just insert a dummy one.
1487 if (Symbols.empty() || std::get<0>(Symbols[0]) != 0) {
1488 Symbols.insert(
1489 Symbols.begin(),
1490 std::make_tuple(SectionAddr, SectionName,
1491 Section.isText() ? ELF::STT_FUNC : ELF::STT_OBJECT));
1492 }
1493
1494 SmallString<40> Comments;
1495 raw_svector_ostream CommentStream(Comments);
1496
1497 StringRef BytesStr;
1498 error(Section.getContents(BytesStr));
1499 ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()),
1500 BytesStr.size());
1501
1502 uint64_t Size;
1503 uint64_t Index;
1504 bool PrintedSection = false;
1505
1506 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
1507 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
1508 // Disassemble symbol by symbol.
1509 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
1510 uint64_t Start = std::get<0>(Symbols[si]) - SectionAddr;
1511 // The end is either the section end or the beginning of the next
1512 // symbol.
1513 uint64_t End =
1514 (si == se - 1) ? SectSize : std::get<0>(Symbols[si + 1]) - SectionAddr;
1515 // Don't try to disassemble beyond the end of section contents.
1516 if (End > SectSize)
1517 End = SectSize;
1518 // If this symbol has the same address as the next symbol, then skip it.
1519 if (Start >= End)
1520 continue;
1521
1522 // Check if we need to skip symbol
1523 // Skip if the symbol's data is not between StartAddress and StopAddress
1524 if (End + SectionAddr < StartAddress ||
1525 Start + SectionAddr > StopAddress) {
1526 continue;
1527 }
1528
1529 /// Skip if user requested specific symbols and this is not in the list
1530 if (!DisasmFuncsSet.empty() &&
1531 !DisasmFuncsSet.count(std::get<1>(Symbols[si])))
1532 continue;
1533
1534 if (!PrintedSection) {
1535 PrintedSection = true;
1536 outs() << "Disassembly of section ";
1537 if (!SegmentName.empty())
1538 outs() << SegmentName << ",";
1539 outs() << SectionName << ':';
1540 }
1541
1542 // Stop disassembly at the stop address specified
1543 if (End + SectionAddr > StopAddress)
1544 End = StopAddress - SectionAddr;
1545
1546 if (Obj->isELF() && Obj->getArch() == Triple::amdgcn) {
1547 if (std::get<2>(Symbols[si]) == ELF::STT_AMDGPU_HSA_KERNEL) {
1548 // skip amd_kernel_code_t at the begining of kernel symbol (256 bytes)
1549 Start += 256;
1550 }
1551 if (si == se - 1 ||
1552 std::get<2>(Symbols[si + 1]) == ELF::STT_AMDGPU_HSA_KERNEL) {
1553 // cut trailing zeroes at the end of kernel
1554 // cut up to 256 bytes
1555 const uint64_t EndAlign = 256;
1556 const auto Limit = End - (std::min)(EndAlign, End - Start);
1557 while (End > Limit &&
1558 *reinterpret_cast<const support::ulittle32_t*>(&Bytes[End - 4]) == 0)
1559 End -= 4;
1560 }
1561 }
1562
1563 auto PrintSymbol = [](StringRef Name) {
1564 outs() << '\n' << Name << ":\n";
1565 };
1566 StringRef SymbolName = std::get<1>(Symbols[si]);
1567 if (Demangle) {
1568 char *DemangledSymbol = nullptr;
1569 size_t Size = 0;
1570 int Status = -1;
1571 if (SymbolName.startswith("_Z"))
1572 DemangledSymbol = itaniumDemangle(SymbolName.data(), DemangledSymbol,
1573 &Size, &Status);
1574 else if (SymbolName.startswith("?"))
1575 DemangledSymbol = microsoftDemangle(SymbolName.data(),
1576 DemangledSymbol, &Size, &Status);
1577
1578 if (Status == 0 && DemangledSymbol)
1579 PrintSymbol(StringRef(DemangledSymbol));
1580 else
1581 PrintSymbol(SymbolName);
1582
1583 if (DemangledSymbol)
1584 free(DemangledSymbol);
1585 } else
1586 PrintSymbol(SymbolName);
1587
1588 // Don't print raw contents of a virtual section. A virtual section
1589 // doesn't have any contents in the file.
1590 if (Section.isVirtual()) {
1591 outs() << "...\n";
1592 continue;
1593 }
1594
1595#ifndef NDEBUG
1596 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
1597#else
1598 raw_ostream &DebugOut = nulls();
1599#endif
1600
1601 for (Index = Start; Index < End; Index += Size) {
1602 MCInst Inst;
1603
1604 if (Index + SectionAddr < StartAddress ||
1605 Index + SectionAddr > StopAddress) {
1606 // skip byte by byte till StartAddress is reached
1607 Size = 1;
1608 continue;
1609 }
1610 // AArch64 ELF binaries can interleave data and text in the
1611 // same section. We rely on the markers introduced to
1612 // understand what we need to dump. If the data marker is within a
1613 // function, it is denoted as a word/short etc
1614 if (isArmElf(Obj) && std::get<2>(Symbols[si]) != ELF::STT_OBJECT &&
1615 !DisassembleAll) {
1616 uint64_t Stride = 0;
1617
1618 auto DAI = std::lower_bound(DataMappingSymsAddr.begin(),
1619 DataMappingSymsAddr.end(), Index);
1620 if (DAI != DataMappingSymsAddr.end() && *DAI == Index) {
1621 // Switch to data.
1622 while (Index < End) {
1623 outs() << format("%8" PRIx64"l" "x" ":", SectionAddr + Index);
1624 outs() << "\t";
1625 if (Index + 4 <= End) {
1626 Stride = 4;
1627 dumpBytes(Bytes.slice(Index, 4), outs());
1628 outs() << "\t.word\t";
1629 uint32_t Data = 0;
1630 if (Obj->isLittleEndian()) {
1631 const auto Word =
1632 reinterpret_cast<const support::ulittle32_t *>(
1633 Bytes.data() + Index);
1634 Data = *Word;
1635 } else {
1636 const auto Word = reinterpret_cast<const support::ubig32_t *>(
1637 Bytes.data() + Index);
1638 Data = *Word;
1639 }
1640 outs() << "0x" << format("%08" PRIx32"x", Data);
1641 } else if (Index + 2 <= End) {
1642 Stride = 2;
1643 dumpBytes(Bytes.slice(Index, 2), outs());
1644 outs() << "\t\t.short\t";
1645 uint16_t Data = 0;
1646 if (Obj->isLittleEndian()) {
1647 const auto Short =
1648 reinterpret_cast<const support::ulittle16_t *>(
1649 Bytes.data() + Index);
1650 Data = *Short;
1651 } else {
1652 const auto Short =
1653 reinterpret_cast<const support::ubig16_t *>(Bytes.data() +
1654 Index);
1655 Data = *Short;
1656 }
1657 outs() << "0x" << format("%04" PRIx16"x", Data);
1658 } else {
1659 Stride = 1;
1660 dumpBytes(Bytes.slice(Index, 1), outs());
1661 outs() << "\t\t.byte\t";
1662 outs() << "0x" << format("%02" PRIx8"x", Bytes.slice(Index, 1)[0]);
1663 }
1664 Index += Stride;
1665 outs() << "\n";
1666 auto TAI = std::lower_bound(TextMappingSymsAddr.begin(),
1667 TextMappingSymsAddr.end(), Index);
1668 if (TAI != TextMappingSymsAddr.end() && *TAI == Index)
1669 break;
1670 }
1671 }
1672 }
1673
1674 // If there is a data symbol inside an ELF text section and we are only
1675 // disassembling text (applicable all architectures),
1676 // we are in a situation where we must print the data and not
1677 // disassemble it.
1678 if (Obj->isELF() && std::get<2>(Symbols[si]) == ELF::STT_OBJECT &&
1679 !DisassembleAll && Section.isText()) {
1680 // print out data up to 8 bytes at a time in hex and ascii
1681 uint8_t AsciiData[9] = {'\0'};
1682 uint8_t Byte;
1683 int NumBytes = 0;
1684
1685 for (Index = Start; Index < End; Index += 1) {
1686 if (((SectionAddr + Index) < StartAddress) ||
1687 ((SectionAddr + Index) > StopAddress))
1688 continue;
1689 if (NumBytes == 0) {
1690 outs() << format("%8" PRIx64"l" "x" ":", SectionAddr + Index);
1691 outs() << "\t";
1692 }
1693 Byte = Bytes.slice(Index)[0];
1694 outs() << format(" %02x", Byte);
1695 AsciiData[NumBytes] = isPrint(Byte) ? Byte : '.';
1696
1697 uint8_t IndentOffset = 0;
1698 NumBytes++;
1699 if (Index == End - 1 || NumBytes > 8) {
1700 // Indent the space for less than 8 bytes data.
1701 // 2 spaces for byte and one for space between bytes
1702 IndentOffset = 3 * (8 - NumBytes);
1703 for (int Excess = 8 - NumBytes; Excess < 8; Excess++)
1704 AsciiData[Excess] = '\0';
1705 NumBytes = 8;
1706 }
1707 if (NumBytes == 8) {
1708 AsciiData[8] = '\0';
1709 outs() << std::string(IndentOffset, ' ') << " ";
1710 outs() << reinterpret_cast<char *>(AsciiData);
1711 outs() << '\n';
1712 NumBytes = 0;
1713 }
1714 }
1715 }
1716 if (Index >= End)
1717 break;
1718
1719 // Disassemble a real instruction or a data when disassemble all is
1720 // provided
1721 bool Disassembled = DisAsm->getInstruction(Inst, Size, Bytes.slice(Index),
1722 SectionAddr + Index, DebugOut,
1723 CommentStream);
1724 if (Size == 0)
1725 Size = 1;
1726
1727 PIP.printInst(*IP, Disassembled ? &Inst : nullptr,
1728 Bytes.slice(Index, Size), SectionAddr + Index, outs(), "",
1729 *STI, &SP, &Rels);
1730 outs() << CommentStream.str();
1731 Comments.clear();
1732
1733 // Try to resolve the target of a call, tail call, etc. to a specific
1734 // symbol.
1735 if (MIA && (MIA->isCall(Inst) || MIA->isUnconditionalBranch(Inst) ||
1736 MIA->isConditionalBranch(Inst))) {
1737 uint64_t Target;
1738 if (MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target)) {
1739 // In a relocatable object, the target's section must reside in
1740 // the same section as the call instruction or it is accessed
1741 // through a relocation.
1742 //
1743 // In a non-relocatable object, the target may be in any section.
1744 //
1745 // N.B. We don't walk the relocations in the relocatable case yet.
1746 auto *TargetSectionSymbols = &Symbols;
1747 if (!Obj->isRelocatableObject()) {
1748 auto SectionAddress = std::upper_bound(
1749 SectionAddresses.begin(), SectionAddresses.end(), Target,
1750 [](uint64_t LHS,
1751 const std::pair<uint64_t, SectionRef> &RHS) {
1752 return LHS < RHS.first;
1753 });
1754 if (SectionAddress != SectionAddresses.begin()) {
1755 --SectionAddress;
1756 TargetSectionSymbols = &AllSymbols[SectionAddress->second];
1757 } else {
1758 TargetSectionSymbols = &AbsoluteSymbols;
1759 }
1760 }
1761
1762 // Find the first symbol in the section whose offset is less than
1763 // or equal to the target. If there isn't a section that contains
1764 // the target, find the nearest preceding absolute symbol.
1765 auto TargetSym = std::upper_bound(
1766 TargetSectionSymbols->begin(), TargetSectionSymbols->end(),
1767 Target, [](uint64_t LHS,
1768 const std::tuple<uint64_t, StringRef, uint8_t> &RHS) {
1769 return LHS < std::get<0>(RHS);
1770 });
1771 if (TargetSym == TargetSectionSymbols->begin()) {
1772 TargetSectionSymbols = &AbsoluteSymbols;
1773 TargetSym = std::upper_bound(
1774 AbsoluteSymbols.begin(), AbsoluteSymbols.end(),
1775 Target, [](uint64_t LHS,
1776 const std::tuple<uint64_t, StringRef, uint8_t> &RHS) {
1777 return LHS < std::get<0>(RHS);
1778 });
1779 }
1780 if (TargetSym != TargetSectionSymbols->begin()) {
1781 --TargetSym;
1782 uint64_t TargetAddress = std::get<0>(*TargetSym);
1783 StringRef TargetName = std::get<1>(*TargetSym);
1784 outs() << " <" << TargetName;
1785 uint64_t Disp = Target - TargetAddress;
1786 if (Disp)
1787 outs() << "+0x" << Twine::utohexstr(Disp);
1788 outs() << '>';
1789 }
1790 }
1791 }
1792 outs() << "\n";
1793
1794 // Hexagon does this in pretty printer
1795 if (Obj->getArch() != Triple::hexagon)
1796 // Print relocation for instruction.
1797 while (rel_cur != rel_end) {
1798 bool hidden = getHidden(*rel_cur);
1799 uint64_t addr = rel_cur->getOffset();
1800 SmallString<16> name;
1801 SmallString<32> val;
1802
1803 // If this relocation is hidden, skip it.
1804 if (hidden || ((SectionAddr + addr) < StartAddress)) {
1805 ++rel_cur;
1806 continue;
1807 }
1808
1809 // Stop when rel_cur's address is past the current instruction.
1810 if (addr >= Index + Size) break;
1811 rel_cur->getTypeName(name);
1812 error(getRelocationValueString(*rel_cur, val));
1813 outs() << format(Fmt.data(), SectionAddr + addr) << name
1814 << "\t" << val << "\n";
1815 ++rel_cur;
1816 }
1817 }
1818 }
1819 }
1820}
1821
1822void llvm::PrintRelocations(const ObjectFile *Obj) {
1823 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64"l" "x" :
1824 "%08" PRIx64"l" "x";
1825 // Regular objdump doesn't print relocations in non-relocatable object
1826 // files.
1827 if (!Obj->isRelocatableObject())
1828 return;
1829
1830 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1831 if (Section.relocation_begin() == Section.relocation_end())
1832 continue;
1833 StringRef secname;
1834 error(Section.getName(secname));
1835 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
1836 for (const RelocationRef &Reloc : Section.relocations()) {
1837 bool hidden = getHidden(Reloc);
1838 uint64_t address = Reloc.getOffset();
1839 SmallString<32> relocname;
1840 SmallString<32> valuestr;
1841 if (address < StartAddress || address > StopAddress || hidden)
1842 continue;
1843 Reloc.getTypeName(relocname);
1844 error(getRelocationValueString(Reloc, valuestr));
1845 outs() << format(Fmt.data(), address) << " " << relocname << " "
1846 << valuestr << "\n";
1847 }
1848 outs() << "\n";
1849 }
1850}
1851
1852void llvm::PrintDynamicRelocations(const ObjectFile *Obj) {
1853
1854 // For the moment, this option is for ELF only
1855 if (!Obj->isELF())
1856 return;
1857
1858 const auto *Elf = dyn_cast<ELFObjectFileBase>(Obj);
1859
1860 if (!Elf || Elf->getEType() != ELF::ET_DYN) {
1861 error("not a dynamic object");
1862 return;
1863 }
1864
1865 StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64"l" "x" : "%08" PRIx64"l" "x";
1866
1867 std::vector<SectionRef> DynRelSec = Obj->dynamic_relocation_sections();
1868 if (DynRelSec.empty())
1869 return;
1870
1871 outs() << "DYNAMIC RELOCATION RECORDS\n";
1872 for (const SectionRef &Section : DynRelSec) {
1873 if (Section.relocation_begin() == Section.relocation_end())
1874 continue;
1875 for (const RelocationRef &Reloc : Section.relocations()) {
1876 uint64_t address = Reloc.getOffset();
1877 SmallString<32> relocname;
1878 SmallString<32> valuestr;
1879 Reloc.getTypeName(relocname);
1880 error(getRelocationValueString(Reloc, valuestr));
1881 outs() << format(Fmt.data(), address) << " " << relocname << " "
1882 << valuestr << "\n";
1883 }
1884 }
1885}
1886
1887void llvm::PrintSectionHeaders(const ObjectFile *Obj) {
1888 outs() << "Sections:\n"
1889 "Idx Name Size Address Type\n";
1890 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1891 StringRef Name;
1892 error(Section.getName(Name));
1893 uint64_t Address = Section.getAddress();
1894 uint64_t Size = Section.getSize();
1895 bool Text = Section.isText();
1896 bool Data = Section.isData();
1897 bool BSS = Section.isBSS();
1898 std::string Type = (std::string(Text ? "TEXT " : "") +
1899 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
1900 outs() << format("%3d %-13s %08" PRIx64"l" "x" " %016" PRIx64"l" "x" " %s\n",
1901 (unsigned)Section.getIndex(), Name.str().c_str(), Size,
1902 Address, Type.c_str());
1903 }
1904}
1905
1906void llvm::PrintSectionContents(const ObjectFile *Obj) {
1907 std::error_code EC;
1908 for (const SectionRef &Section : ToolSectionFilter(*Obj)) {
1909 StringRef Name;
1910 StringRef Contents;
1911 error(Section.getName(Name));
1912 uint64_t BaseAddr = Section.getAddress();
1913 uint64_t Size = Section.getSize();
1914 if (!Size)
1915 continue;
1916
1917 outs() << "Contents of section " << Name << ":\n";
1918 if (Section.isBSS()) {
1919 outs() << format("<skipping contents of bss section at [%04" PRIx64"l" "x"
1920 ", %04" PRIx64"l" "x" ")>\n",
1921 BaseAddr, BaseAddr + Size);
1922 continue;
1923 }
1924
1925 error(Section.getContents(Contents));
1926
1927 // Dump out the content as hex and printable ascii characters.
1928 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
1929 outs() << format(" %04" PRIx64"l" "x" " ", BaseAddr + addr);
1930 // Dump line of hex.
1931 for (std::size_t i = 0; i < 16; ++i) {
1932 if (i != 0 && i % 4 == 0)
1933 outs() << ' ';
1934 if (addr + i < end)
1935 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
1936 << hexdigit(Contents[addr + i] & 0xF, true);
1937 else
1938 outs() << " ";
1939 }
1940 // Print ascii.
1941 outs() << " ";
1942 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
1943 if (isPrint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
1944 outs() << Contents[addr + i];
1945 else
1946 outs() << ".";
1947 }
1948 outs() << "\n";
1949 }
1950 }
1951}
1952
1953void llvm::PrintSymbolTable(const ObjectFile *o, StringRef ArchiveName,
1954 StringRef ArchitectureName) {
1955 outs() << "SYMBOL TABLE:\n";
1956
1957 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
1958 printCOFFSymbolTable(coff);
1959 return;
1960 }
1961 for (const SymbolRef &Symbol : o->symbols()) {
1962 Expected<uint64_t> AddressOrError = Symbol.getAddress();
1963 if (!AddressOrError)
1964 report_error(ArchiveName, o->getFileName(), AddressOrError.takeError(),
1965 ArchitectureName);
1966 uint64_t Address = *AddressOrError;
1967 if ((Address < StartAddress) || (Address > StopAddress))
1968 continue;
1969 Expected<SymbolRef::Type> TypeOrError = Symbol.getType();
1970 if (!TypeOrError)
1971 report_error(ArchiveName, o->getFileName(), TypeOrError.takeError(),
1972 ArchitectureName);
1973 SymbolRef::Type Type = *TypeOrError;
1974 uint32_t Flags = Symbol.getFlags();
1975 Expected<section_iterator> SectionOrErr = Symbol.getSection();
1976 if (!SectionOrErr)
1977 report_error(ArchiveName, o->getFileName(), SectionOrErr.takeError(),
1978 ArchitectureName);
1979 section_iterator Section = *SectionOrErr;
1980 StringRef Name;
1981 if (Type == SymbolRef::ST_Debug && Section != o->section_end()) {
1982 Section->getName(Name);
1983 } else {
1984 Expected<StringRef> NameOrErr = Symbol.getName();
1985 if (!NameOrErr)
1986 report_error(ArchiveName, o->getFileName(), NameOrErr.takeError(),
1987 ArchitectureName);
1988 Name = *NameOrErr;
1989 }
1990
1991 bool Global = Flags & SymbolRef::SF_Global;
1992 bool Weak = Flags & SymbolRef::SF_Weak;
1993 bool Absolute = Flags & SymbolRef::SF_Absolute;
1994 bool Common = Flags & SymbolRef::SF_Common;
1995 bool Hidden = Flags & SymbolRef::SF_Hidden;
1996
1997 char GlobLoc = ' ';
1998 if (Type != SymbolRef::ST_Unknown)
1999 GlobLoc = Global ? 'g' : 'l';
2000 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
2001 ? 'd' : ' ';
2002 char FileFunc = ' ';
2003 if (Type == SymbolRef::ST_File)
2004 FileFunc = 'f';
2005 else if (Type == SymbolRef::ST_Function)
2006 FileFunc = 'F';
2007
2008 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64"l" "x" :
2009 "%08" PRIx64"l" "x";
2010
2011 outs() << format(Fmt, Address) << " "
2012 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
2013 << (Weak ? 'w' : ' ') // Weak?
2014 << ' ' // Constructor. Not supported yet.
2015 << ' ' // Warning. Not supported yet.
2016 << ' ' // Indirect reference to another symbol.
2017 << Debug // Debugging (d) or dynamic (D) symbol.
2018 << FileFunc // Name of function (F), file (f) or object (O).
2019 << ' ';
2020 if (Absolute) {
2021 outs() << "*ABS*";
2022 } else if (Common) {
2023 outs() << "*COM*";
2024 } else if (Section == o->section_end()) {
2025 outs() << "*UND*";
2026 } else {
2027 if (const MachOObjectFile *MachO =
2028 dyn_cast<const MachOObjectFile>(o)) {
2029 DataRefImpl DR = Section->getRawDataRefImpl();
2030 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
2031 outs() << SegmentName << ",";
2032 }
2033 StringRef SectionName;
2034 error(Section->getName(SectionName));
2035 outs() << SectionName;
2036 }
2037
2038 outs() << '\t';
2039 if (Common || isa<ELFObjectFileBase>(o)) {
2040 uint64_t Val =
2041 Common ? Symbol.getAlignment() : ELFSymbolRef(Symbol).getSize();
2042 outs() << format("\t %08" PRIx64"l" "x" " ", Val);
2043 }
2044
2045 if (Hidden) {
2046 outs() << ".hidden ";
2047 }
2048 outs() << Name
2049 << '\n';
2050 }
2051}
2052
2053static void PrintUnwindInfo(const ObjectFile *o) {
2054 outs() << "Unwind info:\n\n";
2055
2056 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
2057 printCOFFUnwindInfo(coff);
2058 } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
2059 printMachOUnwindInfo(MachO);
2060 else {
2061 // TODO: Extract DWARF dump tool to objdump.
2062 errs() << "This operation is only currently supported "
2063 "for COFF and MachO object files.\n";
2064 return;
2065 }
2066}
2067
2068void llvm::printExportsTrie(const ObjectFile *o) {
2069 outs() << "Exports trie:\n";
2070 if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
2071 printMachOExportsTrie(MachO);
2072 else {
2073 errs() << "This operation is only currently supported "
2074 "for Mach-O executable files.\n";
2075 return;
2076 }
2077}
2078
2079void llvm::printRebaseTable(ObjectFile *o) {
2080 outs() << "Rebase table:\n";
2081 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
2082 printMachORebaseTable(MachO);
2083 else {
2084 errs() << "This operation is only currently supported "
2085 "for Mach-O executable files.\n";
2086 return;
2087 }
2088}
2089
2090void llvm::printBindTable(ObjectFile *o) {
2091 outs() << "Bind table:\n";
2092 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
2093 printMachOBindTable(MachO);
2094 else {
2095 errs() << "This operation is only currently supported "
2096 "for Mach-O executable files.\n";
2097 return;
2098 }
2099}
2100
2101void llvm::printLazyBindTable(ObjectFile *o) {
2102 outs() << "Lazy bind table:\n";
2103 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
2104 printMachOLazyBindTable(MachO);
2105 else {
2106 errs() << "This operation is only currently supported "
2107 "for Mach-O executable files.\n";
2108 return;
2109 }
2110}
2111
2112void llvm::printWeakBindTable(ObjectFile *o) {
2113 outs() << "Weak bind table:\n";
2114 if (MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
2115 printMachOWeakBindTable(MachO);
2116 else {
2117 errs() << "This operation is only currently supported "
2118 "for Mach-O executable files.\n";
2119 return;
2120 }
2121}
2122
2123/// Dump the raw contents of the __clangast section so the output can be piped
2124/// into llvm-bcanalyzer.
2125void llvm::printRawClangAST(const ObjectFile *Obj) {
2126 if (outs().is_displayed()) {
2127 errs() << "The -raw-clang-ast option will dump the raw binary contents of "
2128 "the clang ast section.\n"
2129 "Please redirect the output to a file or another program such as "
2130 "llvm-bcanalyzer.\n";
2131 return;
2132 }
2133
2134 StringRef ClangASTSectionName("__clangast");
2135 if (isa<COFFObjectFile>(Obj)) {
2136 ClangASTSectionName = "clangast";
2137 }
2138
2139 Optional<object::SectionRef> ClangASTSection;
2140 for (auto Sec : ToolSectionFilter(*Obj)) {
2141 StringRef Name;
2142 Sec.getName(Name);
2143 if (Name == ClangASTSectionName) {
2144 ClangASTSection = Sec;
2145 break;
2146 }
2147 }
2148 if (!ClangASTSection)
2149 return;
2150
2151 StringRef ClangASTContents;
2152 error(ClangASTSection.getValue().getContents(ClangASTContents));
2153 outs().write(ClangASTContents.data(), ClangASTContents.size());
2154}
2155
2156static void printFaultMaps(const ObjectFile *Obj) {
2157 const char *FaultMapSectionName = nullptr;
2158
2159 if (isa<ELFObjectFileBase>(Obj)) {
2160 FaultMapSectionName = ".llvm_faultmaps";
2161 } else if (isa<MachOObjectFile>(Obj)) {
2162 FaultMapSectionName = "__llvm_faultmaps";
2163 } else {
2164 errs() << "This operation is only currently supported "
2165 "for ELF and Mach-O executable files.\n";
2166 return;
2167 }
2168
2169 Optional<object::SectionRef> FaultMapSection;
2170
2171 for (auto Sec : ToolSectionFilter(*Obj)) {
2172 StringRef Name;
2173 Sec.getName(Name);
2174 if (Name == FaultMapSectionName) {
2175 FaultMapSection = Sec;
2176 break;
2177 }
2178 }
2179
2180 outs() << "FaultMap table:\n";
2181
2182 if (!FaultMapSection.hasValue()) {
2183 outs() << "<not found>\n";
2184 return;
2185 }
2186
2187 StringRef FaultMapContents;
2188 error(FaultMapSection.getValue().getContents(FaultMapContents));
2189
2190 FaultMapParser FMP(FaultMapContents.bytes_begin(),
2191 FaultMapContents.bytes_end());
2192
2193 outs() << FMP;
2194}
2195
2196static void printPrivateFileHeaders(const ObjectFile *o, bool onlyFirst) {
2197 if (o->isELF()) {
2198 printELFFileHeader(o);
2199 return printELFDynamicSection(o);
2200 }
2201 if (o->isCOFF())
2202 return printCOFFFileHeader(o);
2203 if (o->isWasm())
2204 return printWasmFileHeader(o);
2205 if (o->isMachO()) {
2206 printMachOFileHeader(o);
2207 if (!onlyFirst)
2208 printMachOLoadCommands(o);
2209 return;
2210 }
2211 report_error(o->getFileName(), "Invalid/Unsupported object file format");
2212}
2213
2214static void printFileHeaders(const ObjectFile *o) {
2215 if (!o->isELF() && !o->isCOFF())
2216 report_error(o->getFileName(), "Invalid/Unsupported object file format");
2217
2218 Triple::ArchType AT = o->getArch();
2219 outs() << "architecture: " << Triple::getArchTypeName(AT) << "\n";
2220 Expected<uint64_t> StartAddrOrErr = o->getStartAddress();
2221 if (!StartAddrOrErr)
2222 report_error(o->getFileName(), StartAddrOrErr.takeError());
2223
2224 StringRef Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64"l" "x" : "%08" PRIx64"l" "x";
2225 uint64_t Address = StartAddrOrErr.get();
2226 outs() << "start address: "
2227 << "0x" << format(Fmt.data(), Address)
2228 << "\n";
2229}
2230
2231static void printArchiveChild(StringRef Filename, const Archive::Child &C) {
2232 Expected<sys::fs::perms> ModeOrErr = C.getAccessMode();
2233 if (!ModeOrErr) {
2234 errs() << "ill-formed archive entry.\n";
2235 consumeError(ModeOrErr.takeError());
2236 return;
2237 }
2238 sys::fs::perms Mode = ModeOrErr.get();
2239 outs() << ((Mode & sys::fs::owner_read) ? "r" : "-");
2240 outs() << ((Mode & sys::fs::owner_write) ? "w" : "-");
2241 outs() << ((Mode & sys::fs::owner_exe) ? "x" : "-");
2242 outs() << ((Mode & sys::fs::group_read) ? "r" : "-");
2243 outs() << ((Mode & sys::fs::group_write) ? "w" : "-");
2244 outs() << ((Mode & sys::fs::group_exe) ? "x" : "-");
2245 outs() << ((Mode & sys::fs::others_read) ? "r" : "-");
2246 outs() << ((Mode & sys::fs::others_write) ? "w" : "-");
2247 outs() << ((Mode & sys::fs::others_exe) ? "x" : "-");
2248
2249 outs() << " ";
2250
2251 Expected<unsigned> UIDOrErr = C.getUID();
2252 if (!UIDOrErr)
2253 report_error(Filename, UIDOrErr.takeError());
2254 unsigned UID = UIDOrErr.get();
2255 outs() << format("%d/", UID);
2256
2257 Expected<unsigned> GIDOrErr = C.getGID();
2258 if (!GIDOrErr)
2259 report_error(Filename, GIDOrErr.takeError());
2260 unsigned GID = GIDOrErr.get();
2261 outs() << format("%-d ", GID);
2262
2263 Expected<uint64_t> Size = C.getRawSize();
2264 if (!Size)
2265 report_error(Filename, Size.takeError());
2266 outs() << format("%6" PRId64"l" "d", Size.get()) << " ";
2267
2268 StringRef RawLastModified = C.getRawLastModified();
2269 unsigned Seconds;
2270 if (RawLastModified.getAsInteger(10, Seconds))
2271 outs() << "(date: \"" << RawLastModified
2272 << "\" contains non-decimal chars) ";
2273 else {
2274 // Since ctime(3) returns a 26 character string of the form:
2275 // "Sun Sep 16 01:03:52 1973\n\0"
2276 // just print 24 characters.
2277 time_t t = Seconds;
2278 outs() << format("%.24s ", ctime(&t));
2279 }
2280
2281 StringRef Name = "";
2282 Expected<StringRef> NameOrErr = C.getName();
2283 if (!NameOrErr) {
2284 consumeError(NameOrErr.takeError());
2285 Expected<StringRef> RawNameOrErr = C.getRawName();
2286 if (!RawNameOrErr)
2287 report_error(Filename, NameOrErr.takeError());
2288 Name = RawNameOrErr.get();
2289 } else {
2290 Name = NameOrErr.get();
2291 }
2292 outs() << Name << "\n";
2293}
2294
2295static void DumpObject(ObjectFile *o, const Archive *a = nullptr,
2296 const Archive::Child *c = nullptr) {
2297 StringRef ArchiveName = a != nullptr ? a->getFileName() : "";
2298 // Avoid other output when using a raw option.
2299 if (!RawClangAST) {
2300 outs() << '\n';
2301 if (a)
2302 outs() << a->getFileName() << "(" << o->getFileName() << ")";
2303 else
2304 outs() << o->getFileName();
2305 outs() << ":\tfile format " << o->getFileFormatName() << "\n\n";
2306 }
2307
2308 if (ArchiveHeaders && !MachOOpt)
2309 printArchiveChild(a->getFileName(), *c);
2310 if (Disassemble)
2311 DisassembleObject(o, Relocations);
2312 if (Relocations && !Disassemble)
2313 PrintRelocations(o);
2314 if (DynamicRelocations)
2315 PrintDynamicRelocations(o);
2316 if (SectionHeaders)
2317 PrintSectionHeaders(o);
2318 if (SectionContents)
2319 PrintSectionContents(o);
2320 if (SymbolTable)
2321 PrintSymbolTable(o, ArchiveName);
2322 if (UnwindInfo)
2323 PrintUnwindInfo(o);
2324 if (PrivateHeaders || FirstPrivateHeader)
2325 printPrivateFileHeaders(o, FirstPrivateHeader);
2326 if (FileHeaders)
2327 printFileHeaders(o);
2328 if (ExportsTrie)
2329 printExportsTrie(o);
2330 if (Rebase)
2331 printRebaseTable(o);
2332 if (Bind)
2333 printBindTable(o);
2334 if (LazyBind)
2335 printLazyBindTable(o);
2336 if (WeakBind)
2337 printWeakBindTable(o);
2338 if (RawClangAST)
2339 printRawClangAST(o);
2340 if (PrintFaultMaps)
2341 printFaultMaps(o);
2342 if (DwarfDumpType != DIDT_Null) {
2343 std::unique_ptr<DIContext> DICtx = DWARFContext::create(*o);
2344 // Dump the complete DWARF structure.
2345 DIDumpOptions DumpOpts;
2346 DumpOpts.DumpType = DwarfDumpType;
2347 DICtx->dump(outs(), DumpOpts);
2348 }
2349}
2350
2351static void DumpObject(const COFFImportFile *I, const Archive *A,
2352 const Archive::Child *C = nullptr) {
2353 StringRef ArchiveName = A ? A->getFileName() : "";
2354
2355 // Avoid other output when using a raw option.
2356 if (!RawClangAST)
2357 outs() << '\n'
2358 << ArchiveName << "(" << I->getFileName() << ")"
2359 << ":\tfile format COFF-import-file"
2360 << "\n\n";
2361
2362 if (ArchiveHeaders && !MachOOpt)
2363 printArchiveChild(A->getFileName(), *C);
2364 if (SymbolTable)
2365 printCOFFSymbolTable(I);
2366}
2367
2368/// Dump each object file in \a a;
2369static void DumpArchive(const Archive *a) {
2370 Error Err = Error::success();
2371 for (auto &C : a->children(Err)) {
2372 Expected<std::unique_ptr<Binary>> ChildOrErr = C.getAsBinary();
2373 if (!ChildOrErr) {
2374 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
2375 report_error(a->getFileName(), C, std::move(E));
2376 continue;
2377 }
2378 if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
2379 DumpObject(o, a, &C);
2380 else if (COFFImportFile *I = dyn_cast<COFFImportFile>(&*ChildOrErr.get()))
2381 DumpObject(I, a, &C);
2382 else
2383 report_error(a->getFileName(), object_error::invalid_file_type);
2384 }
2385 if (Err)
2386 report_error(a->getFileName(), std::move(Err));
2387}
2388
2389/// Open file and figure out how to dump it.
2390static void DumpInput(StringRef file) {
2391
2392 // If we are using the Mach-O specific object file parser, then let it parse
2393 // the file and process the command line options. So the -arch flags can
2394 // be used to select specific slices, etc.
2395 if (MachOOpt) {
2396 ParseInputMachO(file);
2397 return;
2398 }
2399
2400 // Attempt to open the binary.
2401 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
2402 if (!BinaryOrErr)
2403 report_error(file, BinaryOrErr.takeError());
2404 Binary &Binary = *BinaryOrErr.get().getBinary();
2405
2406 if (Archive *a = dyn_cast<Archive>(&Binary))
2407 DumpArchive(a);
2408 else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
2409 DumpObject(o);
2410 else if (MachOUniversalBinary *UB = dyn_cast<MachOUniversalBinary>(&Binary))
2411 ParseInputMachO(UB);
2412 else
2413 report_error(file, object_error::invalid_file_type);
2414}
2415
2416int main(int argc, char **argv) {
2417 InitLLVM X(argc, argv);
2418
2419 // Initialize targets and assembly printers/parsers.
2420 llvm::InitializeAllTargetInfos();
2421 llvm::InitializeAllTargetMCs();
2422 llvm::InitializeAllDisassemblers();
2423
2424 // Register the target printer for --version.
2425 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
2426
2427 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
2428
2429 ToolName = argv[0];
2430
2431 // Defaults to a.out if no filenames specified.
2432 if (InputFilenames.size() == 0)
2433 InputFilenames.push_back("a.out");
2434
2435 if (AllHeaders)
2436 PrivateHeaders = Relocations = SectionHeaders = SymbolTable = true;
2437
2438 if (DisassembleAll || PrintSource || PrintLines)
2439 Disassemble = true;
2440
2441 if (!Disassemble
2442 && !Relocations
2443 && !DynamicRelocations
2444 && !SectionHeaders
2445 && !SectionContents
2446 && !SymbolTable
2447 && !UnwindInfo
2448 && !PrivateHeaders
2449 && !FileHeaders
2450 && !FirstPrivateHeader
2451 && !ExportsTrie
2452 && !Rebase
2453 && !Bind
2454 && !LazyBind
2455 && !WeakBind
2456 && !RawClangAST
2457 && !(UniversalHeaders && MachOOpt)
2458 && !ArchiveHeaders
2459 && !(IndirectSymbols && MachOOpt)
2460 && !(DataInCode && MachOOpt)
2461 && !(LinkOptHints && MachOOpt)
2462 && !(InfoPlist && MachOOpt)
2463 && !(DylibsUsed && MachOOpt)
2464 && !(DylibId && MachOOpt)
2465 && !(ObjcMetaData && MachOOpt)
2466 && !(FilterSections.size() != 0 && MachOOpt)
2467 && !PrintFaultMaps
2468 && DwarfDumpType == DIDT_Null) {
2469 cl::PrintHelpMessage();
2470 return 2;
2471 }
2472
2473 DisasmFuncsSet.insert(DisassembleFunctions.begin(),
2474 DisassembleFunctions.end());
2475
2476 llvm::for_each(InputFilenames, DumpInput);
2477
2478 return EXIT_SUCCESS0;
2479}

/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Object/ELFObjectFile.h

1//===- ELFObjectFile.h - ELF object file implementation ---------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file declares the ELFObjectFile template class.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_OBJECT_ELFOBJECTFILE_H
15#define LLVM_OBJECT_ELFOBJECTFILE_H
16
17#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/STLExtras.h"
19#include "llvm/ADT/SmallVector.h"
20#include "llvm/ADT/StringRef.h"
21#include "llvm/ADT/Triple.h"
22#include "llvm/ADT/iterator_range.h"
23#include "llvm/BinaryFormat/ELF.h"
24#include "llvm/MC/SubtargetFeature.h"
25#include "llvm/Object/Binary.h"
26#include "llvm/Object/ELF.h"
27#include "llvm/Object/ELFTypes.h"
28#include "llvm/Object/Error.h"
29#include "llvm/Object/ObjectFile.h"
30#include "llvm/Object/SymbolicFile.h"
31#include "llvm/Support/ARMAttributeParser.h"
32#include "llvm/Support/ARMBuildAttributes.h"
33#include "llvm/Support/Casting.h"
34#include "llvm/Support/Endian.h"
35#include "llvm/Support/Error.h"
36#include "llvm/Support/ErrorHandling.h"
37#include "llvm/Support/MemoryBuffer.h"
38#include <cassert>
39#include <cstdint>
40#include <system_error>
41
42namespace llvm {
43namespace object {
44
45class elf_symbol_iterator;
46
47class ELFObjectFileBase : public ObjectFile {
48 friend class ELFRelocationRef;
49 friend class ELFSectionRef;
50 friend class ELFSymbolRef;
51
52protected:
53 ELFObjectFileBase(unsigned int Type, MemoryBufferRef Source);
54
55 virtual uint16_t getEMachine() const = 0;
56 virtual uint64_t getSymbolSize(DataRefImpl Symb) const = 0;
57 virtual uint8_t getSymbolOther(DataRefImpl Symb) const = 0;
58 virtual uint8_t getSymbolELFType(DataRefImpl Symb) const = 0;
59
60 virtual uint32_t getSectionType(DataRefImpl Sec) const = 0;
61 virtual uint64_t getSectionFlags(DataRefImpl Sec) const = 0;
62 virtual uint64_t getSectionOffset(DataRefImpl Sec) const = 0;
63
64 virtual Expected<int64_t> getRelocationAddend(DataRefImpl Rel) const = 0;
65
66public:
67 using elf_symbol_iterator_range = iterator_range<elf_symbol_iterator>;
68
69 virtual elf_symbol_iterator_range getDynamicSymbolIterators() const = 0;
70
71 /// Returns platform-specific object flags, if any.
72 virtual unsigned getPlatformFlags() const = 0;
73
74 elf_symbol_iterator_range symbols() const;
75
76 static bool classof(const Binary *v) { return v->isELF(); }
77
78 SubtargetFeatures getFeatures() const override;
79
80 SubtargetFeatures getMIPSFeatures() const;
81
82 SubtargetFeatures getARMFeatures() const;
83
84 SubtargetFeatures getRISCVFeatures() const;
85
86 void setARMSubArch(Triple &TheTriple) const override;
87
88 virtual uint16_t getEType() const = 0;
89
90 std::vector<std::pair<DataRefImpl, uint64_t>> getPltAddresses() const;
91};
92
93class ELFSectionRef : public SectionRef {
94public:
95 ELFSectionRef(const SectionRef &B) : SectionRef(B) {
96 assert(isa<ELFObjectFileBase>(SectionRef::getObject()))((isa<ELFObjectFileBase>(SectionRef::getObject())) ? static_cast
<void> (0) : __assert_fail ("isa<ELFObjectFileBase>(SectionRef::getObject())"
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Object/ELFObjectFile.h"
, 96, __PRETTY_FUNCTION__))
;
97 }
98
99 const ELFObjectFileBase *getObject() const {
100 return cast<ELFObjectFileBase>(SectionRef::getObject());
101 }
102
103 uint32_t getType() const {
104 return getObject()->getSectionType(getRawDataRefImpl());
105 }
106
107 uint64_t getFlags() const {
108 return getObject()->getSectionFlags(getRawDataRefImpl());
109 }
110
111 uint64_t getOffset() const {
112 return getObject()->getSectionOffset(getRawDataRefImpl());
113 }
114};
115
116class elf_section_iterator : public section_iterator {
117public:
118 elf_section_iterator(const section_iterator &B) : section_iterator(B) {
119 assert(isa<ELFObjectFileBase>(B->getObject()))((isa<ELFObjectFileBase>(B->getObject())) ? static_cast
<void> (0) : __assert_fail ("isa<ELFObjectFileBase>(B->getObject())"
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Object/ELFObjectFile.h"
, 119, __PRETTY_FUNCTION__))
;
120 }
121
122 const ELFSectionRef *operator->() const {
123 return static_cast<const ELFSectionRef *>(section_iterator::operator->());
124 }
125
126 const ELFSectionRef &operator*() const {
127 return static_cast<const ELFSectionRef &>(section_iterator::operator*());
128 }
129};
130
131class ELFSymbolRef : public SymbolRef {
132public:
133 ELFSymbolRef(const SymbolRef &B) : SymbolRef(B) {
134 assert(isa<ELFObjectFileBase>(SymbolRef::getObject()))((isa<ELFObjectFileBase>(SymbolRef::getObject())) ? static_cast
<void> (0) : __assert_fail ("isa<ELFObjectFileBase>(SymbolRef::getObject())"
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Object/ELFObjectFile.h"
, 134, __PRETTY_FUNCTION__))
;
135 }
136
137 const ELFObjectFileBase *getObject() const {
138 return cast<ELFObjectFileBase>(BasicSymbolRef::getObject());
139 }
140
141 uint64_t getSize() const {
142 return getObject()->getSymbolSize(getRawDataRefImpl());
143 }
144
145 uint8_t getOther() const {
146 return getObject()->getSymbolOther(getRawDataRefImpl());
147 }
148
149 uint8_t getELFType() const {
150 return getObject()->getSymbolELFType(getRawDataRefImpl());
151 }
152};
153
154class elf_symbol_iterator : public symbol_iterator {
155public:
156 elf_symbol_iterator(const basic_symbol_iterator &B)
157 : symbol_iterator(SymbolRef(B->getRawDataRefImpl(),
158 cast<ELFObjectFileBase>(B->getObject()))) {}
159
160 const ELFSymbolRef *operator->() const {
161 return static_cast<const ELFSymbolRef *>(symbol_iterator::operator->());
162 }
163
164 const ELFSymbolRef &operator*() const {
165 return static_cast<const ELFSymbolRef &>(symbol_iterator::operator*());
166 }
167};
168
169class ELFRelocationRef : public RelocationRef {
170public:
171 ELFRelocationRef(const RelocationRef &B) : RelocationRef(B) {
172 assert(isa<ELFObjectFileBase>(RelocationRef::getObject()))((isa<ELFObjectFileBase>(RelocationRef::getObject())) ?
static_cast<void> (0) : __assert_fail ("isa<ELFObjectFileBase>(RelocationRef::getObject())"
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Object/ELFObjectFile.h"
, 172, __PRETTY_FUNCTION__))
;
173 }
174
175 const ELFObjectFileBase *getObject() const {
176 return cast<ELFObjectFileBase>(RelocationRef::getObject());
177 }
178
179 Expected<int64_t> getAddend() const {
180 return getObject()->getRelocationAddend(getRawDataRefImpl());
181 }
182};
183
184class elf_relocation_iterator : public relocation_iterator {
185public:
186 elf_relocation_iterator(const relocation_iterator &B)
187 : relocation_iterator(RelocationRef(
188 B->getRawDataRefImpl(), cast<ELFObjectFileBase>(B->getObject()))) {}
189
190 const ELFRelocationRef *operator->() const {
191 return static_cast<const ELFRelocationRef *>(
192 relocation_iterator::operator->());
193 }
194
195 const ELFRelocationRef &operator*() const {
196 return static_cast<const ELFRelocationRef &>(
197 relocation_iterator::operator*());
198 }
199};
200
201inline ELFObjectFileBase::elf_symbol_iterator_range
202ELFObjectFileBase::symbols() const {
203 return elf_symbol_iterator_range(symbol_begin(), symbol_end());
204}
205
206template <class ELFT> class ELFObjectFile : public ELFObjectFileBase {
207 uint16_t getEMachine() const override;
208 uint16_t getEType() const override;
209 uint64_t getSymbolSize(DataRefImpl Sym) const override;
210
211public:
212 LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)using Elf_Addr = typename ELFT::Addr; using Elf_Off = typename
ELFT::Off; using Elf_Half = typename ELFT::Half; using Elf_Word
= typename ELFT::Word; using Elf_Sword = typename ELFT::Sword
; using Elf_Xword = typename ELFT::Xword; using Elf_Sxword = typename
ELFT::Sxword;
213
214 using uintX_t = typename ELFT::uint;
215
216 using Elf_Sym = typename ELFT::Sym;
217 using Elf_Shdr = typename ELFT::Shdr;
218 using Elf_Ehdr = typename ELFT::Ehdr;
219 using Elf_Rel = typename ELFT::Rel;
220 using Elf_Rela = typename ELFT::Rela;
221 using Elf_Dyn = typename ELFT::Dyn;
222
223private:
224 ELFObjectFile(MemoryBufferRef Object, ELFFile<ELFT> EF,
225 const Elf_Shdr *DotDynSymSec, const Elf_Shdr *DotSymtabSec,
226 ArrayRef<Elf_Word> ShndxTable);
227
228protected:
229 ELFFile<ELFT> EF;
230
231 const Elf_Shdr *DotDynSymSec = nullptr; // Dynamic symbol table section.
232 const Elf_Shdr *DotSymtabSec = nullptr; // Symbol table section.
233 ArrayRef<Elf_Word> ShndxTable;
234
235 void moveSymbolNext(DataRefImpl &Symb) const override;
236 Expected<StringRef> getSymbolName(DataRefImpl Symb) const override;
237 Expected<uint64_t> getSymbolAddress(DataRefImpl Symb) const override;
238 uint64_t getSymbolValueImpl(DataRefImpl Symb) const override;
239 uint32_t getSymbolAlignment(DataRefImpl Symb) const override;
240 uint64_t getCommonSymbolSizeImpl(DataRefImpl Symb) const override;
241 uint32_t getSymbolFlags(DataRefImpl Symb) const override;
242 uint8_t getSymbolOther(DataRefImpl Symb) const override;
243 uint8_t getSymbolELFType(DataRefImpl Symb) const override;
244 Expected<SymbolRef::Type> getSymbolType(DataRefImpl Symb) const override;
245 Expected<section_iterator> getSymbolSection(const Elf_Sym *Symb,
246 const Elf_Shdr *SymTab) const;
247 Expected<section_iterator> getSymbolSection(DataRefImpl Symb) const override;
248
249 void moveSectionNext(DataRefImpl &Sec) const override;
250 std::error_code getSectionName(DataRefImpl Sec,
251 StringRef &Res) const override;
252 uint64_t getSectionAddress(DataRefImpl Sec) const override;
253 uint64_t getSectionIndex(DataRefImpl Sec) const override;
254 uint64_t getSectionSize(DataRefImpl Sec) const override;
255 std::error_code getSectionContents(DataRefImpl Sec,
256 StringRef &Res) const override;
257 uint64_t getSectionAlignment(DataRefImpl Sec) const override;
258 bool isSectionCompressed(DataRefImpl Sec) const override;
259 bool isSectionText(DataRefImpl Sec) const override;
260 bool isSectionData(DataRefImpl Sec) const override;
261 bool isSectionBSS(DataRefImpl Sec) const override;
262 bool isSectionVirtual(DataRefImpl Sec) const override;
263 relocation_iterator section_rel_begin(DataRefImpl Sec) const override;
264 relocation_iterator section_rel_end(DataRefImpl Sec) const override;
265 std::vector<SectionRef> dynamic_relocation_sections() const override;
266 section_iterator getRelocatedSection(DataRefImpl Sec) const override;
267
268 void moveRelocationNext(DataRefImpl &Rel) const override;
269 uint64_t getRelocationOffset(DataRefImpl Rel) const override;
270 symbol_iterator getRelocationSymbol(DataRefImpl Rel) const override;
271 uint64_t getRelocationType(DataRefImpl Rel) const override;
272 void getRelocationTypeName(DataRefImpl Rel,
273 SmallVectorImpl<char> &Result) const override;
274
275 uint32_t getSectionType(DataRefImpl Sec) const override;
276 uint64_t getSectionFlags(DataRefImpl Sec) const override;
277 uint64_t getSectionOffset(DataRefImpl Sec) const override;
278 StringRef getRelocationTypeName(uint32_t Type) const;
279
280 /// Get the relocation section that contains \a Rel.
281 const Elf_Shdr *getRelSection(DataRefImpl Rel) const {
282 auto RelSecOrErr = EF.getSection(Rel.d.a);
283 if (!RelSecOrErr)
284 report_fatal_error(errorToErrorCode(RelSecOrErr.takeError()).message());
285 return *RelSecOrErr;
286 }
287
288 DataRefImpl toDRI(const Elf_Shdr *SymTable, unsigned SymbolNum) const {
289 DataRefImpl DRI;
290 if (!SymTable) {
291 DRI.d.a = 0;
292 DRI.d.b = 0;
293 return DRI;
294 }
295 assert(SymTable->sh_type == ELF::SHT_SYMTAB ||((SymTable->sh_type == ELF::SHT_SYMTAB || SymTable->sh_type
== ELF::SHT_DYNSYM) ? static_cast<void> (0) : __assert_fail
("SymTable->sh_type == ELF::SHT_SYMTAB || SymTable->sh_type == ELF::SHT_DYNSYM"
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Object/ELFObjectFile.h"
, 296, __PRETTY_FUNCTION__))
296 SymTable->sh_type == ELF::SHT_DYNSYM)((SymTable->sh_type == ELF::SHT_SYMTAB || SymTable->sh_type
== ELF::SHT_DYNSYM) ? static_cast<void> (0) : __assert_fail
("SymTable->sh_type == ELF::SHT_SYMTAB || SymTable->sh_type == ELF::SHT_DYNSYM"
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Object/ELFObjectFile.h"
, 296, __PRETTY_FUNCTION__))
;
297
298 auto SectionsOrErr = EF.sections();
299 if (!SectionsOrErr) {
300 DRI.d.a = 0;
301 DRI.d.b = 0;
302 return DRI;
303 }
304 uintptr_t SHT = reinterpret_cast<uintptr_t>((*SectionsOrErr).begin());
305 unsigned SymTableIndex =
306 (reinterpret_cast<uintptr_t>(SymTable) - SHT) / sizeof(Elf_Shdr);
307
308 DRI.d.a = SymTableIndex;
309 DRI.d.b = SymbolNum;
310 return DRI;
311 }
312
313 const Elf_Shdr *toELFShdrIter(DataRefImpl Sec) const {
314 return reinterpret_cast<const Elf_Shdr *>(Sec.p);
315 }
316
317 DataRefImpl toDRI(const Elf_Shdr *Sec) const {
318 DataRefImpl DRI;
319 DRI.p = reinterpret_cast<uintptr_t>(Sec);
320 return DRI;
321 }
322
323 DataRefImpl toDRI(const Elf_Dyn *Dyn) const {
324 DataRefImpl DRI;
325 DRI.p = reinterpret_cast<uintptr_t>(Dyn);
326 return DRI;
327 }
328
329 bool isExportedToOtherDSO(const Elf_Sym *ESym) const {
330 unsigned char Binding = ESym->getBinding();
331 unsigned char Visibility = ESym->getVisibility();
332
333 // A symbol is exported if its binding is either GLOBAL or WEAK, and its
334 // visibility is either DEFAULT or PROTECTED. All other symbols are not
335 // exported.
336 return ((Binding == ELF::STB_GLOBAL || Binding == ELF::STB_WEAK) &&
337 (Visibility == ELF::STV_DEFAULT ||
338 Visibility == ELF::STV_PROTECTED));
339 }
340
341 // This flag is used for classof, to distinguish ELFObjectFile from
342 // its subclass. If more subclasses will be created, this flag will
343 // have to become an enum.
344 bool isDyldELFObject;
345
346public:
347 ELFObjectFile(ELFObjectFile<ELFT> &&Other);
348 static Expected<ELFObjectFile<ELFT>> create(MemoryBufferRef Object);
349
350 const Elf_Rel *getRel(DataRefImpl Rel) const;
351 const Elf_Rela *getRela(DataRefImpl Rela) const;
352
353 const Elf_Sym *getSymbol(DataRefImpl Sym) const {
354 auto Ret = EF.template getEntry<Elf_Sym>(Sym.d.a, Sym.d.b);
3
Calling 'ELFFile::getEntry'
355 if (!Ret)
356 report_fatal_error(errorToErrorCode(Ret.takeError()).message());
357 return *Ret;
358 }
359
360 const Elf_Shdr *getSection(DataRefImpl Sec) const {
361 return reinterpret_cast<const Elf_Shdr *>(Sec.p);
362 }
363
364 basic_symbol_iterator symbol_begin() const override;
365 basic_symbol_iterator symbol_end() const override;
366
367 elf_symbol_iterator dynamic_symbol_begin() const;
368 elf_symbol_iterator dynamic_symbol_end() const;
369
370 section_iterator section_begin() const override;
371 section_iterator section_end() const override;
372
373 Expected<int64_t> getRelocationAddend(DataRefImpl Rel) const override;
374
375 uint8_t getBytesInAddress() const override;
376 StringRef getFileFormatName() const override;
377 Triple::ArchType getArch() const override;
378 Expected<uint64_t> getStartAddress() const override;
379
380 unsigned getPlatformFlags() const override { return EF.getHeader()->e_flags; }
381
382 std::error_code getBuildAttributes(ARMAttributeParser &Attributes) const override {
383 auto SectionsOrErr = EF.sections();
384 if (!SectionsOrErr)
385 return errorToErrorCode(SectionsOrErr.takeError());
386
387 for (const Elf_Shdr &Sec : *SectionsOrErr) {
388 if (Sec.sh_type == ELF::SHT_ARM_ATTRIBUTES) {
389 auto ErrorOrContents = EF.getSectionContents(&Sec);
390 if (!ErrorOrContents)
391 return errorToErrorCode(ErrorOrContents.takeError());
392
393 auto Contents = ErrorOrContents.get();
394 if (Contents[0] != ARMBuildAttrs::Format_Version || Contents.size() == 1)
395 return std::error_code();
396
397 Attributes.Parse(Contents, ELFT::TargetEndianness == support::little);
398 break;
399 }
400 }
401 return std::error_code();
402 }
403
404 const ELFFile<ELFT> *getELFFile() const { return &EF; }
405
406 bool isDyldType() const { return isDyldELFObject; }
407 static bool classof(const Binary *v) {
408 return v->getType() == getELFType(ELFT::TargetEndianness == support::little,
409 ELFT::Is64Bits);
410 }
411
412 elf_symbol_iterator_range getDynamicSymbolIterators() const override;
413
414 bool isRelocatableObject() const override;
415};
416
417using ELF32LEObjectFile = ELFObjectFile<ELF32LE>;
418using ELF64LEObjectFile = ELFObjectFile<ELF64LE>;
419using ELF32BEObjectFile = ELFObjectFile<ELF32BE>;
420using ELF64BEObjectFile = ELFObjectFile<ELF64BE>;
421
422template <class ELFT>
423void ELFObjectFile<ELFT>::moveSymbolNext(DataRefImpl &Sym) const {
424 ++Sym.d.b;
425}
426
427template <class ELFT>
428Expected<StringRef> ELFObjectFile<ELFT>::getSymbolName(DataRefImpl Sym) const {
429 const Elf_Sym *ESym = getSymbol(Sym);
430 auto SymTabOrErr = EF.getSection(Sym.d.a);
431 if (!SymTabOrErr)
432 return SymTabOrErr.takeError();
433 const Elf_Shdr *SymTableSec = *SymTabOrErr;
434 auto StrTabOrErr = EF.getSection(SymTableSec->sh_link);
435 if (!StrTabOrErr)
436 return StrTabOrErr.takeError();
437 const Elf_Shdr *StringTableSec = *StrTabOrErr;
438 auto SymStrTabOrErr = EF.getStringTable(StringTableSec);
439 if (!SymStrTabOrErr)
440 return SymStrTabOrErr.takeError();
441 return ESym->getName(*SymStrTabOrErr);
442}
443
444template <class ELFT>
445uint64_t ELFObjectFile<ELFT>::getSectionFlags(DataRefImpl Sec) const {
446 return getSection(Sec)->sh_flags;
447}
448
449template <class ELFT>
450uint32_t ELFObjectFile<ELFT>::getSectionType(DataRefImpl Sec) const {
451 return getSection(Sec)->sh_type;
452}
453
454template <class ELFT>
455uint64_t ELFObjectFile<ELFT>::getSectionOffset(DataRefImpl Sec) const {
456 return getSection(Sec)->sh_offset;
457}
458
459template <class ELFT>
460uint64_t ELFObjectFile<ELFT>::getSymbolValueImpl(DataRefImpl Symb) const {
461 const Elf_Sym *ESym = getSymbol(Symb);
462 uint64_t Ret = ESym->st_value;
463 if (ESym->st_shndx == ELF::SHN_ABS)
464 return Ret;
465
466 const Elf_Ehdr *Header = EF.getHeader();
467 // Clear the ARM/Thumb or microMIPS indicator flag.
468 if ((Header->e_machine == ELF::EM_ARM || Header->e_machine == ELF::EM_MIPS) &&
469 ESym->getType() == ELF::STT_FUNC)
470 Ret &= ~1;
471
472 return Ret;
473}
474
475template <class ELFT>
476Expected<uint64_t>
477ELFObjectFile<ELFT>::getSymbolAddress(DataRefImpl Symb) const {
478 uint64_t Result = getSymbolValue(Symb);
479 const Elf_Sym *ESym = getSymbol(Symb);
480 switch (ESym->st_shndx) {
481 case ELF::SHN_COMMON:
482 case ELF::SHN_UNDEF:
483 case ELF::SHN_ABS:
484 return Result;
485 }
486
487 const Elf_Ehdr *Header = EF.getHeader();
488 auto SymTabOrErr = EF.getSection(Symb.d.a);
489 if (!SymTabOrErr)
490 return SymTabOrErr.takeError();
491 const Elf_Shdr *SymTab = *SymTabOrErr;
492
493 if (Header->e_type == ELF::ET_REL) {
494 auto SectionOrErr = EF.getSection(ESym, SymTab, ShndxTable);
495 if (!SectionOrErr)
496 return SectionOrErr.takeError();
497 const Elf_Shdr *Section = *SectionOrErr;
498 if (Section)
499 Result += Section->sh_addr;
500 }
501
502 return Result;
503}
504
505template <class ELFT>
506uint32_t ELFObjectFile<ELFT>::getSymbolAlignment(DataRefImpl Symb) const {
507 const Elf_Sym *Sym = getSymbol(Symb);
508 if (Sym->st_shndx == ELF::SHN_COMMON)
509 return Sym->st_value;
510 return 0;
511}
512
513template <class ELFT>
514uint16_t ELFObjectFile<ELFT>::getEMachine() const {
515 return EF.getHeader()->e_machine;
516}
517
518template <class ELFT> uint16_t ELFObjectFile<ELFT>::getEType() const {
519 return EF.getHeader()->e_type;
520}
521
522template <class ELFT>
523uint64_t ELFObjectFile<ELFT>::getSymbolSize(DataRefImpl Sym) const {
524 return getSymbol(Sym)->st_size;
525}
526
527template <class ELFT>
528uint64_t ELFObjectFile<ELFT>::getCommonSymbolSizeImpl(DataRefImpl Symb) const {
529 return getSymbol(Symb)->st_size;
530}
531
532template <class ELFT>
533uint8_t ELFObjectFile<ELFT>::getSymbolOther(DataRefImpl Symb) const {
534 return getSymbol(Symb)->st_other;
535}
536
537template <class ELFT>
538uint8_t ELFObjectFile<ELFT>::getSymbolELFType(DataRefImpl Symb) const {
539 return getSymbol(Symb)->getType();
540}
541
542template <class ELFT>
543Expected<SymbolRef::Type>
544ELFObjectFile<ELFT>::getSymbolType(DataRefImpl Symb) const {
545 const Elf_Sym *ESym = getSymbol(Symb);
546
547 switch (ESym->getType()) {
548 case ELF::STT_NOTYPE:
549 return SymbolRef::ST_Unknown;
550 case ELF::STT_SECTION:
551 return SymbolRef::ST_Debug;
552 case ELF::STT_FILE:
553 return SymbolRef::ST_File;
554 case ELF::STT_FUNC:
555 return SymbolRef::ST_Function;
556 case ELF::STT_OBJECT:
557 case ELF::STT_COMMON:
558 case ELF::STT_TLS:
559 return SymbolRef::ST_Data;
560 default:
561 return SymbolRef::ST_Other;
562 }
563}
564
565template <class ELFT>
566uint32_t ELFObjectFile<ELFT>::getSymbolFlags(DataRefImpl Sym) const {
567 const Elf_Sym *ESym = getSymbol(Sym);
568
569 uint32_t Result = SymbolRef::SF_None;
570
571 if (ESym->getBinding() != ELF::STB_LOCAL)
572 Result |= SymbolRef::SF_Global;
573
574 if (ESym->getBinding() == ELF::STB_WEAK)
575 Result |= SymbolRef::SF_Weak;
576
577 if (ESym->st_shndx == ELF::SHN_ABS)
578 Result |= SymbolRef::SF_Absolute;
579
580 if (ESym->getType() == ELF::STT_FILE || ESym->getType() == ELF::STT_SECTION)
581 Result |= SymbolRef::SF_FormatSpecific;
582
583 auto DotSymtabSecSyms = EF.symbols(DotSymtabSec);
584 if (DotSymtabSecSyms && ESym == (*DotSymtabSecSyms).begin())
585 Result |= SymbolRef::SF_FormatSpecific;
586 auto DotDynSymSecSyms = EF.symbols(DotDynSymSec);
587 if (DotDynSymSecSyms && ESym == (*DotDynSymSecSyms).begin())
588 Result |= SymbolRef::SF_FormatSpecific;
589
590 if (EF.getHeader()->e_machine == ELF::EM_ARM) {
591 if (Expected<StringRef> NameOrErr = getSymbolName(Sym)) {
592 StringRef Name = *NameOrErr;
593 if (Name.startswith("$d") || Name.startswith("$t") ||
594 Name.startswith("$a"))
595 Result |= SymbolRef::SF_FormatSpecific;
596 } else {
597 // TODO: Actually report errors helpfully.
598 consumeError(NameOrErr.takeError());
599 }
600 if (ESym->getType() == ELF::STT_FUNC && (ESym->st_value & 1) == 1)
601 Result |= SymbolRef::SF_Thumb;
602 }
603
604 if (ESym->st_shndx == ELF::SHN_UNDEF)
605 Result |= SymbolRef::SF_Undefined;
606
607 if (ESym->getType() == ELF::STT_COMMON || ESym->st_shndx == ELF::SHN_COMMON)
608 Result |= SymbolRef::SF_Common;
609
610 if (isExportedToOtherDSO(ESym))
611 Result |= SymbolRef::SF_Exported;
612
613 if (ESym->getVisibility() == ELF::STV_HIDDEN)
614 Result |= SymbolRef::SF_Hidden;
615
616 return Result;
617}
618
619template <class ELFT>
620Expected<section_iterator>
621ELFObjectFile<ELFT>::getSymbolSection(const Elf_Sym *ESym,
622 const Elf_Shdr *SymTab) const {
623 auto ESecOrErr = EF.getSection(ESym, SymTab, ShndxTable);
624 if (!ESecOrErr)
625 return ESecOrErr.takeError();
626
627 const Elf_Shdr *ESec = *ESecOrErr;
628 if (!ESec)
629 return section_end();
630
631 DataRefImpl Sec;
632 Sec.p = reinterpret_cast<intptr_t>(ESec);
633 return section_iterator(SectionRef(Sec, this));
634}
635
636template <class ELFT>
637Expected<section_iterator>
638ELFObjectFile<ELFT>::getSymbolSection(DataRefImpl Symb) const {
639 const Elf_Sym *Sym = getSymbol(Symb);
640 auto SymTabOrErr = EF.getSection(Symb.d.a);
641 if (!SymTabOrErr)
642 return SymTabOrErr.takeError();
643 const Elf_Shdr *SymTab = *SymTabOrErr;
644 return getSymbolSection(Sym, SymTab);
645}
646
647template <class ELFT>
648void ELFObjectFile<ELFT>::moveSectionNext(DataRefImpl &Sec) const {
649 const Elf_Shdr *ESec = getSection(Sec);
650 Sec = toDRI(++ESec);
651}
652
653template <class ELFT>
654std::error_code ELFObjectFile<ELFT>::getSectionName(DataRefImpl Sec,
655 StringRef &Result) const {
656 auto Name = EF.getSectionName(&*getSection(Sec));
657 if (!Name)
658 return errorToErrorCode(Name.takeError());
659 Result = *Name;
660 return std::error_code();
661}
662
663template <class ELFT>
664uint64_t ELFObjectFile<ELFT>::getSectionAddress(DataRefImpl Sec) const {
665 return getSection(Sec)->sh_addr;
666}
667
668template <class ELFT>
669uint64_t ELFObjectFile<ELFT>::getSectionIndex(DataRefImpl Sec) const {
670 auto SectionsOrErr = EF.sections();
671 handleAllErrors(std::move(SectionsOrErr.takeError()),
672 [](const ErrorInfoBase &) {
673 llvm_unreachable("unable to get section index")::llvm::llvm_unreachable_internal("unable to get section index"
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Object/ELFObjectFile.h"
, 673)
;
674 });
675 const Elf_Shdr *First = SectionsOrErr->begin();
676 return getSection(Sec) - First;
677}
678
679template <class ELFT>
680uint64_t ELFObjectFile<ELFT>::getSectionSize(DataRefImpl Sec) const {
681 return getSection(Sec)->sh_size;
682}
683
684template <class ELFT>
685std::error_code
686ELFObjectFile<ELFT>::getSectionContents(DataRefImpl Sec,
687 StringRef &Result) const {
688 const Elf_Shdr *EShdr = getSection(Sec);
689 if (std::error_code EC =
690 checkOffset(getMemoryBufferRef(),
691 (uintptr_t)base() + EShdr->sh_offset, EShdr->sh_size))
692 return EC;
693 Result = StringRef((const char *)base() + EShdr->sh_offset, EShdr->sh_size);
694 return std::error_code();
695}
696
697template <class ELFT>
698uint64_t ELFObjectFile<ELFT>::getSectionAlignment(DataRefImpl Sec) const {
699 return getSection(Sec)->sh_addralign;
700}
701
702template <class ELFT>
703bool ELFObjectFile<ELFT>::isSectionCompressed(DataRefImpl Sec) const {
704 return getSection(Sec)->sh_flags & ELF::SHF_COMPRESSED;
705}
706
707template <class ELFT>
708bool ELFObjectFile<ELFT>::isSectionText(DataRefImpl Sec) const {
709 return getSection(Sec)->sh_flags & ELF::SHF_EXECINSTR;
710}
711
712template <class ELFT>
713bool ELFObjectFile<ELFT>::isSectionData(DataRefImpl Sec) const {
714 const Elf_Shdr *EShdr = getSection(Sec);
715 return EShdr->sh_type == ELF::SHT_PROGBITS &&
716 EShdr->sh_flags & ELF::SHF_ALLOC &&
717 !(EShdr->sh_flags & ELF::SHF_EXECINSTR);
718}
719
720template <class ELFT>
721bool ELFObjectFile<ELFT>::isSectionBSS(DataRefImpl Sec) const {
722 const Elf_Shdr *EShdr = getSection(Sec);
723 return EShdr->sh_flags & (ELF::SHF_ALLOC | ELF::SHF_WRITE) &&
724 EShdr->sh_type == ELF::SHT_NOBITS;
725}
726
727template <class ELFT>
728std::vector<SectionRef>
729ELFObjectFile<ELFT>::dynamic_relocation_sections() const {
730 std::vector<SectionRef> Res;
731 std::vector<uintptr_t> Offsets;
732
733 auto SectionsOrErr = EF.sections();
734 if (!SectionsOrErr)
735 return Res;
736
737 for (const Elf_Shdr &Sec : *SectionsOrErr) {
738 if (Sec.sh_type != ELF::SHT_DYNAMIC)
739 continue;
740 Elf_Dyn *Dynamic =
741 reinterpret_cast<Elf_Dyn *>((uintptr_t)base() + Sec.sh_offset);
742 for (; Dynamic->d_tag != ELF::DT_NULL; Dynamic++) {
743 if (Dynamic->d_tag == ELF::DT_REL || Dynamic->d_tag == ELF::DT_RELA ||
744 Dynamic->d_tag == ELF::DT_JMPREL) {
745 Offsets.push_back(Dynamic->d_un.d_val);
746 }
747 }
748 }
749 for (const Elf_Shdr &Sec : *SectionsOrErr) {
750 if (is_contained(Offsets, Sec.sh_offset))
751 Res.emplace_back(toDRI(&Sec), this);
752 }
753 return Res;
754}
755
756template <class ELFT>
757bool ELFObjectFile<ELFT>::isSectionVirtual(DataRefImpl Sec) const {
758 return getSection(Sec)->sh_type == ELF::SHT_NOBITS;
759}
760
761template <class ELFT>
762relocation_iterator
763ELFObjectFile<ELFT>::section_rel_begin(DataRefImpl Sec) const {
764 DataRefImpl RelData;
765 auto SectionsOrErr = EF.sections();
766 if (!SectionsOrErr)
767 return relocation_iterator(RelocationRef());
768 uintptr_t SHT = reinterpret_cast<uintptr_t>((*SectionsOrErr).begin());
769 RelData.d.a = (Sec.p - SHT) / EF.getHeader()->e_shentsize;
770 RelData.d.b = 0;
771 return relocation_iterator(RelocationRef(RelData, this));
772}
773
774template <class ELFT>
775relocation_iterator
776ELFObjectFile<ELFT>::section_rel_end(DataRefImpl Sec) const {
777 const Elf_Shdr *S = reinterpret_cast<const Elf_Shdr *>(Sec.p);
778 relocation_iterator Begin = section_rel_begin(Sec);
779 if (S->sh_type != ELF::SHT_RELA && S->sh_type != ELF::SHT_REL)
780 return Begin;
781 DataRefImpl RelData = Begin->getRawDataRefImpl();
782 const Elf_Shdr *RelSec = getRelSection(RelData);
783
784 // Error check sh_link here so that getRelocationSymbol can just use it.
785 auto SymSecOrErr = EF.getSection(RelSec->sh_link);
786 if (!SymSecOrErr)
787 report_fatal_error(errorToErrorCode(SymSecOrErr.takeError()).message());
788
789 RelData.d.b += S->sh_size / S->sh_entsize;
790 return relocation_iterator(RelocationRef(RelData, this));
791}
792
793template <class ELFT>
794section_iterator
795ELFObjectFile<ELFT>::getRelocatedSection(DataRefImpl Sec) const {
796 if (EF.getHeader()->e_type != ELF::ET_REL)
797 return section_end();
798
799 const Elf_Shdr *EShdr = getSection(Sec);
800 uintX_t Type = EShdr->sh_type;
801 if (Type != ELF::SHT_REL && Type != ELF::SHT_RELA)
802 return section_end();
803
804 auto R = EF.getSection(EShdr->sh_info);
805 if (!R)
806 report_fatal_error(errorToErrorCode(R.takeError()).message());
807 return section_iterator(SectionRef(toDRI(*R), this));
808}
809
810// Relocations
811template <class ELFT>
812void ELFObjectFile<ELFT>::moveRelocationNext(DataRefImpl &Rel) const {
813 ++Rel.d.b;
814}
815
816template <class ELFT>
817symbol_iterator
818ELFObjectFile<ELFT>::getRelocationSymbol(DataRefImpl Rel) const {
819 uint32_t symbolIdx;
820 const Elf_Shdr *sec = getRelSection(Rel);
821 if (sec->sh_type == ELF::SHT_REL)
822 symbolIdx = getRel(Rel)->getSymbol(EF.isMips64EL());
823 else
824 symbolIdx = getRela(Rel)->getSymbol(EF.isMips64EL());
825 if (!symbolIdx)
826 return symbol_end();
827
828 // FIXME: error check symbolIdx
829 DataRefImpl SymbolData;
830 SymbolData.d.a = sec->sh_link;
831 SymbolData.d.b = symbolIdx;
832 return symbol_iterator(SymbolRef(SymbolData, this));
833}
834
835template <class ELFT>
836uint64_t ELFObjectFile<ELFT>::getRelocationOffset(DataRefImpl Rel) const {
837 const Elf_Shdr *sec = getRelSection(Rel);
838 if (sec->sh_type == ELF::SHT_REL)
839 return getRel(Rel)->r_offset;
840
841 return getRela(Rel)->r_offset;
842}
843
844template <class ELFT>
845uint64_t ELFObjectFile<ELFT>::getRelocationType(DataRefImpl Rel) const {
846 const Elf_Shdr *sec = getRelSection(Rel);
847 if (sec->sh_type == ELF::SHT_REL)
848 return getRel(Rel)->getType(EF.isMips64EL());
849 else
850 return getRela(Rel)->getType(EF.isMips64EL());
851}
852
853template <class ELFT>
854StringRef ELFObjectFile<ELFT>::getRelocationTypeName(uint32_t Type) const {
855 return getELFRelocationTypeName(EF.getHeader()->e_machine, Type);
856}
857
858template <class ELFT>
859void ELFObjectFile<ELFT>::getRelocationTypeName(
860 DataRefImpl Rel, SmallVectorImpl<char> &Result) const {
861 uint32_t type = getRelocationType(Rel);
862 EF.getRelocationTypeName(type, Result);
863}
864
865template <class ELFT>
866Expected<int64_t>
867ELFObjectFile<ELFT>::getRelocationAddend(DataRefImpl Rel) const {
868 if (getRelSection(Rel)->sh_type != ELF::SHT_RELA)
869 return createError("Section is not SHT_RELA");
870 return (int64_t)getRela(Rel)->r_addend;
871}
872
873template <class ELFT>
874const typename ELFObjectFile<ELFT>::Elf_Rel *
875ELFObjectFile<ELFT>::getRel(DataRefImpl Rel) const {
876 assert(getRelSection(Rel)->sh_type == ELF::SHT_REL)((getRelSection(Rel)->sh_type == ELF::SHT_REL) ? static_cast
<void> (0) : __assert_fail ("getRelSection(Rel)->sh_type == ELF::SHT_REL"
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Object/ELFObjectFile.h"
, 876, __PRETTY_FUNCTION__))
;
877 auto Ret = EF.template getEntry<Elf_Rel>(Rel.d.a, Rel.d.b);
878 if (!Ret)
879 report_fatal_error(errorToErrorCode(Ret.takeError()).message());
880 return *Ret;
881}
882
883template <class ELFT>
884const typename ELFObjectFile<ELFT>::Elf_Rela *
885ELFObjectFile<ELFT>::getRela(DataRefImpl Rela) const {
886 assert(getRelSection(Rela)->sh_type == ELF::SHT_RELA)((getRelSection(Rela)->sh_type == ELF::SHT_RELA) ? static_cast
<void> (0) : __assert_fail ("getRelSection(Rela)->sh_type == ELF::SHT_RELA"
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Object/ELFObjectFile.h"
, 886, __PRETTY_FUNCTION__))
;
887 auto Ret = EF.template getEntry<Elf_Rela>(Rela.d.a, Rela.d.b);
888 if (!Ret)
889 report_fatal_error(errorToErrorCode(Ret.takeError()).message());
890 return *Ret;
891}
892
893template <class ELFT>
894Expected<ELFObjectFile<ELFT>>
895ELFObjectFile<ELFT>::create(MemoryBufferRef Object) {
896 auto EFOrErr = ELFFile<ELFT>::create(Object.getBuffer());
897 if (Error E = EFOrErr.takeError())
898 return std::move(E);
899 auto EF = std::move(*EFOrErr);
900
901 auto SectionsOrErr = EF.sections();
902 if (!SectionsOrErr)
903 return SectionsOrErr.takeError();
904
905 const Elf_Shdr *DotDynSymSec = nullptr;
906 const Elf_Shdr *DotSymtabSec = nullptr;
907 ArrayRef<Elf_Word> ShndxTable;
908 for (const Elf_Shdr &Sec : *SectionsOrErr) {
909 switch (Sec.sh_type) {
910 case ELF::SHT_DYNSYM: {
911 if (DotDynSymSec)
912 return createError("More than one dynamic symbol table!");
913 DotDynSymSec = &Sec;
914 break;
915 }
916 case ELF::SHT_SYMTAB: {
917 if (DotSymtabSec)
918 return createError("More than one static symbol table!");
919 DotSymtabSec = &Sec;
920 break;
921 }
922 case ELF::SHT_SYMTAB_SHNDX: {
923 auto TableOrErr = EF.getSHNDXTable(Sec);
924 if (!TableOrErr)
925 return TableOrErr.takeError();
926 ShndxTable = *TableOrErr;
927 break;
928 }
929 }
930 }
931 return ELFObjectFile<ELFT>(Object, EF, DotDynSymSec, DotSymtabSec,
932 ShndxTable);
933}
934
935template <class ELFT>
936ELFObjectFile<ELFT>::ELFObjectFile(MemoryBufferRef Object, ELFFile<ELFT> EF,
937 const Elf_Shdr *DotDynSymSec,
938 const Elf_Shdr *DotSymtabSec,
939 ArrayRef<Elf_Word> ShndxTable)
940 : ELFObjectFileBase(
941 getELFType(ELFT::TargetEndianness == support::little, ELFT::Is64Bits),
942 Object),
943 EF(EF), DotDynSymSec(DotDynSymSec), DotSymtabSec(DotSymtabSec),
944 ShndxTable(ShndxTable) {}
945
946template <class ELFT>
947ELFObjectFile<ELFT>::ELFObjectFile(ELFObjectFile<ELFT> &&Other)
948 : ELFObjectFile(Other.Data, Other.EF, Other.DotDynSymSec,
949 Other.DotSymtabSec, Other.ShndxTable) {}
950
951template <class ELFT>
952basic_symbol_iterator ELFObjectFile<ELFT>::symbol_begin() const {
953 DataRefImpl Sym = toDRI(DotSymtabSec, 0);
954 return basic_symbol_iterator(SymbolRef(Sym, this));
955}
956
957template <class ELFT>
958basic_symbol_iterator ELFObjectFile<ELFT>::symbol_end() const {
959 const Elf_Shdr *SymTab = DotSymtabSec;
960 if (!SymTab)
961 return symbol_begin();
962 DataRefImpl Sym = toDRI(SymTab, SymTab->sh_size / sizeof(Elf_Sym));
963 return basic_symbol_iterator(SymbolRef(Sym, this));
964}
965
966template <class ELFT>
967elf_symbol_iterator ELFObjectFile<ELFT>::dynamic_symbol_begin() const {
968 DataRefImpl Sym = toDRI(DotDynSymSec, 0);
969 return symbol_iterator(SymbolRef(Sym, this));
970}
971
972template <class ELFT>
973elf_symbol_iterator ELFObjectFile<ELFT>::dynamic_symbol_end() const {
974 const Elf_Shdr *SymTab = DotDynSymSec;
975 if (!SymTab)
976 return dynamic_symbol_begin();
977 DataRefImpl Sym = toDRI(SymTab, SymTab->sh_size / sizeof(Elf_Sym));
978 return basic_symbol_iterator(SymbolRef(Sym, this));
979}
980
981template <class ELFT>
982section_iterator ELFObjectFile<ELFT>::section_begin() const {
983 auto SectionsOrErr = EF.sections();
984 if (!SectionsOrErr)
985 return section_iterator(SectionRef());
986 return section_iterator(SectionRef(toDRI((*SectionsOrErr).begin()), this));
987}
988
989template <class ELFT>
990section_iterator ELFObjectFile<ELFT>::section_end() const {
991 auto SectionsOrErr = EF.sections();
992 if (!SectionsOrErr)
993 return section_iterator(SectionRef());
994 return section_iterator(SectionRef(toDRI((*SectionsOrErr).end()), this));
995}
996
997template <class ELFT>
998uint8_t ELFObjectFile<ELFT>::getBytesInAddress() const {
999 return ELFT::Is64Bits ? 8 : 4;
1000}
1001
1002template <class ELFT>
1003StringRef ELFObjectFile<ELFT>::getFileFormatName() const {
1004 bool IsLittleEndian = ELFT::TargetEndianness == support::little;
1005 switch (EF.getHeader()->e_ident[ELF::EI_CLASS]) {
1006 case ELF::ELFCLASS32:
1007 switch (EF.getHeader()->e_machine) {
1008 case ELF::EM_386:
1009 return "ELF32-i386";
1010 case ELF::EM_IAMCU:
1011 return "ELF32-iamcu";
1012 case ELF::EM_X86_64:
1013 return "ELF32-x86-64";
1014 case ELF::EM_ARM:
1015 return (IsLittleEndian ? "ELF32-arm-little" : "ELF32-arm-big");
1016 case ELF::EM_AVR:
1017 return "ELF32-avr";
1018 case ELF::EM_HEXAGON:
1019 return "ELF32-hexagon";
1020 case ELF::EM_LANAI:
1021 return "ELF32-lanai";
1022 case ELF::EM_MIPS:
1023 return "ELF32-mips";
1024 case ELF::EM_PPC:
1025 return "ELF32-ppc";
1026 case ELF::EM_RISCV:
1027 return "ELF32-riscv";
1028 case ELF::EM_SPARC:
1029 case ELF::EM_SPARC32PLUS:
1030 return "ELF32-sparc";
1031 case ELF::EM_AMDGPU:
1032 return "ELF32-amdgpu";
1033 default:
1034 return "ELF32-unknown";
1035 }
1036 case ELF::ELFCLASS64:
1037 switch (EF.getHeader()->e_machine) {
1038 case ELF::EM_386:
1039 return "ELF64-i386";
1040 case ELF::EM_X86_64:
1041 return "ELF64-x86-64";
1042 case ELF::EM_AARCH64:
1043 return (IsLittleEndian ? "ELF64-aarch64-little" : "ELF64-aarch64-big");
1044 case ELF::EM_PPC64:
1045 return "ELF64-ppc64";
1046 case ELF::EM_RISCV:
1047 return "ELF64-riscv";
1048 case ELF::EM_S390:
1049 return "ELF64-s390";
1050 case ELF::EM_SPARCV9:
1051 return "ELF64-sparc";
1052 case ELF::EM_MIPS:
1053 return "ELF64-mips";
1054 case ELF::EM_AMDGPU:
1055 return "ELF64-amdgpu";
1056 case ELF::EM_BPF:
1057 return "ELF64-BPF";
1058 default:
1059 return "ELF64-unknown";
1060 }
1061 default:
1062 // FIXME: Proper error handling.
1063 report_fatal_error("Invalid ELFCLASS!");
1064 }
1065}
1066
1067template <class ELFT> Triple::ArchType ELFObjectFile<ELFT>::getArch() const {
1068 bool IsLittleEndian = ELFT::TargetEndianness == support::little;
1069 switch (EF.getHeader()->e_machine) {
1070 case ELF::EM_386:
1071 case ELF::EM_IAMCU:
1072 return Triple::x86;
1073 case ELF::EM_X86_64:
1074 return Triple::x86_64;
1075 case ELF::EM_AARCH64:
1076 return IsLittleEndian ? Triple::aarch64 : Triple::aarch64_be;
1077 case ELF::EM_ARM:
1078 return Triple::arm;
1079 case ELF::EM_AVR:
1080 return Triple::avr;
1081 case ELF::EM_HEXAGON:
1082 return Triple::hexagon;
1083 case ELF::EM_LANAI:
1084 return Triple::lanai;
1085 case ELF::EM_MIPS:
1086 switch (EF.getHeader()->e_ident[ELF::EI_CLASS]) {
1087 case ELF::ELFCLASS32:
1088 return IsLittleEndian ? Triple::mipsel : Triple::mips;
1089 case ELF::ELFCLASS64:
1090 return IsLittleEndian ? Triple::mips64el : Triple::mips64;
1091 default:
1092 report_fatal_error("Invalid ELFCLASS!");
1093 }
1094 case ELF::EM_PPC:
1095 return Triple::ppc;
1096 case ELF::EM_PPC64:
1097 return IsLittleEndian ? Triple::ppc64le : Triple::ppc64;
1098 case ELF::EM_RISCV:
1099 switch (EF.getHeader()->e_ident[ELF::EI_CLASS]) {
1100 case ELF::ELFCLASS32:
1101 return Triple::riscv32;
1102 case ELF::ELFCLASS64:
1103 return Triple::riscv64;
1104 default:
1105 report_fatal_error("Invalid ELFCLASS!");
1106 }
1107 case ELF::EM_S390:
1108 return Triple::systemz;
1109
1110 case ELF::EM_SPARC:
1111 case ELF::EM_SPARC32PLUS:
1112 return IsLittleEndian ? Triple::sparcel : Triple::sparc;
1113 case ELF::EM_SPARCV9:
1114 return Triple::sparcv9;
1115
1116 case ELF::EM_AMDGPU: {
1117 if (!IsLittleEndian)
1118 return Triple::UnknownArch;
1119
1120 unsigned MACH = EF.getHeader()->e_flags & ELF::EF_AMDGPU_MACH;
1121 if (MACH >= ELF::EF_AMDGPU_MACH_R600_FIRST &&
1122 MACH <= ELF::EF_AMDGPU_MACH_R600_LAST)
1123 return Triple::r600;
1124 if (MACH >= ELF::EF_AMDGPU_MACH_AMDGCN_FIRST &&
1125 MACH <= ELF::EF_AMDGPU_MACH_AMDGCN_LAST)
1126 return Triple::amdgcn;
1127
1128 return Triple::UnknownArch;
1129 }
1130
1131 case ELF::EM_BPF:
1132 return IsLittleEndian ? Triple::bpfel : Triple::bpfeb;
1133
1134 default:
1135 return Triple::UnknownArch;
1136 }
1137}
1138
1139template <class ELFT>
1140Expected<uint64_t> ELFObjectFile<ELFT>::getStartAddress() const {
1141 return EF.getHeader()->e_entry;
1142}
1143
1144template <class ELFT>
1145ELFObjectFileBase::elf_symbol_iterator_range
1146ELFObjectFile<ELFT>::getDynamicSymbolIterators() const {
1147 return make_range(dynamic_symbol_begin(), dynamic_symbol_end());
1148}
1149
1150template <class ELFT> bool ELFObjectFile<ELFT>::isRelocatableObject() const {
1151 return EF.getHeader()->e_type == ELF::ET_REL;
1152}
1153
1154} // end namespace object
1155} // end namespace llvm
1156
1157#endif // LLVM_OBJECT_ELFOBJECTFILE_H

/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Object/ELF.h

1//===- ELF.h - ELF object file implementation -------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file declares the ELFFile template class.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_OBJECT_ELF_H
15#define LLVM_OBJECT_ELF_H
16
17#include "llvm/ADT/ArrayRef.h"
18#include "llvm/ADT/SmallVector.h"
19#include "llvm/ADT/StringRef.h"
20#include "llvm/BinaryFormat/ELF.h"
21#include "llvm/Object/ELFTypes.h"
22#include "llvm/Object/Error.h"
23#include "llvm/Support/Endian.h"
24#include "llvm/Support/Error.h"
25#include <cassert>
26#include <cstddef>
27#include <cstdint>
28#include <limits>
29#include <utility>
30
31namespace llvm {
32namespace object {
33
34StringRef getELFRelocationTypeName(uint32_t Machine, uint32_t Type);
35uint32_t getELFRelrRelocationType(uint32_t Machine);
36StringRef getELFSectionTypeName(uint32_t Machine, uint32_t Type);
37
38// Subclasses of ELFFile may need this for template instantiation
39inline std::pair<unsigned char, unsigned char>
40getElfArchType(StringRef Object) {
41 if (Object.size() < ELF::EI_NIDENT)
42 return std::make_pair((uint8_t)ELF::ELFCLASSNONE,
43 (uint8_t)ELF::ELFDATANONE);
44 return std::make_pair((uint8_t)Object[ELF::EI_CLASS],
45 (uint8_t)Object[ELF::EI_DATA]);
46}
47
48static inline Error createError(StringRef Err) {
49 return make_error<StringError>(Err, object_error::parse_failed);
11
Calling 'make_error<llvm::StringError, llvm::StringRef &, llvm::object::object_error>'
50}
51
52template <class ELFT>
53class ELFFile {
54public:
55 LLVM_ELF_IMPORT_TYPES_ELFT(ELFT)using Elf_Addr = typename ELFT::Addr; using Elf_Off = typename
ELFT::Off; using Elf_Half = typename ELFT::Half; using Elf_Word
= typename ELFT::Word; using Elf_Sword = typename ELFT::Sword
; using Elf_Xword = typename ELFT::Xword; using Elf_Sxword = typename
ELFT::Sxword;
56 using uintX_t = typename ELFT::uint;
57 using Elf_Ehdr = typename ELFT::Ehdr;
58 using Elf_Shdr = typename ELFT::Shdr;
59 using Elf_Sym = typename ELFT::Sym;
60 using Elf_Dyn = typename ELFT::Dyn;
61 using Elf_Phdr = typename ELFT::Phdr;
62 using Elf_Rel = typename ELFT::Rel;
63 using Elf_Rela = typename ELFT::Rela;
64 using Elf_Relr = typename ELFT::Relr;
65 using Elf_Verdef = typename ELFT::Verdef;
66 using Elf_Verdaux = typename ELFT::Verdaux;
67 using Elf_Verneed = typename ELFT::Verneed;
68 using Elf_Vernaux = typename ELFT::Vernaux;
69 using Elf_Versym = typename ELFT::Versym;
70 using Elf_Hash = typename ELFT::Hash;
71 using Elf_GnuHash = typename ELFT::GnuHash;
72 using Elf_Nhdr = typename ELFT::Nhdr;
73 using Elf_Note = typename ELFT::Note;
74 using Elf_Note_Iterator = typename ELFT::NoteIterator;
75 using Elf_Dyn_Range = typename ELFT::DynRange;
76 using Elf_Shdr_Range = typename ELFT::ShdrRange;
77 using Elf_Sym_Range = typename ELFT::SymRange;
78 using Elf_Rel_Range = typename ELFT::RelRange;
79 using Elf_Rela_Range = typename ELFT::RelaRange;
80 using Elf_Relr_Range = typename ELFT::RelrRange;
81 using Elf_Phdr_Range = typename ELFT::PhdrRange;
82
83 const uint8_t *base() const {
84 return reinterpret_cast<const uint8_t *>(Buf.data());
85 }
86
87 size_t getBufSize() const { return Buf.size(); }
88
89private:
90 StringRef Buf;
91
92 ELFFile(StringRef Object);
93
94public:
95 const Elf_Ehdr *getHeader() const {
96 return reinterpret_cast<const Elf_Ehdr *>(base());
97 }
98
99 template <typename T>
100 Expected<const T *> getEntry(uint32_t Section, uint32_t Entry) const;
101 template <typename T>
102 Expected<const T *> getEntry(const Elf_Shdr *Section, uint32_t Entry) const;
103
104 Expected<StringRef> getStringTable(const Elf_Shdr *Section) const;
105 Expected<StringRef> getStringTableForSymtab(const Elf_Shdr &Section) const;
106 Expected<StringRef> getStringTableForSymtab(const Elf_Shdr &Section,
107 Elf_Shdr_Range Sections) const;
108
109 Expected<ArrayRef<Elf_Word>> getSHNDXTable(const Elf_Shdr &Section) const;
110 Expected<ArrayRef<Elf_Word>> getSHNDXTable(const Elf_Shdr &Section,
111 Elf_Shdr_Range Sections) const;
112
113 StringRef getRelocationTypeName(uint32_t Type) const;
114 void getRelocationTypeName(uint32_t Type,
115 SmallVectorImpl<char> &Result) const;
116 uint32_t getRelrRelocationType() const;
117
118 const char *getDynamicTagAsString(unsigned Arch, uint64_t Type) const;
119 const char *getDynamicTagAsString(uint64_t Type) const;
120
121 /// Get the symbol for a given relocation.
122 Expected<const Elf_Sym *> getRelocationSymbol(const Elf_Rel *Rel,
123 const Elf_Shdr *SymTab) const;
124
125 static Expected<ELFFile> create(StringRef Object);
126
127 bool isMipsELF64() const {
128 return getHeader()->e_machine == ELF::EM_MIPS &&
129 getHeader()->getFileClass() == ELF::ELFCLASS64;
130 }
131
132 bool isMips64EL() const {
133 return isMipsELF64() &&
134 getHeader()->getDataEncoding() == ELF::ELFDATA2LSB;
135 }
136
137 Expected<Elf_Shdr_Range> sections() const;
138
139 Expected<Elf_Dyn_Range> dynamicEntries() const;
140
141 Expected<const uint8_t *> toMappedAddr(uint64_t VAddr) const;
142
143 Expected<Elf_Sym_Range> symbols(const Elf_Shdr *Sec) const {
144 if (!Sec)
145 return makeArrayRef<Elf_Sym>(nullptr, nullptr);
146 return getSectionContentsAsArray<Elf_Sym>(Sec);
147 }
148
149 Expected<Elf_Rela_Range> relas(const Elf_Shdr *Sec) const {
150 return getSectionContentsAsArray<Elf_Rela>(Sec);
151 }
152
153 Expected<Elf_Rel_Range> rels(const Elf_Shdr *Sec) const {
154 return getSectionContentsAsArray<Elf_Rel>(Sec);
155 }
156
157 Expected<Elf_Relr_Range> relrs(const Elf_Shdr *Sec) const {
158 return getSectionContentsAsArray<Elf_Relr>(Sec);
159 }
160
161 Expected<std::vector<Elf_Rela>> decode_relrs(Elf_Relr_Range relrs) const;
162
163 Expected<std::vector<Elf_Rela>> android_relas(const Elf_Shdr *Sec) const;
164
165 /// Iterate over program header table.
166 Expected<Elf_Phdr_Range> program_headers() const {
167 if (getHeader()->e_phnum && getHeader()->e_phentsize != sizeof(Elf_Phdr))
168 return createError("invalid e_phentsize");
169 if (getHeader()->e_phoff +
170 (getHeader()->e_phnum * getHeader()->e_phentsize) >
171 getBufSize())
172 return createError("program headers longer than binary");
173 auto *Begin =
174 reinterpret_cast<const Elf_Phdr *>(base() + getHeader()->e_phoff);
175 return makeArrayRef(Begin, Begin + getHeader()->e_phnum);
176 }
177
178 /// Get an iterator over notes in a program header.
179 ///
180 /// The program header must be of type \c PT_NOTE.
181 ///
182 /// \param Phdr the program header to iterate over.
183 /// \param Err [out] an error to support fallible iteration, which should
184 /// be checked after iteration ends.
185 Elf_Note_Iterator notes_begin(const Elf_Phdr &Phdr, Error &Err) const {
186 if (Phdr.p_type != ELF::PT_NOTE) {
187 Err = createError("attempt to iterate notes of non-note program header");
188 return Elf_Note_Iterator(Err);
189 }
190 if (Phdr.p_offset + Phdr.p_filesz > getBufSize()) {
191 Err = createError("invalid program header offset/size");
192 return Elf_Note_Iterator(Err);
193 }
194 return Elf_Note_Iterator(base() + Phdr.p_offset, Phdr.p_filesz, Err);
195 }
196
197 /// Get an iterator over notes in a section.
198 ///
199 /// The section must be of type \c SHT_NOTE.
200 ///
201 /// \param Shdr the section to iterate over.
202 /// \param Err [out] an error to support fallible iteration, which should
203 /// be checked after iteration ends.
204 Elf_Note_Iterator notes_begin(const Elf_Shdr &Shdr, Error &Err) const {
205 if (Shdr.sh_type != ELF::SHT_NOTE) {
206 Err = createError("attempt to iterate notes of non-note section");
207 return Elf_Note_Iterator(Err);
208 }
209 if (Shdr.sh_offset + Shdr.sh_size > getBufSize()) {
210 Err = createError("invalid section offset/size");
211 return Elf_Note_Iterator(Err);
212 }
213 return Elf_Note_Iterator(base() + Shdr.sh_offset, Shdr.sh_size, Err);
214 }
215
216 /// Get the end iterator for notes.
217 Elf_Note_Iterator notes_end() const {
218 return Elf_Note_Iterator();
219 }
220
221 /// Get an iterator range over notes of a program header.
222 ///
223 /// The program header must be of type \c PT_NOTE.
224 ///
225 /// \param Phdr the program header to iterate over.
226 /// \param Err [out] an error to support fallible iteration, which should
227 /// be checked after iteration ends.
228 iterator_range<Elf_Note_Iterator> notes(const Elf_Phdr &Phdr,
229 Error &Err) const {
230 return make_range(notes_begin(Phdr, Err), notes_end());
231 }
232
233 /// Get an iterator range over notes of a section.
234 ///
235 /// The section must be of type \c SHT_NOTE.
236 ///
237 /// \param Shdr the section to iterate over.
238 /// \param Err [out] an error to support fallible iteration, which should
239 /// be checked after iteration ends.
240 iterator_range<Elf_Note_Iterator> notes(const Elf_Shdr &Shdr,
241 Error &Err) const {
242 return make_range(notes_begin(Shdr, Err), notes_end());
243 }
244
245 Expected<StringRef> getSectionStringTable(Elf_Shdr_Range Sections) const;
246 Expected<uint32_t> getSectionIndex(const Elf_Sym *Sym, Elf_Sym_Range Syms,
247 ArrayRef<Elf_Word> ShndxTable) const;
248 Expected<const Elf_Shdr *> getSection(const Elf_Sym *Sym,
249 const Elf_Shdr *SymTab,
250 ArrayRef<Elf_Word> ShndxTable) const;
251 Expected<const Elf_Shdr *> getSection(const Elf_Sym *Sym,
252 Elf_Sym_Range Symtab,
253 ArrayRef<Elf_Word> ShndxTable) const;
254 Expected<const Elf_Shdr *> getSection(uint32_t Index) const;
255 Expected<const Elf_Shdr *> getSection(const StringRef SectionName) const;
256
257 Expected<const Elf_Sym *> getSymbol(const Elf_Shdr *Sec,
258 uint32_t Index) const;
259
260 Expected<StringRef> getSectionName(const Elf_Shdr *Section) const;
261 Expected<StringRef> getSectionName(const Elf_Shdr *Section,
262 StringRef DotShstrtab) const;
263 template <typename T>
264 Expected<ArrayRef<T>> getSectionContentsAsArray(const Elf_Shdr *Sec) const;
265 Expected<ArrayRef<uint8_t>> getSectionContents(const Elf_Shdr *Sec) const;
266};
267
268using ELF32LEFile = ELFFile<ELF32LE>;
269using ELF64LEFile = ELFFile<ELF64LE>;
270using ELF32BEFile = ELFFile<ELF32BE>;
271using ELF64BEFile = ELFFile<ELF64BE>;
272
273template <class ELFT>
274inline Expected<const typename ELFT::Shdr *>
275getSection(typename ELFT::ShdrRange Sections, uint32_t Index) {
276 if (Index >= Sections.size())
277 return createError("invalid section index");
278 return &Sections[Index];
279}
280
281template <class ELFT>
282inline Expected<uint32_t>
283getExtendedSymbolTableIndex(const typename ELFT::Sym *Sym,
284 const typename ELFT::Sym *FirstSym,
285 ArrayRef<typename ELFT::Word> ShndxTable) {
286 assert(Sym->st_shndx == ELF::SHN_XINDEX)((Sym->st_shndx == ELF::SHN_XINDEX) ? static_cast<void>
(0) : __assert_fail ("Sym->st_shndx == ELF::SHN_XINDEX", "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Object/ELF.h"
, 286, __PRETTY_FUNCTION__))
;
287 unsigned Index = Sym - FirstSym;
288 if (Index >= ShndxTable.size())
289 return createError("index past the end of the symbol table");
290
291 // The size of the table was checked in getSHNDXTable.
292 return ShndxTable[Index];
293}
294
295template <class ELFT>
296Expected<uint32_t>
297ELFFile<ELFT>::getSectionIndex(const Elf_Sym *Sym, Elf_Sym_Range Syms,
298 ArrayRef<Elf_Word> ShndxTable) const {
299 uint32_t Index = Sym->st_shndx;
300 if (Index == ELF::SHN_XINDEX) {
301 auto ErrorOrIndex = getExtendedSymbolTableIndex<ELFT>(
302 Sym, Syms.begin(), ShndxTable);
303 if (!ErrorOrIndex)
304 return ErrorOrIndex.takeError();
305 return *ErrorOrIndex;
306 }
307 if (Index == ELF::SHN_UNDEF || Index >= ELF::SHN_LORESERVE)
308 return 0;
309 return Index;
310}
311
312template <class ELFT>
313Expected<const typename ELFT::Shdr *>
314ELFFile<ELFT>::getSection(const Elf_Sym *Sym, const Elf_Shdr *SymTab,
315 ArrayRef<Elf_Word> ShndxTable) const {
316 auto SymsOrErr = symbols(SymTab);
317 if (!SymsOrErr)
318 return SymsOrErr.takeError();
319 return getSection(Sym, *SymsOrErr, ShndxTable);
320}
321
322template <class ELFT>
323Expected<const typename ELFT::Shdr *>
324ELFFile<ELFT>::getSection(const Elf_Sym *Sym, Elf_Sym_Range Symbols,
325 ArrayRef<Elf_Word> ShndxTable) const {
326 auto IndexOrErr = getSectionIndex(Sym, Symbols, ShndxTable);
327 if (!IndexOrErr)
328 return IndexOrErr.takeError();
329 uint32_t Index = *IndexOrErr;
330 if (Index == 0)
331 return nullptr;
332 return getSection(Index);
333}
334
335template <class ELFT>
336inline Expected<const typename ELFT::Sym *>
337getSymbol(typename ELFT::SymRange Symbols, uint32_t Index) {
338 if (Index >= Symbols.size())
339 return createError("invalid symbol index");
340 return &Symbols[Index];
341}
342
343template <class ELFT>
344Expected<const typename ELFT::Sym *>
345ELFFile<ELFT>::getSymbol(const Elf_Shdr *Sec, uint32_t Index) const {
346 auto SymtabOrErr = symbols(Sec);
347 if (!SymtabOrErr)
348 return SymtabOrErr.takeError();
349 return object::getSymbol<ELFT>(*SymtabOrErr, Index);
350}
351
352template <class ELFT>
353template <typename T>
354Expected<ArrayRef<T>>
355ELFFile<ELFT>::getSectionContentsAsArray(const Elf_Shdr *Sec) const {
356 if (Sec->sh_entsize != sizeof(T) && sizeof(T) != 1)
357 return createError("invalid sh_entsize");
358
359 uintX_t Offset = Sec->sh_offset;
360 uintX_t Size = Sec->sh_size;
361
362 if (Size % sizeof(T))
363 return createError("size is not a multiple of sh_entsize");
364 if ((std::numeric_limits<uintX_t>::max() - Offset < Size) ||
365 Offset + Size > Buf.size())
366 return createError("invalid section offset");
367
368 if (Offset % alignof(T))
369 return createError("unaligned data");
370
371 const T *Start = reinterpret_cast<const T *>(base() + Offset);
372 return makeArrayRef(Start, Size / sizeof(T));
373}
374
375template <class ELFT>
376Expected<ArrayRef<uint8_t>>
377ELFFile<ELFT>::getSectionContents(const Elf_Shdr *Sec) const {
378 return getSectionContentsAsArray<uint8_t>(Sec);
379}
380
381template <class ELFT>
382StringRef ELFFile<ELFT>::getRelocationTypeName(uint32_t Type) const {
383 return getELFRelocationTypeName(getHeader()->e_machine, Type);
384}
385
386template <class ELFT>
387void ELFFile<ELFT>::getRelocationTypeName(uint32_t Type,
388 SmallVectorImpl<char> &Result) const {
389 if (!isMipsELF64()) {
390 StringRef Name = getRelocationTypeName(Type);
391 Result.append(Name.begin(), Name.end());
392 } else {
393 // The Mips N64 ABI allows up to three operations to be specified per
394 // relocation record. Unfortunately there's no easy way to test for the
395 // presence of N64 ELFs as they have no special flag that identifies them
396 // as being N64. We can safely assume at the moment that all Mips
397 // ELFCLASS64 ELFs are N64. New Mips64 ABIs should provide enough
398 // information to disambiguate between old vs new ABIs.
399 uint8_t Type1 = (Type >> 0) & 0xFF;
400 uint8_t Type2 = (Type >> 8) & 0xFF;
401 uint8_t Type3 = (Type >> 16) & 0xFF;
402
403 // Concat all three relocation type names.
404 StringRef Name = getRelocationTypeName(Type1);
405 Result.append(Name.begin(), Name.end());
406
407 Name = getRelocationTypeName(Type2);
408 Result.append(1, '/');
409 Result.append(Name.begin(), Name.end());
410
411 Name = getRelocationTypeName(Type3);
412 Result.append(1, '/');
413 Result.append(Name.begin(), Name.end());
414 }
415}
416
417template <class ELFT>
418uint32_t ELFFile<ELFT>::getRelrRelocationType() const {
419 return getELFRelrRelocationType(getHeader()->e_machine);
420}
421
422template <class ELFT>
423Expected<const typename ELFT::Sym *>
424ELFFile<ELFT>::getRelocationSymbol(const Elf_Rel *Rel,
425 const Elf_Shdr *SymTab) const {
426 uint32_t Index = Rel->getSymbol(isMips64EL());
427 if (Index == 0)
428 return nullptr;
429 return getEntry<Elf_Sym>(SymTab, Index);
430}
431
432template <class ELFT>
433Expected<StringRef>
434ELFFile<ELFT>::getSectionStringTable(Elf_Shdr_Range Sections) const {
435 uint32_t Index = getHeader()->e_shstrndx;
436 if (Index == ELF::SHN_XINDEX)
437 Index = Sections[0].sh_link;
438
439 if (!Index) // no section string table.
440 return "";
441 if (Index >= Sections.size())
442 return createError("invalid section index");
443 return getStringTable(&Sections[Index]);
444}
445
446template <class ELFT> ELFFile<ELFT>::ELFFile(StringRef Object) : Buf(Object) {}
447
448template <class ELFT>
449Expected<ELFFile<ELFT>> ELFFile<ELFT>::create(StringRef Object) {
450 if (sizeof(Elf_Ehdr) > Object.size())
451 return createError("Invalid buffer");
452 return ELFFile(Object);
453}
454
455template <class ELFT>
456Expected<typename ELFT::ShdrRange> ELFFile<ELFT>::sections() const {
457 const uintX_t SectionTableOffset = getHeader()->e_shoff;
458 if (SectionTableOffset == 0)
6
Assuming 'SectionTableOffset' is not equal to 0
7
Taking false branch
459 return ArrayRef<Elf_Shdr>();
460
461 if (getHeader()->e_shentsize != sizeof(Elf_Shdr))
8
Assuming the condition is true
9
Taking true branch
462 return createError(
10
Calling 'createError'
463 "invalid section header entry size (e_shentsize) in ELF header");
464
465 const uint64_t FileSize = Buf.size();
466
467 if (SectionTableOffset + sizeof(Elf_Shdr) > FileSize)
468 return createError("section header table goes past the end of the file");
469
470 // Invalid address alignment of section headers
471 if (SectionTableOffset & (alignof(Elf_Shdr) - 1))
472 return createError("invalid alignment of section headers");
473
474 const Elf_Shdr *First =
475 reinterpret_cast<const Elf_Shdr *>(base() + SectionTableOffset);
476
477 uintX_t NumSections = getHeader()->e_shnum;
478 if (NumSections == 0)
479 NumSections = First->sh_size;
480
481 if (NumSections > UINT64_MAX(18446744073709551615UL) / sizeof(Elf_Shdr))
482 return createError("section table goes past the end of file");
483
484 const uint64_t SectionTableSize = NumSections * sizeof(Elf_Shdr);
485
486 // Section table goes past end of file!
487 if (SectionTableOffset + SectionTableSize > FileSize)
488 return createError("section table goes past the end of file");
489
490 return makeArrayRef(First, NumSections);
491}
492
493template <class ELFT>
494template <typename T>
495Expected<const T *> ELFFile<ELFT>::getEntry(uint32_t Section,
496 uint32_t Entry) const {
497 auto SecOrErr = getSection(Section);
4
Calling 'ELFFile::getSection'
498 if (!SecOrErr)
499 return SecOrErr.takeError();
500 return getEntry<T>(*SecOrErr, Entry);
501}
502
503template <class ELFT>
504template <typename T>
505Expected<const T *> ELFFile<ELFT>::getEntry(const Elf_Shdr *Section,
506 uint32_t Entry) const {
507 if (sizeof(T) != Section->sh_entsize)
508 return createError("invalid sh_entsize");
509 size_t Pos = Section->sh_offset + Entry * sizeof(T);
510 if (Pos + sizeof(T) > Buf.size())
511 return createError("invalid section offset");
512 return reinterpret_cast<const T *>(base() + Pos);
513}
514
515template <class ELFT>
516Expected<const typename ELFT::Shdr *>
517ELFFile<ELFT>::getSection(uint32_t Index) const {
518 auto TableOrErr = sections();
5
Calling 'ELFFile::sections'
519 if (!TableOrErr)
520 return TableOrErr.takeError();
521 return object::getSection<ELFT>(*TableOrErr, Index);
522}
523
524template <class ELFT>
525Expected<const typename ELFT::Shdr *>
526ELFFile<ELFT>::getSection(const StringRef SectionName) const {
527 auto TableOrErr = sections();
528 if (!TableOrErr)
529 return TableOrErr.takeError();
530 for (auto &Sec : *TableOrErr) {
531 auto SecNameOrErr = getSectionName(&Sec);
532 if (!SecNameOrErr)
533 return SecNameOrErr.takeError();
534 if (*SecNameOrErr == SectionName)
535 return &Sec;
536 }
537 return createError("invalid section name");
538}
539
540template <class ELFT>
541Expected<StringRef>
542ELFFile<ELFT>::getStringTable(const Elf_Shdr *Section) const {
543 if (Section->sh_type != ELF::SHT_STRTAB)
544 return createError("invalid sh_type for string table, expected SHT_STRTAB");
545 auto V = getSectionContentsAsArray<char>(Section);
546 if (!V)
547 return V.takeError();
548 ArrayRef<char> Data = *V;
549 if (Data.empty())
550 return createError("empty string table");
551 if (Data.back() != '\0')
552 return createError("string table non-null terminated");
553 return StringRef(Data.begin(), Data.size());
554}
555
556template <class ELFT>
557Expected<ArrayRef<typename ELFT::Word>>
558ELFFile<ELFT>::getSHNDXTable(const Elf_Shdr &Section) const {
559 auto SectionsOrErr = sections();
560 if (!SectionsOrErr)
561 return SectionsOrErr.takeError();
562 return getSHNDXTable(Section, *SectionsOrErr);
563}
564
565template <class ELFT>
566Expected<ArrayRef<typename ELFT::Word>>
567ELFFile<ELFT>::getSHNDXTable(const Elf_Shdr &Section,
568 Elf_Shdr_Range Sections) const {
569 assert(Section.sh_type == ELF::SHT_SYMTAB_SHNDX)((Section.sh_type == ELF::SHT_SYMTAB_SHNDX) ? static_cast<
void> (0) : __assert_fail ("Section.sh_type == ELF::SHT_SYMTAB_SHNDX"
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Object/ELF.h"
, 569, __PRETTY_FUNCTION__))
;
570 auto VOrErr = getSectionContentsAsArray<Elf_Word>(&Section);
571 if (!VOrErr)
572 return VOrErr.takeError();
573 ArrayRef<Elf_Word> V = *VOrErr;
574 auto SymTableOrErr = object::getSection<ELFT>(Sections, Section.sh_link);
575 if (!SymTableOrErr)
576 return SymTableOrErr.takeError();
577 const Elf_Shdr &SymTable = **SymTableOrErr;
578 if (SymTable.sh_type != ELF::SHT_SYMTAB &&
579 SymTable.sh_type != ELF::SHT_DYNSYM)
580 return createError("invalid sh_type");
581 if (V.size() != (SymTable.sh_size / sizeof(Elf_Sym)))
582 return createError("invalid section contents size");
583 return V;
584}
585
586template <class ELFT>
587Expected<StringRef>
588ELFFile<ELFT>::getStringTableForSymtab(const Elf_Shdr &Sec) const {
589 auto SectionsOrErr = sections();
590 if (!SectionsOrErr)
591 return SectionsOrErr.takeError();
592 return getStringTableForSymtab(Sec, *SectionsOrErr);
593}
594
595template <class ELFT>
596Expected<StringRef>
597ELFFile<ELFT>::getStringTableForSymtab(const Elf_Shdr &Sec,
598 Elf_Shdr_Range Sections) const {
599
600 if (Sec.sh_type != ELF::SHT_SYMTAB && Sec.sh_type != ELF::SHT_DYNSYM)
601 return createError(
602 "invalid sh_type for symbol table, expected SHT_SYMTAB or SHT_DYNSYM");
603 auto SectionOrErr = object::getSection<ELFT>(Sections, Sec.sh_link);
604 if (!SectionOrErr)
605 return SectionOrErr.takeError();
606 return getStringTable(*SectionOrErr);
607}
608
609template <class ELFT>
610Expected<StringRef>
611ELFFile<ELFT>::getSectionName(const Elf_Shdr *Section) const {
612 auto SectionsOrErr = sections();
613 if (!SectionsOrErr)
614 return SectionsOrErr.takeError();
615 auto Table = getSectionStringTable(*SectionsOrErr);
616 if (!Table)
617 return Table.takeError();
618 return getSectionName(Section, *Table);
619}
620
621template <class ELFT>
622Expected<StringRef> ELFFile<ELFT>::getSectionName(const Elf_Shdr *Section,
623 StringRef DotShstrtab) const {
624 uint32_t Offset = Section->sh_name;
625 if (Offset == 0)
626 return StringRef();
627 if (Offset >= DotShstrtab.size())
628 return createError("invalid string offset");
629 return StringRef(DotShstrtab.data() + Offset);
630}
631
632/// This function returns the hash value for a symbol in the .dynsym section
633/// Name of the API remains consistent as specified in the libelf
634/// REF : http://www.sco.com/developers/gabi/latest/ch5.dynamic.html#hash
635inline unsigned hashSysV(StringRef SymbolName) {
636 unsigned h = 0, g;
637 for (char C : SymbolName) {
638 h = (h << 4) + C;
639 g = h & 0xf0000000L;
640 if (g != 0)
641 h ^= g >> 24;
642 h &= ~g;
643 }
644 return h;
645}
646
647} // end namespace object
648} // end namespace llvm
649
650#endif // LLVM_OBJECT_ELF_H

/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/Error.h

1//===- llvm/Support/Error.h - Recoverable error handling --------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines an API used to report recoverable errors.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_SUPPORT_ERROR_H
15#define LLVM_SUPPORT_ERROR_H
16
17#include "llvm-c/Error.h"
18#include "llvm/ADT/STLExtras.h"
19#include "llvm/ADT/SmallVector.h"
20#include "llvm/ADT/StringExtras.h"
21#include "llvm/ADT/Twine.h"
22#include "llvm/Config/abi-breaking.h"
23#include "llvm/Support/AlignOf.h"
24#include "llvm/Support/Compiler.h"
25#include "llvm/Support/Debug.h"
26#include "llvm/Support/ErrorHandling.h"
27#include "llvm/Support/ErrorOr.h"
28#include "llvm/Support/Format.h"
29#include "llvm/Support/raw_ostream.h"
30#include <algorithm>
31#include <cassert>
32#include <cstdint>
33#include <cstdlib>
34#include <functional>
35#include <memory>
36#include <new>
37#include <string>
38#include <system_error>
39#include <type_traits>
40#include <utility>
41#include <vector>
42
43namespace llvm {
44
45class ErrorSuccess;
46
47/// Base class for error info classes. Do not extend this directly: Extend
48/// the ErrorInfo template subclass instead.
49class ErrorInfoBase {
50public:
51 virtual ~ErrorInfoBase() = default;
52
53 /// Print an error message to an output stream.
54 virtual void log(raw_ostream &OS) const = 0;
55
56 /// Return the error message as a string.
57 virtual std::string message() const {
58 std::string Msg;
59 raw_string_ostream OS(Msg);
60 log(OS);
61 return OS.str();
62 }
63
64 /// Convert this error to a std::error_code.
65 ///
66 /// This is a temporary crutch to enable interaction with code still
67 /// using std::error_code. It will be removed in the future.
68 virtual std::error_code convertToErrorCode() const = 0;
69
70 // Returns the class ID for this type.
71 static const void *classID() { return &ID; }
72
73 // Returns the class ID for the dynamic type of this ErrorInfoBase instance.
74 virtual const void *dynamicClassID() const = 0;
75
76 // Check whether this instance is a subclass of the class identified by
77 // ClassID.
78 virtual bool isA(const void *const ClassID) const {
79 return ClassID == classID();
80 }
81
82 // Check whether this instance is a subclass of ErrorInfoT.
83 template <typename ErrorInfoT> bool isA() const {
84 return isA(ErrorInfoT::classID());
85 }
86
87private:
88 virtual void anchor();
89
90 static char ID;
91};
92
93/// Lightweight error class with error context and mandatory checking.
94///
95/// Instances of this class wrap a ErrorInfoBase pointer. Failure states
96/// are represented by setting the pointer to a ErrorInfoBase subclass
97/// instance containing information describing the failure. Success is
98/// represented by a null pointer value.
99///
100/// Instances of Error also contains a 'Checked' flag, which must be set
101/// before the destructor is called, otherwise the destructor will trigger a
102/// runtime error. This enforces at runtime the requirement that all Error
103/// instances be checked or returned to the caller.
104///
105/// There are two ways to set the checked flag, depending on what state the
106/// Error instance is in. For Error instances indicating success, it
107/// is sufficient to invoke the boolean conversion operator. E.g.:
108///
109/// @code{.cpp}
110/// Error foo(<...>);
111///
112/// if (auto E = foo(<...>))
113/// return E; // <- Return E if it is in the error state.
114/// // We have verified that E was in the success state. It can now be safely
115/// // destroyed.
116/// @endcode
117///
118/// A success value *can not* be dropped. For example, just calling 'foo(<...>)'
119/// without testing the return value will raise a runtime error, even if foo
120/// returns success.
121///
122/// For Error instances representing failure, you must use either the
123/// handleErrors or handleAllErrors function with a typed handler. E.g.:
124///
125/// @code{.cpp}
126/// class MyErrorInfo : public ErrorInfo<MyErrorInfo> {
127/// // Custom error info.
128/// };
129///
130/// Error foo(<...>) { return make_error<MyErrorInfo>(...); }
131///
132/// auto E = foo(<...>); // <- foo returns failure with MyErrorInfo.
133/// auto NewE =
134/// handleErrors(E,
135/// [](const MyErrorInfo &M) {
136/// // Deal with the error.
137/// },
138/// [](std::unique_ptr<OtherError> M) -> Error {
139/// if (canHandle(*M)) {
140/// // handle error.
141/// return Error::success();
142/// }
143/// // Couldn't handle this error instance. Pass it up the stack.
144/// return Error(std::move(M));
145/// );
146/// // Note - we must check or return NewE in case any of the handlers
147/// // returned a new error.
148/// @endcode
149///
150/// The handleAllErrors function is identical to handleErrors, except
151/// that it has a void return type, and requires all errors to be handled and
152/// no new errors be returned. It prevents errors (assuming they can all be
153/// handled) from having to be bubbled all the way to the top-level.
154///
155/// *All* Error instances must be checked before destruction, even if
156/// they're moved-assigned or constructed from Success values that have already
157/// been checked. This enforces checking through all levels of the call stack.
158class LLVM_NODISCARD[[clang::warn_unused_result]] Error {
159 // Both ErrorList and FileError need to be able to yank ErrorInfoBase
160 // pointers out of this class to add to the error list.
161 friend class ErrorList;
162 friend class FileError;
163
164 // handleErrors needs to be able to set the Checked flag.
165 template <typename... HandlerTs>
166 friend Error handleErrors(Error E, HandlerTs &&... Handlers);
167
168 // Expected<T> needs to be able to steal the payload when constructed from an
169 // error.
170 template <typename T> friend class Expected;
171
172 // wrap needs to be able to steal the payload.
173 friend LLVMErrorRef wrap(Error);
174
175protected:
176 /// Create a success value. Prefer using 'Error::success()' for readability
177 Error() {
178 setPtr(nullptr);
179 setChecked(false);
180 }
181
182public:
183 /// Create a success value.
184 static ErrorSuccess success();
185
186 // Errors are not copy-constructable.
187 Error(const Error &Other) = delete;
188
189 /// Move-construct an error value. The newly constructed error is considered
190 /// unchecked, even if the source error had been checked. The original error
191 /// becomes a checked Success value, regardless of its original state.
192 Error(Error &&Other) {
193 setChecked(true);
194 *this = std::move(Other);
195 }
196
197 /// Create an error value. Prefer using the 'make_error' function, but
198 /// this constructor can be useful when "re-throwing" errors from handlers.
199 Error(std::unique_ptr<ErrorInfoBase> Payload) {
200 setPtr(Payload.release());
201 setChecked(false);
16
Potential leak of memory pointed to by 'Payload._M_t._M_head_impl'
202 }
203
204 // Errors are not copy-assignable.
205 Error &operator=(const Error &Other) = delete;
206
207 /// Move-assign an error value. The current error must represent success, you
208 /// you cannot overwrite an unhandled error. The current error is then
209 /// considered unchecked. The source error becomes a checked success value,
210 /// regardless of its original state.
211 Error &operator=(Error &&Other) {
212 // Don't allow overwriting of unchecked values.
213 assertIsChecked();
214 setPtr(Other.getPtr());
215
216 // This Error is unchecked, even if the source error was checked.
217 setChecked(false);
218
219 // Null out Other's payload and set its checked bit.
220 Other.setPtr(nullptr);
221 Other.setChecked(true);
222
223 return *this;
224 }
225
226 /// Destroy a Error. Fails with a call to abort() if the error is
227 /// unchecked.
228 ~Error() {
229 assertIsChecked();
230 delete getPtr();
231 }
232
233 /// Bool conversion. Returns true if this Error is in a failure state,
234 /// and false if it is in an accept state. If the error is in a Success state
235 /// it will be considered checked.
236 explicit operator bool() {
237 setChecked(getPtr() == nullptr);
238 return getPtr() != nullptr;
239 }
240
241 /// Check whether one error is a subclass of another.
242 template <typename ErrT> bool isA() const {
243 return getPtr() && getPtr()->isA(ErrT::classID());
244 }
245
246 /// Returns the dynamic class id of this error, or null if this is a success
247 /// value.
248 const void* dynamicClassID() const {
249 if (!getPtr())
250 return nullptr;
251 return getPtr()->dynamicClassID();
252 }
253
254private:
255#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
256 // assertIsChecked() happens very frequently, but under normal circumstances
257 // is supposed to be a no-op. So we want it to be inlined, but having a bunch
258 // of debug prints can cause the function to be too large for inlining. So
259 // it's important that we define this function out of line so that it can't be
260 // inlined.
261 LLVM_ATTRIBUTE_NORETURN__attribute__((noreturn))
262 void fatalUncheckedError() const;
263#endif
264
265 void assertIsChecked() {
266#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
267 if (LLVM_UNLIKELY(!getChecked() || getPtr())__builtin_expect((bool)(!getChecked() || getPtr()), false))
268 fatalUncheckedError();
269#endif
270 }
271
272 ErrorInfoBase *getPtr() const {
273 return reinterpret_cast<ErrorInfoBase*>(
274 reinterpret_cast<uintptr_t>(Payload) &
275 ~static_cast<uintptr_t>(0x1));
276 }
277
278 void setPtr(ErrorInfoBase *EI) {
279#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
280 Payload = reinterpret_cast<ErrorInfoBase*>(
281 (reinterpret_cast<uintptr_t>(EI) &
282 ~static_cast<uintptr_t>(0x1)) |
283 (reinterpret_cast<uintptr_t>(Payload) & 0x1));
284#else
285 Payload = EI;
286#endif
287 }
288
289 bool getChecked() const {
290#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
291 return (reinterpret_cast<uintptr_t>(Payload) & 0x1) == 0;
292#else
293 return true;
294#endif
295 }
296
297 void setChecked(bool V) {
298 Payload = reinterpret_cast<ErrorInfoBase*>(
299 (reinterpret_cast<uintptr_t>(Payload) &
300 ~static_cast<uintptr_t>(0x1)) |
301 (V ? 0 : 1));
302 }
303
304 std::unique_ptr<ErrorInfoBase> takePayload() {
305 std::unique_ptr<ErrorInfoBase> Tmp(getPtr());
306 setPtr(nullptr);
307 setChecked(true);
308 return Tmp;
309 }
310
311 friend raw_ostream &operator<<(raw_ostream &OS, const Error &E) {
312 if (auto P = E.getPtr())
313 P->log(OS);
314 else
315 OS << "success";
316 return OS;
317 }
318
319 ErrorInfoBase *Payload = nullptr;
320};
321
322/// Subclass of Error for the sole purpose of identifying the success path in
323/// the type system. This allows to catch invalid conversion to Expected<T> at
324/// compile time.
325class ErrorSuccess final : public Error {};
326
327inline ErrorSuccess Error::success() { return ErrorSuccess(); }
328
329/// Make a Error instance representing failure using the given error info
330/// type.
331template <typename ErrT, typename... ArgTs> Error make_error(ArgTs &&... Args) {
332 return Error(llvm::make_unique<ErrT>(std::forward<ArgTs>(Args)...));
12
Calling 'make_unique<llvm::StringError, llvm::StringRef &, llvm::object::object_error>'
14
Returned allocated memory
15
Calling constructor for 'Error'
333}
334
335/// Base class for user error types. Users should declare their error types
336/// like:
337///
338/// class MyError : public ErrorInfo<MyError> {
339/// ....
340/// };
341///
342/// This class provides an implementation of the ErrorInfoBase::kind
343/// method, which is used by the Error RTTI system.
344template <typename ThisErrT, typename ParentErrT = ErrorInfoBase>
345class ErrorInfo : public ParentErrT {
346public:
347 using ParentErrT::ParentErrT; // inherit constructors
348
349 static const void *classID() { return &ThisErrT::ID; }
350
351 const void *dynamicClassID() const override { return &ThisErrT::ID; }
352
353 bool isA(const void *const ClassID) const override {
354 return ClassID == classID() || ParentErrT::isA(ClassID);
355 }
356};
357
358/// Special ErrorInfo subclass representing a list of ErrorInfos.
359/// Instances of this class are constructed by joinError.
360class ErrorList final : public ErrorInfo<ErrorList> {
361 // handleErrors needs to be able to iterate the payload list of an
362 // ErrorList.
363 template <typename... HandlerTs>
364 friend Error handleErrors(Error E, HandlerTs &&... Handlers);
365
366 // joinErrors is implemented in terms of join.
367 friend Error joinErrors(Error, Error);
368
369public:
370 void log(raw_ostream &OS) const override {
371 OS << "Multiple errors:\n";
372 for (auto &ErrPayload : Payloads) {
373 ErrPayload->log(OS);
374 OS << "\n";
375 }
376 }
377
378 std::error_code convertToErrorCode() const override;
379
380 // Used by ErrorInfo::classID.
381 static char ID;
382
383private:
384 ErrorList(std::unique_ptr<ErrorInfoBase> Payload1,
385 std::unique_ptr<ErrorInfoBase> Payload2) {
386 assert(!Payload1->isA<ErrorList>() && !Payload2->isA<ErrorList>() &&((!Payload1->isA<ErrorList>() && !Payload2->
isA<ErrorList>() && "ErrorList constructor payloads should be singleton errors"
) ? static_cast<void> (0) : __assert_fail ("!Payload1->isA<ErrorList>() && !Payload2->isA<ErrorList>() && \"ErrorList constructor payloads should be singleton errors\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/Error.h"
, 387, __PRETTY_FUNCTION__))
387 "ErrorList constructor payloads should be singleton errors")((!Payload1->isA<ErrorList>() && !Payload2->
isA<ErrorList>() && "ErrorList constructor payloads should be singleton errors"
) ? static_cast<void> (0) : __assert_fail ("!Payload1->isA<ErrorList>() && !Payload2->isA<ErrorList>() && \"ErrorList constructor payloads should be singleton errors\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/Error.h"
, 387, __PRETTY_FUNCTION__))
;
388 Payloads.push_back(std::move(Payload1));
389 Payloads.push_back(std::move(Payload2));
390 }
391
392 static Error join(Error E1, Error E2) {
393 if (!E1)
394 return E2;
395 if (!E2)
396 return E1;
397 if (E1.isA<ErrorList>()) {
398 auto &E1List = static_cast<ErrorList &>(*E1.getPtr());
399 if (E2.isA<ErrorList>()) {
400 auto E2Payload = E2.takePayload();
401 auto &E2List = static_cast<ErrorList &>(*E2Payload);
402 for (auto &Payload : E2List.Payloads)
403 E1List.Payloads.push_back(std::move(Payload));
404 } else
405 E1List.Payloads.push_back(E2.takePayload());
406
407 return E1;
408 }
409 if (E2.isA<ErrorList>()) {
410 auto &E2List = static_cast<ErrorList &>(*E2.getPtr());
411 E2List.Payloads.insert(E2List.Payloads.begin(), E1.takePayload());
412 return E2;
413 }
414 return Error(std::unique_ptr<ErrorList>(
415 new ErrorList(E1.takePayload(), E2.takePayload())));
416 }
417
418 std::vector<std::unique_ptr<ErrorInfoBase>> Payloads;
419};
420
421/// Concatenate errors. The resulting Error is unchecked, and contains the
422/// ErrorInfo(s), if any, contained in E1, followed by the
423/// ErrorInfo(s), if any, contained in E2.
424inline Error joinErrors(Error E1, Error E2) {
425 return ErrorList::join(std::move(E1), std::move(E2));
426}
427
428/// Tagged union holding either a T or a Error.
429///
430/// This class parallels ErrorOr, but replaces error_code with Error. Since
431/// Error cannot be copied, this class replaces getError() with
432/// takeError(). It also adds an bool errorIsA<ErrT>() method for testing the
433/// error class type.
434template <class T> class LLVM_NODISCARD[[clang::warn_unused_result]] Expected {
435 template <class T1> friend class ExpectedAsOutParameter;
436 template <class OtherT> friend class Expected;
437
438 static const bool isRef = std::is_reference<T>::value;
439
440 using wrap = std::reference_wrapper<typename std::remove_reference<T>::type>;
441
442 using error_type = std::unique_ptr<ErrorInfoBase>;
443
444public:
445 using storage_type = typename std::conditional<isRef, wrap, T>::type;
446 using value_type = T;
447
448private:
449 using reference = typename std::remove_reference<T>::type &;
450 using const_reference = const typename std::remove_reference<T>::type &;
451 using pointer = typename std::remove_reference<T>::type *;
452 using const_pointer = const typename std::remove_reference<T>::type *;
453
454public:
455 /// Create an Expected<T> error value from the given Error.
456 Expected(Error Err)
457 : HasError(true)
458#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
459 // Expected is unchecked upon construction in Debug builds.
460 , Unchecked(true)
461#endif
462 {
463 assert(Err && "Cannot create Expected<T> from Error success value.")((Err && "Cannot create Expected<T> from Error success value."
) ? static_cast<void> (0) : __assert_fail ("Err && \"Cannot create Expected<T> from Error success value.\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/Error.h"
, 463, __PRETTY_FUNCTION__))
;
464 new (getErrorStorage()) error_type(Err.takePayload());
465 }
466
467 /// Forbid to convert from Error::success() implicitly, this avoids having
468 /// Expected<T> foo() { return Error::success(); } which compiles otherwise
469 /// but triggers the assertion above.
470 Expected(ErrorSuccess) = delete;
471
472 /// Create an Expected<T> success value from the given OtherT value, which
473 /// must be convertible to T.
474 template <typename OtherT>
475 Expected(OtherT &&Val,
476 typename std::enable_if<std::is_convertible<OtherT, T>::value>::type
477 * = nullptr)
478 : HasError(false)
479#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
480 // Expected is unchecked upon construction in Debug builds.
481 , Unchecked(true)
482#endif
483 {
484 new (getStorage()) storage_type(std::forward<OtherT>(Val));
485 }
486
487 /// Move construct an Expected<T> value.
488 Expected(Expected &&Other) { moveConstruct(std::move(Other)); }
489
490 /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT
491 /// must be convertible to T.
492 template <class OtherT>
493 Expected(Expected<OtherT> &&Other,
494 typename std::enable_if<std::is_convertible<OtherT, T>::value>::type
495 * = nullptr) {
496 moveConstruct(std::move(Other));
497 }
498
499 /// Move construct an Expected<T> value from an Expected<OtherT>, where OtherT
500 /// isn't convertible to T.
501 template <class OtherT>
502 explicit Expected(
503 Expected<OtherT> &&Other,
504 typename std::enable_if<!std::is_convertible<OtherT, T>::value>::type * =
505 nullptr) {
506 moveConstruct(std::move(Other));
507 }
508
509 /// Move-assign from another Expected<T>.
510 Expected &operator=(Expected &&Other) {
511 moveAssign(std::move(Other));
512 return *this;
513 }
514
515 /// Destroy an Expected<T>.
516 ~Expected() {
517 assertIsChecked();
518 if (!HasError)
519 getStorage()->~storage_type();
520 else
521 getErrorStorage()->~error_type();
522 }
523
524 /// Return false if there is an error.
525 explicit operator bool() {
526#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
527 Unchecked = HasError;
528#endif
529 return !HasError;
530 }
531
532 /// Returns a reference to the stored T value.
533 reference get() {
534 assertIsChecked();
535 return *getStorage();
536 }
537
538 /// Returns a const reference to the stored T value.
539 const_reference get() const {
540 assertIsChecked();
541 return const_cast<Expected<T> *>(this)->get();
542 }
543
544 /// Check that this Expected<T> is an error of type ErrT.
545 template <typename ErrT> bool errorIsA() const {
546 return HasError && (*getErrorStorage())->template isA<ErrT>();
547 }
548
549 /// Take ownership of the stored error.
550 /// After calling this the Expected<T> is in an indeterminate state that can
551 /// only be safely destructed. No further calls (beside the destructor) should
552 /// be made on the Expected<T> vaule.
553 Error takeError() {
554#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
555 Unchecked = false;
556#endif
557 return HasError ? Error(std::move(*getErrorStorage())) : Error::success();
558 }
559
560 /// Returns a pointer to the stored T value.
561 pointer operator->() {
562 assertIsChecked();
563 return toPointer(getStorage());
564 }
565
566 /// Returns a const pointer to the stored T value.
567 const_pointer operator->() const {
568 assertIsChecked();
569 return toPointer(getStorage());
570 }
571
572 /// Returns a reference to the stored T value.
573 reference operator*() {
574 assertIsChecked();
575 return *getStorage();
576 }
577
578 /// Returns a const reference to the stored T value.
579 const_reference operator*() const {
580 assertIsChecked();
581 return *getStorage();
582 }
583
584private:
585 template <class T1>
586 static bool compareThisIfSameType(const T1 &a, const T1 &b) {
587 return &a == &b;
588 }
589
590 template <class T1, class T2>
591 static bool compareThisIfSameType(const T1 &a, const T2 &b) {
592 return false;
593 }
594
595 template <class OtherT> void moveConstruct(Expected<OtherT> &&Other) {
596 HasError = Other.HasError;
597#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
598 Unchecked = true;
599 Other.Unchecked = false;
600#endif
601
602 if (!HasError)
603 new (getStorage()) storage_type(std::move(*Other.getStorage()));
604 else
605 new (getErrorStorage()) error_type(std::move(*Other.getErrorStorage()));
606 }
607
608 template <class OtherT> void moveAssign(Expected<OtherT> &&Other) {
609 assertIsChecked();
610
611 if (compareThisIfSameType(*this, Other))
612 return;
613
614 this->~Expected();
615 new (this) Expected(std::move(Other));
616 }
617
618 pointer toPointer(pointer Val) { return Val; }
619
620 const_pointer toPointer(const_pointer Val) const { return Val; }
621
622 pointer toPointer(wrap *Val) { return &Val->get(); }
623
624 const_pointer toPointer(const wrap *Val) const { return &Val->get(); }
625
626 storage_type *getStorage() {
627 assert(!HasError && "Cannot get value when an error exists!")((!HasError && "Cannot get value when an error exists!"
) ? static_cast<void> (0) : __assert_fail ("!HasError && \"Cannot get value when an error exists!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/Error.h"
, 627, __PRETTY_FUNCTION__))
;
628 return reinterpret_cast<storage_type *>(TStorage.buffer);
629 }
630
631 const storage_type *getStorage() const {
632 assert(!HasError && "Cannot get value when an error exists!")((!HasError && "Cannot get value when an error exists!"
) ? static_cast<void> (0) : __assert_fail ("!HasError && \"Cannot get value when an error exists!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/Error.h"
, 632, __PRETTY_FUNCTION__))
;
633 return reinterpret_cast<const storage_type *>(TStorage.buffer);
634 }
635
636 error_type *getErrorStorage() {
637 assert(HasError && "Cannot get error when a value exists!")((HasError && "Cannot get error when a value exists!"
) ? static_cast<void> (0) : __assert_fail ("HasError && \"Cannot get error when a value exists!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/Error.h"
, 637, __PRETTY_FUNCTION__))
;
638 return reinterpret_cast<error_type *>(ErrorStorage.buffer);
639 }
640
641 const error_type *getErrorStorage() const {
642 assert(HasError && "Cannot get error when a value exists!")((HasError && "Cannot get error when a value exists!"
) ? static_cast<void> (0) : __assert_fail ("HasError && \"Cannot get error when a value exists!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/Error.h"
, 642, __PRETTY_FUNCTION__))
;
643 return reinterpret_cast<const error_type *>(ErrorStorage.buffer);
644 }
645
646 // Used by ExpectedAsOutParameter to reset the checked flag.
647 void setUnchecked() {
648#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
649 Unchecked = true;
650#endif
651 }
652
653#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
654 LLVM_ATTRIBUTE_NORETURN__attribute__((noreturn))
655 LLVM_ATTRIBUTE_NOINLINE__attribute__((noinline))
656 void fatalUncheckedExpected() const {
657 dbgs() << "Expected<T> must be checked before access or destruction.\n";
658 if (HasError) {
659 dbgs() << "Unchecked Expected<T> contained error:\n";
660 (*getErrorStorage())->log(dbgs());
661 } else
662 dbgs() << "Expected<T> value was in success state. (Note: Expected<T> "
663 "values in success mode must still be checked prior to being "
664 "destroyed).\n";
665 abort();
666 }
667#endif
668
669 void assertIsChecked() {
670#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
671 if (LLVM_UNLIKELY(Unchecked)__builtin_expect((bool)(Unchecked), false))
672 fatalUncheckedExpected();
673#endif
674 }
675
676 union {
677 AlignedCharArrayUnion<storage_type> TStorage;
678 AlignedCharArrayUnion<error_type> ErrorStorage;
679 };
680 bool HasError : 1;
681#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
682 bool Unchecked : 1;
683#endif
684};
685
686/// Report a serious error, calling any installed error handler. See
687/// ErrorHandling.h.
688LLVM_ATTRIBUTE_NORETURN__attribute__((noreturn)) void report_fatal_error(Error Err,
689 bool gen_crash_diag = true);
690
691/// Report a fatal error if Err is a failure value.
692///
693/// This function can be used to wrap calls to fallible functions ONLY when it
694/// is known that the Error will always be a success value. E.g.
695///
696/// @code{.cpp}
697/// // foo only attempts the fallible operation if DoFallibleOperation is
698/// // true. If DoFallibleOperation is false then foo always returns
699/// // Error::success().
700/// Error foo(bool DoFallibleOperation);
701///
702/// cantFail(foo(false));
703/// @endcode
704inline void cantFail(Error Err, const char *Msg = nullptr) {
705 if (Err) {
706 if (!Msg)
707 Msg = "Failure value returned from cantFail wrapped call";
708 llvm_unreachable(Msg)::llvm::llvm_unreachable_internal(Msg, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/Error.h"
, 708)
;
709 }
710}
711
712/// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and
713/// returns the contained value.
714///
715/// This function can be used to wrap calls to fallible functions ONLY when it
716/// is known that the Error will always be a success value. E.g.
717///
718/// @code{.cpp}
719/// // foo only attempts the fallible operation if DoFallibleOperation is
720/// // true. If DoFallibleOperation is false then foo always returns an int.
721/// Expected<int> foo(bool DoFallibleOperation);
722///
723/// int X = cantFail(foo(false));
724/// @endcode
725template <typename T>
726T cantFail(Expected<T> ValOrErr, const char *Msg = nullptr) {
727 if (ValOrErr)
728 return std::move(*ValOrErr);
729 else {
730 if (!Msg)
731 Msg = "Failure value returned from cantFail wrapped call";
732 llvm_unreachable(Msg)::llvm::llvm_unreachable_internal(Msg, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/Error.h"
, 732)
;
733 }
734}
735
736/// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and
737/// returns the contained reference.
738///
739/// This function can be used to wrap calls to fallible functions ONLY when it
740/// is known that the Error will always be a success value. E.g.
741///
742/// @code{.cpp}
743/// // foo only attempts the fallible operation if DoFallibleOperation is
744/// // true. If DoFallibleOperation is false then foo always returns a Bar&.
745/// Expected<Bar&> foo(bool DoFallibleOperation);
746///
747/// Bar &X = cantFail(foo(false));
748/// @endcode
749template <typename T>
750T& cantFail(Expected<T&> ValOrErr, const char *Msg = nullptr) {
751 if (ValOrErr)
752 return *ValOrErr;
753 else {
754 if (!Msg)
755 Msg = "Failure value returned from cantFail wrapped call";
756 llvm_unreachable(Msg)::llvm::llvm_unreachable_internal(Msg, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/Error.h"
, 756)
;
757 }
758}
759
760/// Helper for testing applicability of, and applying, handlers for
761/// ErrorInfo types.
762template <typename HandlerT>
763class ErrorHandlerTraits
764 : public ErrorHandlerTraits<decltype(
765 &std::remove_reference<HandlerT>::type::operator())> {};
766
767// Specialization functions of the form 'Error (const ErrT&)'.
768template <typename ErrT> class ErrorHandlerTraits<Error (&)(ErrT &)> {
769public:
770 static bool appliesTo(const ErrorInfoBase &E) {
771 return E.template isA<ErrT>();
772 }
773
774 template <typename HandlerT>
775 static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
776 assert(appliesTo(*E) && "Applying incorrect handler")((appliesTo(*E) && "Applying incorrect handler") ? static_cast
<void> (0) : __assert_fail ("appliesTo(*E) && \"Applying incorrect handler\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/Error.h"
, 776, __PRETTY_FUNCTION__))
;
777 return H(static_cast<ErrT &>(*E));
778 }
779};
780
781// Specialization functions of the form 'void (const ErrT&)'.
782template <typename ErrT> class ErrorHandlerTraits<void (&)(ErrT &)> {
783public:
784 static bool appliesTo(const ErrorInfoBase &E) {
785 return E.template isA<ErrT>();
786 }
787
788 template <typename HandlerT>
789 static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
790 assert(appliesTo(*E) && "Applying incorrect handler")((appliesTo(*E) && "Applying incorrect handler") ? static_cast
<void> (0) : __assert_fail ("appliesTo(*E) && \"Applying incorrect handler\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/Error.h"
, 790, __PRETTY_FUNCTION__))
;
791 H(static_cast<ErrT &>(*E));
792 return Error::success();
793 }
794};
795
796/// Specialization for functions of the form 'Error (std::unique_ptr<ErrT>)'.
797template <typename ErrT>
798class ErrorHandlerTraits<Error (&)(std::unique_ptr<ErrT>)> {
799public:
800 static bool appliesTo(const ErrorInfoBase &E) {
801 return E.template isA<ErrT>();
802 }
803
804 template <typename HandlerT>
805 static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
806 assert(appliesTo(*E) && "Applying incorrect handler")((appliesTo(*E) && "Applying incorrect handler") ? static_cast
<void> (0) : __assert_fail ("appliesTo(*E) && \"Applying incorrect handler\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/Error.h"
, 806, __PRETTY_FUNCTION__))
;
807 std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release()));
808 return H(std::move(SubE));
809 }
810};
811
812/// Specialization for functions of the form 'void (std::unique_ptr<ErrT>)'.
813template <typename ErrT>
814class ErrorHandlerTraits<void (&)(std::unique_ptr<ErrT>)> {
815public:
816 static bool appliesTo(const ErrorInfoBase &E) {
817 return E.template isA<ErrT>();
818 }
819
820 template <typename HandlerT>
821 static Error apply(HandlerT &&H, std::unique_ptr<ErrorInfoBase> E) {
822 assert(appliesTo(*E) && "Applying incorrect handler")((appliesTo(*E) && "Applying incorrect handler") ? static_cast
<void> (0) : __assert_fail ("appliesTo(*E) && \"Applying incorrect handler\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/Error.h"
, 822, __PRETTY_FUNCTION__))
;
823 std::unique_ptr<ErrT> SubE(static_cast<ErrT *>(E.release()));
824 H(std::move(SubE));
825 return Error::success();
826 }
827};
828
829// Specialization for member functions of the form 'RetT (const ErrT&)'.
830template <typename C, typename RetT, typename ErrT>
831class ErrorHandlerTraits<RetT (C::*)(ErrT &)>
832 : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
833
834// Specialization for member functions of the form 'RetT (const ErrT&) const'.
835template <typename C, typename RetT, typename ErrT>
836class ErrorHandlerTraits<RetT (C::*)(ErrT &) const>
837 : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
838
839// Specialization for member functions of the form 'RetT (const ErrT&)'.
840template <typename C, typename RetT, typename ErrT>
841class ErrorHandlerTraits<RetT (C::*)(const ErrT &)>
842 : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
843
844// Specialization for member functions of the form 'RetT (const ErrT&) const'.
845template <typename C, typename RetT, typename ErrT>
846class ErrorHandlerTraits<RetT (C::*)(const ErrT &) const>
847 : public ErrorHandlerTraits<RetT (&)(ErrT &)> {};
848
849/// Specialization for member functions of the form
850/// 'RetT (std::unique_ptr<ErrT>)'.
851template <typename C, typename RetT, typename ErrT>
852class ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>)>
853 : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {};
854
855/// Specialization for member functions of the form
856/// 'RetT (std::unique_ptr<ErrT>) const'.
857template <typename C, typename RetT, typename ErrT>
858class ErrorHandlerTraits<RetT (C::*)(std::unique_ptr<ErrT>) const>
859 : public ErrorHandlerTraits<RetT (&)(std::unique_ptr<ErrT>)> {};
860
861inline Error handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload) {
862 return Error(std::move(Payload));
863}
864
865template <typename HandlerT, typename... HandlerTs>
866Error handleErrorImpl(std::unique_ptr<ErrorInfoBase> Payload,
867 HandlerT &&Handler, HandlerTs &&... Handlers) {
868 if (ErrorHandlerTraits<HandlerT>::appliesTo(*Payload))
869 return ErrorHandlerTraits<HandlerT>::apply(std::forward<HandlerT>(Handler),
870 std::move(Payload));
871 return handleErrorImpl(std::move(Payload),
872 std::forward<HandlerTs>(Handlers)...);
873}
874
875/// Pass the ErrorInfo(s) contained in E to their respective handlers. Any
876/// unhandled errors (or Errors returned by handlers) are re-concatenated and
877/// returned.
878/// Because this function returns an error, its result must also be checked
879/// or returned. If you intend to handle all errors use handleAllErrors
880/// (which returns void, and will abort() on unhandled errors) instead.
881template <typename... HandlerTs>
882Error handleErrors(Error E, HandlerTs &&... Hs) {
883 if (!E)
884 return Error::success();
885
886 std::unique_ptr<ErrorInfoBase> Payload = E.takePayload();
887
888 if (Payload->isA<ErrorList>()) {
889 ErrorList &List = static_cast<ErrorList &>(*Payload);
890 Error R;
891 for (auto &P : List.Payloads)
892 R = ErrorList::join(
893 std::move(R),
894 handleErrorImpl(std::move(P), std::forward<HandlerTs>(Hs)...));
895 return R;
896 }
897
898 return handleErrorImpl(std::move(Payload), std::forward<HandlerTs>(Hs)...);
899}
900
901/// Behaves the same as handleErrors, except that by contract all errors
902/// *must* be handled by the given handlers (i.e. there must be no remaining
903/// errors after running the handlers, or llvm_unreachable is called).
904template <typename... HandlerTs>
905void handleAllErrors(Error E, HandlerTs &&... Handlers) {
906 cantFail(handleErrors(std::move(E), std::forward<HandlerTs>(Handlers)...));
907}
908
909/// Check that E is a non-error, then drop it.
910/// If E is an error, llvm_unreachable will be called.
911inline void handleAllErrors(Error E) {
912 cantFail(std::move(E));
913}
914
915/// Handle any errors (if present) in an Expected<T>, then try a recovery path.
916///
917/// If the incoming value is a success value it is returned unmodified. If it
918/// is a failure value then it the contained error is passed to handleErrors.
919/// If handleErrors is able to handle the error then the RecoveryPath functor
920/// is called to supply the final result. If handleErrors is not able to
921/// handle all errors then the unhandled errors are returned.
922///
923/// This utility enables the follow pattern:
924///
925/// @code{.cpp}
926/// enum FooStrategy { Aggressive, Conservative };
927/// Expected<Foo> foo(FooStrategy S);
928///
929/// auto ResultOrErr =
930/// handleExpected(
931/// foo(Aggressive),
932/// []() { return foo(Conservative); },
933/// [](AggressiveStrategyError&) {
934/// // Implicitly conusme this - we'll recover by using a conservative
935/// // strategy.
936/// });
937///
938/// @endcode
939template <typename T, typename RecoveryFtor, typename... HandlerTs>
940Expected<T> handleExpected(Expected<T> ValOrErr, RecoveryFtor &&RecoveryPath,
941 HandlerTs &&... Handlers) {
942 if (ValOrErr)
943 return ValOrErr;
944
945 if (auto Err = handleErrors(ValOrErr.takeError(),
946 std::forward<HandlerTs>(Handlers)...))
947 return std::move(Err);
948
949 return RecoveryPath();
950}
951
952/// Log all errors (if any) in E to OS. If there are any errors, ErrorBanner
953/// will be printed before the first one is logged. A newline will be printed
954/// after each error.
955///
956/// This is useful in the base level of your program to allow clean termination
957/// (allowing clean deallocation of resources, etc.), while reporting error
958/// information to the user.
959void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner);
960
961/// Write all error messages (if any) in E to a string. The newline character
962/// is used to separate error messages.
963inline std::string toString(Error E) {
964 SmallVector<std::string, 2> Errors;
965 handleAllErrors(std::move(E), [&Errors](const ErrorInfoBase &EI) {
966 Errors.push_back(EI.message());
967 });
968 return join(Errors.begin(), Errors.end(), "\n");
969}
970
971/// Consume a Error without doing anything. This method should be used
972/// only where an error can be considered a reasonable and expected return
973/// value.
974///
975/// Uses of this method are potentially indicative of design problems: If it's
976/// legitimate to do nothing while processing an "error", the error-producer
977/// might be more clearly refactored to return an Optional<T>.
978inline void consumeError(Error Err) {
979 handleAllErrors(std::move(Err), [](const ErrorInfoBase &) {});
980}
981
982/// Helper for converting an Error to a bool.
983///
984/// This method returns true if Err is in an error state, or false if it is
985/// in a success state. Puts Err in a checked state in both cases (unlike
986/// Error::operator bool(), which only does this for success states).
987inline bool errorToBool(Error Err) {
988 bool IsError = static_cast<bool>(Err);
989 if (IsError)
990 consumeError(std::move(Err));
991 return IsError;
992}
993
994/// Helper for Errors used as out-parameters.
995///
996/// This helper is for use with the Error-as-out-parameter idiom, where an error
997/// is passed to a function or method by reference, rather than being returned.
998/// In such cases it is helpful to set the checked bit on entry to the function
999/// so that the error can be written to (unchecked Errors abort on assignment)
1000/// and clear the checked bit on exit so that clients cannot accidentally forget
1001/// to check the result. This helper performs these actions automatically using
1002/// RAII:
1003///
1004/// @code{.cpp}
1005/// Result foo(Error &Err) {
1006/// ErrorAsOutParameter ErrAsOutParam(&Err); // 'Checked' flag set
1007/// // <body of foo>
1008/// // <- 'Checked' flag auto-cleared when ErrAsOutParam is destructed.
1009/// }
1010/// @endcode
1011///
1012/// ErrorAsOutParameter takes an Error* rather than Error& so that it can be
1013/// used with optional Errors (Error pointers that are allowed to be null). If
1014/// ErrorAsOutParameter took an Error reference, an instance would have to be
1015/// created inside every condition that verified that Error was non-null. By
1016/// taking an Error pointer we can just create one instance at the top of the
1017/// function.
1018class ErrorAsOutParameter {
1019public:
1020 ErrorAsOutParameter(Error *Err) : Err(Err) {
1021 // Raise the checked bit if Err is success.
1022 if (Err)
1023 (void)!!*Err;
1024 }
1025
1026 ~ErrorAsOutParameter() {
1027 // Clear the checked bit.
1028 if (Err && !*Err)
1029 *Err = Error::success();
1030 }
1031
1032private:
1033 Error *Err;
1034};
1035
1036/// Helper for Expected<T>s used as out-parameters.
1037///
1038/// See ErrorAsOutParameter.
1039template <typename T>
1040class ExpectedAsOutParameter {
1041public:
1042 ExpectedAsOutParameter(Expected<T> *ValOrErr)
1043 : ValOrErr(ValOrErr) {
1044 if (ValOrErr)
1045 (void)!!*ValOrErr;
1046 }
1047
1048 ~ExpectedAsOutParameter() {
1049 if (ValOrErr)
1050 ValOrErr->setUnchecked();
1051 }
1052
1053private:
1054 Expected<T> *ValOrErr;
1055};
1056
1057/// This class wraps a std::error_code in a Error.
1058///
1059/// This is useful if you're writing an interface that returns a Error
1060/// (or Expected) and you want to call code that still returns
1061/// std::error_codes.
1062class ECError : public ErrorInfo<ECError> {
1063 friend Error errorCodeToError(std::error_code);
1064
1065public:
1066 void setErrorCode(std::error_code EC) { this->EC = EC; }
1067 std::error_code convertToErrorCode() const override { return EC; }
1068 void log(raw_ostream &OS) const override { OS << EC.message(); }
1069
1070 // Used by ErrorInfo::classID.
1071 static char ID;
1072
1073protected:
1074 ECError() = default;
1075 ECError(std::error_code EC) : EC(EC) {}
1076
1077 std::error_code EC;
1078};
1079
1080/// The value returned by this function can be returned from convertToErrorCode
1081/// for Error values where no sensible translation to std::error_code exists.
1082/// It should only be used in this situation, and should never be used where a
1083/// sensible conversion to std::error_code is available, as attempts to convert
1084/// to/from this error will result in a fatal error. (i.e. it is a programmatic
1085///error to try to convert such a value).
1086std::error_code inconvertibleErrorCode();
1087
1088/// Helper for converting an std::error_code to a Error.
1089Error errorCodeToError(std::error_code EC);
1090
1091/// Helper for converting an ECError to a std::error_code.
1092///
1093/// This method requires that Err be Error() or an ECError, otherwise it
1094/// will trigger a call to abort().
1095std::error_code errorToErrorCode(Error Err);
1096
1097/// Convert an ErrorOr<T> to an Expected<T>.
1098template <typename T> Expected<T> errorOrToExpected(ErrorOr<T> &&EO) {
1099 if (auto EC = EO.getError())
1100 return errorCodeToError(EC);
1101 return std::move(*EO);
1102}
1103
1104/// Convert an Expected<T> to an ErrorOr<T>.
1105template <typename T> ErrorOr<T> expectedToErrorOr(Expected<T> &&E) {
1106 if (auto Err = E.takeError())
1107 return errorToErrorCode(std::move(Err));
1108 return std::move(*E);
1109}
1110
1111/// This class wraps a string in an Error.
1112///
1113/// StringError is useful in cases where the client is not expected to be able
1114/// to consume the specific error message programmatically (for example, if the
1115/// error message is to be presented to the user).
1116///
1117/// StringError can also be used when additional information is to be printed
1118/// along with a error_code message. Depending on the constructor called, this
1119/// class can either display:
1120/// 1. the error_code message (ECError behavior)
1121/// 2. a string
1122/// 3. the error_code message and a string
1123///
1124/// These behaviors are useful when subtyping is required; for example, when a
1125/// specific library needs an explicit error type. In the example below,
1126/// PDBError is derived from StringError:
1127///
1128/// @code{.cpp}
1129/// Expected<int> foo() {
1130/// return llvm::make_error<PDBError>(pdb_error_code::dia_failed_loading,
1131/// "Additional information");
1132/// }
1133/// @endcode
1134///
1135class StringError : public ErrorInfo<StringError> {
1136public:
1137 static char ID;
1138
1139 // Prints EC + S and converts to EC
1140 StringError(std::error_code EC, const Twine &S = Twine());
1141
1142 // Prints S and converts to EC
1143 StringError(const Twine &S, std::error_code EC);
1144
1145 void log(raw_ostream &OS) const override;
1146 std::error_code convertToErrorCode() const override;
1147
1148 const std::string &getMessage() const { return Msg; }
1149
1150private:
1151 std::string Msg;
1152 std::error_code EC;
1153 const bool PrintMsgOnly = false;
1154};
1155
1156/// Create formatted StringError object.
1157template <typename... Ts>
1158Error createStringError(std::error_code EC, char const *Fmt,
1159 const Ts &... Vals) {
1160 std::string Buffer;
1161 raw_string_ostream Stream(Buffer);
1162 Stream << format(Fmt, Vals...);
1163 return make_error<StringError>(Stream.str(), EC);
1164}
1165
1166Error createStringError(std::error_code EC, char const *Msg);
1167
1168/// This class wraps a filename and another Error.
1169///
1170/// In some cases, an error needs to live along a 'source' name, in order to
1171/// show more detailed information to the user.
1172class FileError final : public ErrorInfo<FileError> {
1173
1174 friend Error createFileError(std::string, Error);
1175
1176public:
1177 void log(raw_ostream &OS) const override {
1178 assert(Err && !FileName.empty() && "Trying to log after takeError().")((Err && !FileName.empty() && "Trying to log after takeError()."
) ? static_cast<void> (0) : __assert_fail ("Err && !FileName.empty() && \"Trying to log after takeError().\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/Error.h"
, 1178, __PRETTY_FUNCTION__))
;
1179 OS << "'" << FileName << "': ";
1180 Err->log(OS);
1181 }
1182
1183 Error takeError() { return Error(std::move(Err)); }
1184
1185 std::error_code convertToErrorCode() const override;
1186
1187 // Used by ErrorInfo::classID.
1188 static char ID;
1189
1190private:
1191 FileError(std::string F, std::unique_ptr<ErrorInfoBase> E) {
1192 assert(E && "Cannot create FileError from Error success value.")((E && "Cannot create FileError from Error success value."
) ? static_cast<void> (0) : __assert_fail ("E && \"Cannot create FileError from Error success value.\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/Error.h"
, 1192, __PRETTY_FUNCTION__))
;
1193 assert(!F.empty() &&((!F.empty() && "The file name provided to FileError must not be empty."
) ? static_cast<void> (0) : __assert_fail ("!F.empty() && \"The file name provided to FileError must not be empty.\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/Error.h"
, 1194, __PRETTY_FUNCTION__))
1194 "The file name provided to FileError must not be empty.")((!F.empty() && "The file name provided to FileError must not be empty."
) ? static_cast<void> (0) : __assert_fail ("!F.empty() && \"The file name provided to FileError must not be empty.\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/Support/Error.h"
, 1194, __PRETTY_FUNCTION__))
;
1195 FileName = F;
1196 Err = std::move(E);
1197 }
1198
1199 static Error build(std::string F, Error E) {
1200 return Error(std::unique_ptr<FileError>(new FileError(F, E.takePayload())));
1201 }
1202
1203 std::string FileName;
1204 std::unique_ptr<ErrorInfoBase> Err;
1205};
1206
1207/// Concatenate a source file path and/or name with an Error. The resulting
1208/// Error is unchecked.
1209inline Error createFileError(std::string F, Error E) {
1210 return FileError::build(F, std::move(E));
1211}
1212
1213Error createFileError(std::string F, ErrorSuccess) = delete;
1214
1215/// Helper for check-and-exit error handling.
1216///
1217/// For tool use only. NOT FOR USE IN LIBRARY CODE.
1218///
1219class ExitOnError {
1220public:
1221 /// Create an error on exit helper.
1222 ExitOnError(std::string Banner = "", int DefaultErrorExitCode = 1)
1223 : Banner(std::move(Banner)),
1224 GetExitCode([=](const Error &) { return DefaultErrorExitCode; }) {}
1225
1226 /// Set the banner string for any errors caught by operator().
1227 void setBanner(std::string Banner) { this->Banner = std::move(Banner); }
1228
1229 /// Set the exit-code mapper function.
1230 void setExitCodeMapper(std::function<int(const Error &)> GetExitCode) {
1231 this->GetExitCode = std::move(GetExitCode);
1232 }
1233
1234 /// Check Err. If it's in a failure state log the error(s) and exit.
1235 void operator()(Error Err) const { checkError(std::move(Err)); }
1236
1237 /// Check E. If it's in a success state then return the contained value. If
1238 /// it's in a failure state log the error(s) and exit.
1239 template <typename T> T operator()(Expected<T> &&E) const {
1240 checkError(E.takeError());
1241 return std::move(*E);
1242 }
1243
1244 /// Check E. If it's in a success state then return the contained reference. If
1245 /// it's in a failure state log the error(s) and exit.
1246 template <typename T> T& operator()(Expected<T&> &&E) const {
1247 checkError(E.takeError());
1248 return *E;
1249 }
1250
1251private:
1252 void checkError(Error Err) const {
1253 if (Err) {
1254 int ExitCode = GetExitCode(Err);
1255 logAllUnhandledErrors(std::move(Err), errs(), Banner);
1256 exit(ExitCode);
1257 }
1258 }
1259
1260 std::string Banner;
1261 std::function<int(const Error &)> GetExitCode;
1262};
1263
1264/// Conversion from Error to LLVMErrorRef for C error bindings.
1265inline LLVMErrorRef wrap(Error Err) {
1266 return reinterpret_cast<LLVMErrorRef>(Err.takePayload().release());
1267}
1268
1269/// Conversion from LLVMErrorRef to Error for C error bindings.
1270inline Error unwrap(LLVMErrorRef ErrRef) {
1271 return Error(std::unique_ptr<ErrorInfoBase>(
1272 reinterpret_cast<ErrorInfoBase *>(ErrRef)));
1273}
1274
1275} // end namespace llvm
1276
1277#endif // LLVM_SUPPORT_ERROR_H

/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/ADT/STLExtras.h

1//===- llvm/ADT/STLExtras.h - Useful STL related functions ------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains some templates that are useful if you are working with the
11// STL at all.
12//
13// No library is required when using these functions.
14//
15//===----------------------------------------------------------------------===//
16
17#ifndef LLVM_ADT_STLEXTRAS_H
18#define LLVM_ADT_STLEXTRAS_H
19
20#include "llvm/ADT/Optional.h"
21#include "llvm/ADT/SmallVector.h"
22#include "llvm/ADT/iterator.h"
23#include "llvm/ADT/iterator_range.h"
24#include "llvm/Config/abi-breaking.h"
25#include "llvm/Support/ErrorHandling.h"
26#include <algorithm>
27#include <cassert>
28#include <cstddef>
29#include <cstdint>
30#include <cstdlib>
31#include <functional>
32#include <initializer_list>
33#include <iterator>
34#include <limits>
35#include <memory>
36#include <tuple>
37#include <type_traits>
38#include <utility>
39
40#ifdef EXPENSIVE_CHECKS
41#include <random> // for std::mt19937
42#endif
43
44namespace llvm {
45
46// Only used by compiler if both template types are the same. Useful when
47// using SFINAE to test for the existence of member functions.
48template <typename T, T> struct SameType;
49
50namespace detail {
51
52template <typename RangeT>
53using IterOfRange = decltype(std::begin(std::declval<RangeT &>()));
54
55template <typename RangeT>
56using ValueOfRange = typename std::remove_reference<decltype(
57 *std::begin(std::declval<RangeT &>()))>::type;
58
59} // end namespace detail
60
61//===----------------------------------------------------------------------===//
62// Extra additions to <type_traits>
63//===----------------------------------------------------------------------===//
64
65template <typename T>
66struct negation : std::integral_constant<bool, !bool(T::value)> {};
67
68template <typename...> struct conjunction : std::true_type {};
69template <typename B1> struct conjunction<B1> : B1 {};
70template <typename B1, typename... Bn>
71struct conjunction<B1, Bn...>
72 : std::conditional<bool(B1::value), conjunction<Bn...>, B1>::type {};
73
74//===----------------------------------------------------------------------===//
75// Extra additions to <functional>
76//===----------------------------------------------------------------------===//
77
78template <class Ty> struct identity {
79 using argument_type = Ty;
80
81 Ty &operator()(Ty &self) const {
82 return self;
83 }
84 const Ty &operator()(const Ty &self) const {
85 return self;
86 }
87};
88
89template <class Ty> struct less_ptr {
90 bool operator()(const Ty* left, const Ty* right) const {
91 return *left < *right;
92 }
93};
94
95template <class Ty> struct greater_ptr {
96 bool operator()(const Ty* left, const Ty* right) const {
97 return *right < *left;
98 }
99};
100
101/// An efficient, type-erasing, non-owning reference to a callable. This is
102/// intended for use as the type of a function parameter that is not used
103/// after the function in question returns.
104///
105/// This class does not own the callable, so it is not in general safe to store
106/// a function_ref.
107template<typename Fn> class function_ref;
108
109template<typename Ret, typename ...Params>
110class function_ref<Ret(Params...)> {
111 Ret (*callback)(intptr_t callable, Params ...params) = nullptr;
112 intptr_t callable;
113
114 template<typename Callable>
115 static Ret callback_fn(intptr_t callable, Params ...params) {
116 return (*reinterpret_cast<Callable*>(callable))(
117 std::forward<Params>(params)...);
118 }
119
120public:
121 function_ref() = default;
122 function_ref(std::nullptr_t) {}
123
124 template <typename Callable>
125 function_ref(Callable &&callable,
126 typename std::enable_if<
127 !std::is_same<typename std::remove_reference<Callable>::type,
128 function_ref>::value>::type * = nullptr)
129 : callback(callback_fn<typename std::remove_reference<Callable>::type>),
130 callable(reinterpret_cast<intptr_t>(&callable)) {}
131
132 Ret operator()(Params ...params) const {
133 return callback(callable, std::forward<Params>(params)...);
134 }
135
136 operator bool() const { return callback; }
137};
138
139// deleter - Very very very simple method that is used to invoke operator
140// delete on something. It is used like this:
141//
142// for_each(V.begin(), B.end(), deleter<Interval>);
143template <class T>
144inline void deleter(T *Ptr) {
145 delete Ptr;
146}
147
148//===----------------------------------------------------------------------===//
149// Extra additions to <iterator>
150//===----------------------------------------------------------------------===//
151
152namespace adl_detail {
153
154using std::begin;
155
156template <typename ContainerTy>
157auto adl_begin(ContainerTy &&container)
158 -> decltype(begin(std::forward<ContainerTy>(container))) {
159 return begin(std::forward<ContainerTy>(container));
160}
161
162using std::end;
163
164template <typename ContainerTy>
165auto adl_end(ContainerTy &&container)
166 -> decltype(end(std::forward<ContainerTy>(container))) {
167 return end(std::forward<ContainerTy>(container));
168}
169
170using std::swap;
171
172template <typename T>
173void adl_swap(T &&lhs, T &&rhs) noexcept(noexcept(swap(std::declval<T>(),
174 std::declval<T>()))) {
175 swap(std::forward<T>(lhs), std::forward<T>(rhs));
176}
177
178} // end namespace adl_detail
179
180template <typename ContainerTy>
181auto adl_begin(ContainerTy &&container)
182 -> decltype(adl_detail::adl_begin(std::forward<ContainerTy>(container))) {
183 return adl_detail::adl_begin(std::forward<ContainerTy>(container));
184}
185
186template <typename ContainerTy>
187auto adl_end(ContainerTy &&container)
188 -> decltype(adl_detail::adl_end(std::forward<ContainerTy>(container))) {
189 return adl_detail::adl_end(std::forward<ContainerTy>(container));
190}
191
192template <typename T>
193void adl_swap(T &&lhs, T &&rhs) noexcept(
194 noexcept(adl_detail::adl_swap(std::declval<T>(), std::declval<T>()))) {
195 adl_detail::adl_swap(std::forward<T>(lhs), std::forward<T>(rhs));
196}
197
198// mapped_iterator - This is a simple iterator adapter that causes a function to
199// be applied whenever operator* is invoked on the iterator.
200
201template <typename ItTy, typename FuncTy,
202 typename FuncReturnTy =
203 decltype(std::declval<FuncTy>()(*std::declval<ItTy>()))>
204class mapped_iterator
205 : public iterator_adaptor_base<
206 mapped_iterator<ItTy, FuncTy>, ItTy,
207 typename std::iterator_traits<ItTy>::iterator_category,
208 typename std::remove_reference<FuncReturnTy>::type> {
209public:
210 mapped_iterator(ItTy U, FuncTy F)
211 : mapped_iterator::iterator_adaptor_base(std::move(U)), F(std::move(F)) {}
212
213 ItTy getCurrent() { return this->I; }
214
215 FuncReturnTy operator*() { return F(*this->I); }
216
217private:
218 FuncTy F;
219};
220
221// map_iterator - Provide a convenient way to create mapped_iterators, just like
222// make_pair is useful for creating pairs...
223template <class ItTy, class FuncTy>
224inline mapped_iterator<ItTy, FuncTy> map_iterator(ItTy I, FuncTy F) {
225 return mapped_iterator<ItTy, FuncTy>(std::move(I), std::move(F));
226}
227
228/// Helper to determine if type T has a member called rbegin().
229template <typename Ty> class has_rbegin_impl {
230 using yes = char[1];
231 using no = char[2];
232
233 template <typename Inner>
234 static yes& test(Inner *I, decltype(I->rbegin()) * = nullptr);
235
236 template <typename>
237 static no& test(...);
238
239public:
240 static const bool value = sizeof(test<Ty>(nullptr)) == sizeof(yes);
241};
242
243/// Metafunction to determine if T& or T has a member called rbegin().
244template <typename Ty>
245struct has_rbegin : has_rbegin_impl<typename std::remove_reference<Ty>::type> {
246};
247
248// Returns an iterator_range over the given container which iterates in reverse.
249// Note that the container must have rbegin()/rend() methods for this to work.
250template <typename ContainerTy>
251auto reverse(ContainerTy &&C,
252 typename std::enable_if<has_rbegin<ContainerTy>::value>::type * =
253 nullptr) -> decltype(make_range(C.rbegin(), C.rend())) {
254 return make_range(C.rbegin(), C.rend());
255}
256
257// Returns a std::reverse_iterator wrapped around the given iterator.
258template <typename IteratorTy>
259std::reverse_iterator<IteratorTy> make_reverse_iterator(IteratorTy It) {
260 return std::reverse_iterator<IteratorTy>(It);
261}
262
263// Returns an iterator_range over the given container which iterates in reverse.
264// Note that the container must have begin()/end() methods which return
265// bidirectional iterators for this to work.
266template <typename ContainerTy>
267auto reverse(
268 ContainerTy &&C,
269 typename std::enable_if<!has_rbegin<ContainerTy>::value>::type * = nullptr)
270 -> decltype(make_range(llvm::make_reverse_iterator(std::end(C)),
271 llvm::make_reverse_iterator(std::begin(C)))) {
272 return make_range(llvm::make_reverse_iterator(std::end(C)),
273 llvm::make_reverse_iterator(std::begin(C)));
274}
275
276/// An iterator adaptor that filters the elements of given inner iterators.
277///
278/// The predicate parameter should be a callable object that accepts the wrapped
279/// iterator's reference type and returns a bool. When incrementing or
280/// decrementing the iterator, it will call the predicate on each element and
281/// skip any where it returns false.
282///
283/// \code
284/// int A[] = { 1, 2, 3, 4 };
285/// auto R = make_filter_range(A, [](int N) { return N % 2 == 1; });
286/// // R contains { 1, 3 }.
287/// \endcode
288///
289/// Note: filter_iterator_base implements support for forward iteration.
290/// filter_iterator_impl exists to provide support for bidirectional iteration,
291/// conditional on whether the wrapped iterator supports it.
292template <typename WrappedIteratorT, typename PredicateT, typename IterTag>
293class filter_iterator_base
294 : public iterator_adaptor_base<
295 filter_iterator_base<WrappedIteratorT, PredicateT, IterTag>,
296 WrappedIteratorT,
297 typename std::common_type<
298 IterTag, typename std::iterator_traits<
299 WrappedIteratorT>::iterator_category>::type> {
300 using BaseT = iterator_adaptor_base<
301 filter_iterator_base<WrappedIteratorT, PredicateT, IterTag>,
302 WrappedIteratorT,
303 typename std::common_type<
304 IterTag, typename std::iterator_traits<
305 WrappedIteratorT>::iterator_category>::type>;
306
307protected:
308 WrappedIteratorT End;
309 PredicateT Pred;
310
311 void findNextValid() {
312 while (this->I != End && !Pred(*this->I))
313 BaseT::operator++();
314 }
315
316 // Construct the iterator. The begin iterator needs to know where the end
317 // is, so that it can properly stop when it gets there. The end iterator only
318 // needs the predicate to support bidirectional iteration.
319 filter_iterator_base(WrappedIteratorT Begin, WrappedIteratorT End,
320 PredicateT Pred)
321 : BaseT(Begin), End(End), Pred(Pred) {
322 findNextValid();
323 }
324
325public:
326 using BaseT::operator++;
327
328 filter_iterator_base &operator++() {
329 BaseT::operator++();
330 findNextValid();
331 return *this;
332 }
333};
334
335/// Specialization of filter_iterator_base for forward iteration only.
336template <typename WrappedIteratorT, typename PredicateT,
337 typename IterTag = std::forward_iterator_tag>
338class filter_iterator_impl
339 : public filter_iterator_base<WrappedIteratorT, PredicateT, IterTag> {
340 using BaseT = filter_iterator_base<WrappedIteratorT, PredicateT, IterTag>;
341
342public:
343 filter_iterator_impl(WrappedIteratorT Begin, WrappedIteratorT End,
344 PredicateT Pred)
345 : BaseT(Begin, End, Pred) {}
346};
347
348/// Specialization of filter_iterator_base for bidirectional iteration.
349template <typename WrappedIteratorT, typename PredicateT>
350class filter_iterator_impl<WrappedIteratorT, PredicateT,
351 std::bidirectional_iterator_tag>
352 : public filter_iterator_base<WrappedIteratorT, PredicateT,
353 std::bidirectional_iterator_tag> {
354 using BaseT = filter_iterator_base<WrappedIteratorT, PredicateT,
355 std::bidirectional_iterator_tag>;
356 void findPrevValid() {
357 while (!this->Pred(*this->I))
358 BaseT::operator--();
359 }
360
361public:
362 using BaseT::operator--;
363
364 filter_iterator_impl(WrappedIteratorT Begin, WrappedIteratorT End,
365 PredicateT Pred)
366 : BaseT(Begin, End, Pred) {}
367
368 filter_iterator_impl &operator--() {
369 BaseT::operator--();
370 findPrevValid();
371 return *this;
372 }
373};
374
375namespace detail {
376
377template <bool is_bidirectional> struct fwd_or_bidi_tag_impl {
378 using type = std::forward_iterator_tag;
379};
380
381template <> struct fwd_or_bidi_tag_impl<true> {
382 using type = std::bidirectional_iterator_tag;
383};
384
385/// Helper which sets its type member to forward_iterator_tag if the category
386/// of \p IterT does not derive from bidirectional_iterator_tag, and to
387/// bidirectional_iterator_tag otherwise.
388template <typename IterT> struct fwd_or_bidi_tag {
389 using type = typename fwd_or_bidi_tag_impl<std::is_base_of<
390 std::bidirectional_iterator_tag,
391 typename std::iterator_traits<IterT>::iterator_category>::value>::type;
392};
393
394} // namespace detail
395
396/// Defines filter_iterator to a suitable specialization of
397/// filter_iterator_impl, based on the underlying iterator's category.
398template <typename WrappedIteratorT, typename PredicateT>
399using filter_iterator = filter_iterator_impl<
400 WrappedIteratorT, PredicateT,
401 typename detail::fwd_or_bidi_tag<WrappedIteratorT>::type>;
402
403/// Convenience function that takes a range of elements and a predicate,
404/// and return a new filter_iterator range.
405///
406/// FIXME: Currently if RangeT && is a rvalue reference to a temporary, the
407/// lifetime of that temporary is not kept by the returned range object, and the
408/// temporary is going to be dropped on the floor after the make_iterator_range
409/// full expression that contains this function call.
410template <typename RangeT, typename PredicateT>
411iterator_range<filter_iterator<detail::IterOfRange<RangeT>, PredicateT>>
412make_filter_range(RangeT &&Range, PredicateT Pred) {
413 using FilterIteratorT =
414 filter_iterator<detail::IterOfRange<RangeT>, PredicateT>;
415 return make_range(
416 FilterIteratorT(std::begin(std::forward<RangeT>(Range)),
417 std::end(std::forward<RangeT>(Range)), Pred),
418 FilterIteratorT(std::end(std::forward<RangeT>(Range)),
419 std::end(std::forward<RangeT>(Range)), Pred));
420}
421
422/// A pseudo-iterator adaptor that is designed to implement "early increment"
423/// style loops.
424///
425/// This is *not a normal iterator* and should almost never be used directly. It
426/// is intended primarily to be used with range based for loops and some range
427/// algorithms.
428///
429/// The iterator isn't quite an `OutputIterator` or an `InputIterator` but
430/// somewhere between them. The constraints of these iterators are:
431///
432/// - On construction or after being incremented, it is comparable and
433/// dereferencable. It is *not* incrementable.
434/// - After being dereferenced, it is neither comparable nor dereferencable, it
435/// is only incrementable.
436///
437/// This means you can only dereference the iterator once, and you can only
438/// increment it once between dereferences.
439template <typename WrappedIteratorT>
440class early_inc_iterator_impl
441 : public iterator_adaptor_base<early_inc_iterator_impl<WrappedIteratorT>,
442 WrappedIteratorT, std::input_iterator_tag> {
443 using BaseT =
444 iterator_adaptor_base<early_inc_iterator_impl<WrappedIteratorT>,
445 WrappedIteratorT, std::input_iterator_tag>;
446
447 using PointerT = typename std::iterator_traits<WrappedIteratorT>::pointer;
448
449protected:
450#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
451 bool IsEarlyIncremented = false;
452#endif
453
454public:
455 early_inc_iterator_impl(WrappedIteratorT I) : BaseT(I) {}
456
457 using BaseT::operator*;
458 typename BaseT::reference operator*() {
459#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
460 assert(!IsEarlyIncremented && "Cannot dereference twice!")((!IsEarlyIncremented && "Cannot dereference twice!")
? static_cast<void> (0) : __assert_fail ("!IsEarlyIncremented && \"Cannot dereference twice!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/ADT/STLExtras.h"
, 460, __PRETTY_FUNCTION__))
;
461 IsEarlyIncremented = true;
462#endif
463 return *(this->I)++;
464 }
465
466 using BaseT::operator++;
467 early_inc_iterator_impl &operator++() {
468#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
469 assert(IsEarlyIncremented && "Cannot increment before dereferencing!")((IsEarlyIncremented && "Cannot increment before dereferencing!"
) ? static_cast<void> (0) : __assert_fail ("IsEarlyIncremented && \"Cannot increment before dereferencing!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/ADT/STLExtras.h"
, 469, __PRETTY_FUNCTION__))
;
470 IsEarlyIncremented = false;
471#endif
472 return *this;
473 }
474
475 using BaseT::operator==;
476 bool operator==(const early_inc_iterator_impl &RHS) const {
477#if LLVM_ENABLE_ABI_BREAKING_CHECKS1
478 assert(!IsEarlyIncremented && "Cannot compare after dereferencing!")((!IsEarlyIncremented && "Cannot compare after dereferencing!"
) ? static_cast<void> (0) : __assert_fail ("!IsEarlyIncremented && \"Cannot compare after dereferencing!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/ADT/STLExtras.h"
, 478, __PRETTY_FUNCTION__))
;
479#endif
480 return BaseT::operator==(RHS);
481 }
482};
483
484/// Make a range that does early increment to allow mutation of the underlying
485/// range without disrupting iteration.
486///
487/// The underlying iterator will be incremented immediately after it is
488/// dereferenced, allowing deletion of the current node or insertion of nodes to
489/// not disrupt iteration provided they do not invalidate the *next* iterator --
490/// the current iterator can be invalidated.
491///
492/// This requires a very exact pattern of use that is only really suitable to
493/// range based for loops and other range algorithms that explicitly guarantee
494/// to dereference exactly once each element, and to increment exactly once each
495/// element.
496template <typename RangeT>
497iterator_range<early_inc_iterator_impl<detail::IterOfRange<RangeT>>>
498make_early_inc_range(RangeT &&Range) {
499 using EarlyIncIteratorT =
500 early_inc_iterator_impl<detail::IterOfRange<RangeT>>;
501 return make_range(EarlyIncIteratorT(std::begin(std::forward<RangeT>(Range))),
502 EarlyIncIteratorT(std::end(std::forward<RangeT>(Range))));
503}
504
505// forward declarations required by zip_shortest/zip_first
506template <typename R, typename UnaryPredicate>
507bool all_of(R &&range, UnaryPredicate P);
508
509template <size_t... I> struct index_sequence;
510
511template <class... Ts> struct index_sequence_for;
512
513namespace detail {
514
515using std::declval;
516
517// We have to alias this since inlining the actual type at the usage site
518// in the parameter list of iterator_facade_base<> below ICEs MSVC 2017.
519template<typename... Iters> struct ZipTupleType {
520 using type = std::tuple<decltype(*declval<Iters>())...>;
521};
522
523template <typename ZipType, typename... Iters>
524using zip_traits = iterator_facade_base<
525 ZipType, typename std::common_type<std::bidirectional_iterator_tag,
526 typename std::iterator_traits<
527 Iters>::iterator_category...>::type,
528 // ^ TODO: Implement random access methods.
529 typename ZipTupleType<Iters...>::type,
530 typename std::iterator_traits<typename std::tuple_element<
531 0, std::tuple<Iters...>>::type>::difference_type,
532 // ^ FIXME: This follows boost::make_zip_iterator's assumption that all
533 // inner iterators have the same difference_type. It would fail if, for
534 // instance, the second field's difference_type were non-numeric while the
535 // first is.
536 typename ZipTupleType<Iters...>::type *,
537 typename ZipTupleType<Iters...>::type>;
538
539template <typename ZipType, typename... Iters>
540struct zip_common : public zip_traits<ZipType, Iters...> {
541 using Base = zip_traits<ZipType, Iters...>;
542 using value_type = typename Base::value_type;
543
544 std::tuple<Iters...> iterators;
545
546protected:
547 template <size_t... Ns> value_type deref(index_sequence<Ns...>) const {
548 return value_type(*std::get<Ns>(iterators)...);
549 }
550
551 template <size_t... Ns>
552 decltype(iterators) tup_inc(index_sequence<Ns...>) const {
553 return std::tuple<Iters...>(std::next(std::get<Ns>(iterators))...);
554 }
555
556 template <size_t... Ns>
557 decltype(iterators) tup_dec(index_sequence<Ns...>) const {
558 return std::tuple<Iters...>(std::prev(std::get<Ns>(iterators))...);
559 }
560
561public:
562 zip_common(Iters &&... ts) : iterators(std::forward<Iters>(ts)...) {}
563
564 value_type operator*() { return deref(index_sequence_for<Iters...>{}); }
565
566 const value_type operator*() const {
567 return deref(index_sequence_for<Iters...>{});
568 }
569
570 ZipType &operator++() {
571 iterators = tup_inc(index_sequence_for<Iters...>{});
572 return *reinterpret_cast<ZipType *>(this);
573 }
574
575 ZipType &operator--() {
576 static_assert(Base::IsBidirectional,
577 "All inner iterators must be at least bidirectional.");
578 iterators = tup_dec(index_sequence_for<Iters...>{});
579 return *reinterpret_cast<ZipType *>(this);
580 }
581};
582
583template <typename... Iters>
584struct zip_first : public zip_common<zip_first<Iters...>, Iters...> {
585 using Base = zip_common<zip_first<Iters...>, Iters...>;
586
587 bool operator==(const zip_first<Iters...> &other) const {
588 return std::get<0>(this->iterators) == std::get<0>(other.iterators);
589 }
590
591 zip_first(Iters &&... ts) : Base(std::forward<Iters>(ts)...) {}
592};
593
594template <typename... Iters>
595class zip_shortest : public zip_common<zip_shortest<Iters...>, Iters...> {
596 template <size_t... Ns>
597 bool test(const zip_shortest<Iters...> &other, index_sequence<Ns...>) const {
598 return all_of(std::initializer_list<bool>{std::get<Ns>(this->iterators) !=
599 std::get<Ns>(other.iterators)...},
600 identity<bool>{});
601 }
602
603public:
604 using Base = zip_common<zip_shortest<Iters...>, Iters...>;
605
606 zip_shortest(Iters &&... ts) : Base(std::forward<Iters>(ts)...) {}
607
608 bool operator==(const zip_shortest<Iters...> &other) const {
609 return !test(other, index_sequence_for<Iters...>{});
610 }
611};
612
613template <template <typename...> class ItType, typename... Args> class zippy {
614public:
615 using iterator = ItType<decltype(std::begin(std::declval<Args>()))...>;
616 using iterator_category = typename iterator::iterator_category;
617 using value_type = typename iterator::value_type;
618 using difference_type = typename iterator::difference_type;
619 using pointer = typename iterator::pointer;
620 using reference = typename iterator::reference;
621
622private:
623 std::tuple<Args...> ts;
624
625 template <size_t... Ns> iterator begin_impl(index_sequence<Ns...>) const {
626 return iterator(std::begin(std::get<Ns>(ts))...);
627 }
628 template <size_t... Ns> iterator end_impl(index_sequence<Ns...>) const {
629 return iterator(std::end(std::get<Ns>(ts))...);
630 }
631
632public:
633 zippy(Args &&... ts_) : ts(std::forward<Args>(ts_)...) {}
634
635 iterator begin() const { return begin_impl(index_sequence_for<Args...>{}); }
636 iterator end() const { return end_impl(index_sequence_for<Args...>{}); }
637};
638
639} // end namespace detail
640
641/// zip iterator for two or more iteratable types.
642template <typename T, typename U, typename... Args>
643detail::zippy<detail::zip_shortest, T, U, Args...> zip(T &&t, U &&u,
644 Args &&... args) {
645 return detail::zippy<detail::zip_shortest, T, U, Args...>(
646 std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...);
647}
648
649/// zip iterator that, for the sake of efficiency, assumes the first iteratee to
650/// be the shortest.
651template <typename T, typename U, typename... Args>
652detail::zippy<detail::zip_first, T, U, Args...> zip_first(T &&t, U &&u,
653 Args &&... args) {
654 return detail::zippy<detail::zip_first, T, U, Args...>(
655 std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...);
656}
657
658/// Iterator wrapper that concatenates sequences together.
659///
660/// This can concatenate different iterators, even with different types, into
661/// a single iterator provided the value types of all the concatenated
662/// iterators expose `reference` and `pointer` types that can be converted to
663/// `ValueT &` and `ValueT *` respectively. It doesn't support more
664/// interesting/customized pointer or reference types.
665///
666/// Currently this only supports forward or higher iterator categories as
667/// inputs and always exposes a forward iterator interface.
668template <typename ValueT, typename... IterTs>
669class concat_iterator
670 : public iterator_facade_base<concat_iterator<ValueT, IterTs...>,
671 std::forward_iterator_tag, ValueT> {
672 using BaseT = typename concat_iterator::iterator_facade_base;
673
674 /// We store both the current and end iterators for each concatenated
675 /// sequence in a tuple of pairs.
676 ///
677 /// Note that something like iterator_range seems nice at first here, but the
678 /// range properties are of little benefit and end up getting in the way
679 /// because we need to do mutation on the current iterators.
680 std::tuple<IterTs...> Begins;
681 std::tuple<IterTs...> Ends;
682
683 /// Attempts to increment a specific iterator.
684 ///
685 /// Returns true if it was able to increment the iterator. Returns false if
686 /// the iterator is already at the end iterator.
687 template <size_t Index> bool incrementHelper() {
688 auto &Begin = std::get<Index>(Begins);
689 auto &End = std::get<Index>(Ends);
690 if (Begin == End)
691 return false;
692
693 ++Begin;
694 return true;
695 }
696
697 /// Increments the first non-end iterator.
698 ///
699 /// It is an error to call this with all iterators at the end.
700 template <size_t... Ns> void increment(index_sequence<Ns...>) {
701 // Build a sequence of functions to increment each iterator if possible.
702 bool (concat_iterator::*IncrementHelperFns[])() = {
703 &concat_iterator::incrementHelper<Ns>...};
704
705 // Loop over them, and stop as soon as we succeed at incrementing one.
706 for (auto &IncrementHelperFn : IncrementHelperFns)
707 if ((this->*IncrementHelperFn)())
708 return;
709
710 llvm_unreachable("Attempted to increment an end concat iterator!")::llvm::llvm_unreachable_internal("Attempted to increment an end concat iterator!"
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/ADT/STLExtras.h"
, 710)
;
711 }
712
713 /// Returns null if the specified iterator is at the end. Otherwise,
714 /// dereferences the iterator and returns the address of the resulting
715 /// reference.
716 template <size_t Index> ValueT *getHelper() const {
717 auto &Begin = std::get<Index>(Begins);
718 auto &End = std::get<Index>(Ends);
719 if (Begin == End)
720 return nullptr;
721
722 return &*Begin;
723 }
724
725 /// Finds the first non-end iterator, dereferences, and returns the resulting
726 /// reference.
727 ///
728 /// It is an error to call this with all iterators at the end.
729 template <size_t... Ns> ValueT &get(index_sequence<Ns...>) const {
730 // Build a sequence of functions to get from iterator if possible.
731 ValueT *(concat_iterator::*GetHelperFns[])() const = {
732 &concat_iterator::getHelper<Ns>...};
733
734 // Loop over them, and return the first result we find.
735 for (auto &GetHelperFn : GetHelperFns)
736 if (ValueT *P = (this->*GetHelperFn)())
737 return *P;
738
739 llvm_unreachable("Attempted to get a pointer from an end concat iterator!")::llvm::llvm_unreachable_internal("Attempted to get a pointer from an end concat iterator!"
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/ADT/STLExtras.h"
, 739)
;
740 }
741
742public:
743 /// Constructs an iterator from a squence of ranges.
744 ///
745 /// We need the full range to know how to switch between each of the
746 /// iterators.
747 template <typename... RangeTs>
748 explicit concat_iterator(RangeTs &&... Ranges)
749 : Begins(std::begin(Ranges)...), Ends(std::end(Ranges)...) {}
750
751 using BaseT::operator++;
752
753 concat_iterator &operator++() {
754 increment(index_sequence_for<IterTs...>());
755 return *this;
756 }
757
758 ValueT &operator*() const { return get(index_sequence_for<IterTs...>()); }
759
760 bool operator==(const concat_iterator &RHS) const {
761 return Begins == RHS.Begins && Ends == RHS.Ends;
762 }
763};
764
765namespace detail {
766
767/// Helper to store a sequence of ranges being concatenated and access them.
768///
769/// This is designed to facilitate providing actual storage when temporaries
770/// are passed into the constructor such that we can use it as part of range
771/// based for loops.
772template <typename ValueT, typename... RangeTs> class concat_range {
773public:
774 using iterator =
775 concat_iterator<ValueT,
776 decltype(std::begin(std::declval<RangeTs &>()))...>;
777
778private:
779 std::tuple<RangeTs...> Ranges;
780
781 template <size_t... Ns> iterator begin_impl(index_sequence<Ns...>) {
782 return iterator(std::get<Ns>(Ranges)...);
783 }
784 template <size_t... Ns> iterator end_impl(index_sequence<Ns...>) {
785 return iterator(make_range(std::end(std::get<Ns>(Ranges)),
786 std::end(std::get<Ns>(Ranges)))...);
787 }
788
789public:
790 concat_range(RangeTs &&... Ranges)
791 : Ranges(std::forward<RangeTs>(Ranges)...) {}
792
793 iterator begin() { return begin_impl(index_sequence_for<RangeTs...>{}); }
794 iterator end() { return end_impl(index_sequence_for<RangeTs...>{}); }
795};
796
797} // end namespace detail
798
799/// Concatenated range across two or more ranges.
800///
801/// The desired value type must be explicitly specified.
802template <typename ValueT, typename... RangeTs>
803detail::concat_range<ValueT, RangeTs...> concat(RangeTs &&... Ranges) {
804 static_assert(sizeof...(RangeTs) > 1,
805 "Need more than one range to concatenate!");
806 return detail::concat_range<ValueT, RangeTs...>(
807 std::forward<RangeTs>(Ranges)...);
808}
809
810//===----------------------------------------------------------------------===//
811// Extra additions to <utility>
812//===----------------------------------------------------------------------===//
813
814/// Function object to check whether the first component of a std::pair
815/// compares less than the first component of another std::pair.
816struct less_first {
817 template <typename T> bool operator()(const T &lhs, const T &rhs) const {
818 return lhs.first < rhs.first;
819 }
820};
821
822/// Function object to check whether the second component of a std::pair
823/// compares less than the second component of another std::pair.
824struct less_second {
825 template <typename T> bool operator()(const T &lhs, const T &rhs) const {
826 return lhs.second < rhs.second;
827 }
828};
829
830/// \brief Function object to apply a binary function to the first component of
831/// a std::pair.
832template<typename FuncTy>
833struct on_first {
834 FuncTy func;
835
836 template <typename T>
837 auto operator()(const T &lhs, const T &rhs) const
838 -> decltype(func(lhs.first, rhs.first)) {
839 return func(lhs.first, rhs.first);
840 }
841};
842
843// A subset of N3658. More stuff can be added as-needed.
844
845/// Represents a compile-time sequence of integers.
846template <class T, T... I> struct integer_sequence {
847 using value_type = T;
848
849 static constexpr size_t size() { return sizeof...(I); }
850};
851
852/// Alias for the common case of a sequence of size_ts.
853template <size_t... I>
854struct index_sequence : integer_sequence<std::size_t, I...> {};
855
856template <std::size_t N, std::size_t... I>
857struct build_index_impl : build_index_impl<N - 1, N - 1, I...> {};
858template <std::size_t... I>
859struct build_index_impl<0, I...> : index_sequence<I...> {};
860
861/// Creates a compile-time integer sequence for a parameter pack.
862template <class... Ts>
863struct index_sequence_for : build_index_impl<sizeof...(Ts)> {};
864
865/// Utility type to build an inheritance chain that makes it easy to rank
866/// overload candidates.
867template <int N> struct rank : rank<N - 1> {};
868template <> struct rank<0> {};
869
870/// traits class for checking whether type T is one of any of the given
871/// types in the variadic list.
872template <typename T, typename... Ts> struct is_one_of {
873 static const bool value = false;
874};
875
876template <typename T, typename U, typename... Ts>
877struct is_one_of<T, U, Ts...> {
878 static const bool value =
879 std::is_same<T, U>::value || is_one_of<T, Ts...>::value;
880};
881
882/// traits class for checking whether type T is a base class for all
883/// the given types in the variadic list.
884template <typename T, typename... Ts> struct are_base_of {
885 static const bool value = true;
886};
887
888template <typename T, typename U, typename... Ts>
889struct are_base_of<T, U, Ts...> {
890 static const bool value =
891 std::is_base_of<T, U>::value && are_base_of<T, Ts...>::value;
892};
893
894//===----------------------------------------------------------------------===//
895// Extra additions for arrays
896//===----------------------------------------------------------------------===//
897
898/// Find the length of an array.
899template <class T, std::size_t N>
900constexpr inline size_t array_lengthof(T (&)[N]) {
901 return N;
902}
903
904/// Adapt std::less<T> for array_pod_sort.
905template<typename T>
906inline int array_pod_sort_comparator(const void *P1, const void *P2) {
907 if (std::less<T>()(*reinterpret_cast<const T*>(P1),
908 *reinterpret_cast<const T*>(P2)))
909 return -1;
910 if (std::less<T>()(*reinterpret_cast<const T*>(P2),
911 *reinterpret_cast<const T*>(P1)))
912 return 1;
913 return 0;
914}
915
916/// get_array_pod_sort_comparator - This is an internal helper function used to
917/// get type deduction of T right.
918template<typename T>
919inline int (*get_array_pod_sort_comparator(const T &))
920 (const void*, const void*) {
921 return array_pod_sort_comparator<T>;
922}
923
924/// array_pod_sort - This sorts an array with the specified start and end
925/// extent. This is just like std::sort, except that it calls qsort instead of
926/// using an inlined template. qsort is slightly slower than std::sort, but
927/// most sorts are not performance critical in LLVM and std::sort has to be
928/// template instantiated for each type, leading to significant measured code
929/// bloat. This function should generally be used instead of std::sort where
930/// possible.
931///
932/// This function assumes that you have simple POD-like types that can be
933/// compared with std::less and can be moved with memcpy. If this isn't true,
934/// you should use std::sort.
935///
936/// NOTE: If qsort_r were portable, we could allow a custom comparator and
937/// default to std::less.
938template<class IteratorTy>
939inline void array_pod_sort(IteratorTy Start, IteratorTy End) {
940 // Don't inefficiently call qsort with one element or trigger undefined
941 // behavior with an empty sequence.
942 auto NElts = End - Start;
943 if (NElts <= 1) return;
944#ifdef EXPENSIVE_CHECKS
945 std::mt19937 Generator(std::random_device{}());
946 std::shuffle(Start, End, Generator);
947#endif
948 qsort(&*Start, NElts, sizeof(*Start), get_array_pod_sort_comparator(*Start));
949}
950
951template <class IteratorTy>
952inline void array_pod_sort(
953 IteratorTy Start, IteratorTy End,
954 int (*Compare)(
955 const typename std::iterator_traits<IteratorTy>::value_type *,
956 const typename std::iterator_traits<IteratorTy>::value_type *)) {
957 // Don't inefficiently call qsort with one element or trigger undefined
958 // behavior with an empty sequence.
959 auto NElts = End - Start;
960 if (NElts <= 1) return;
961#ifdef EXPENSIVE_CHECKS
962 std::mt19937 Generator(std::random_device{}());
963 std::shuffle(Start, End, Generator);
964#endif
965 qsort(&*Start, NElts, sizeof(*Start),
966 reinterpret_cast<int (*)(const void *, const void *)>(Compare));
967}
968
969// Provide wrappers to std::sort which shuffle the elements before sorting
970// to help uncover non-deterministic behavior (PR35135).
971template <typename IteratorTy>
972inline void sort(IteratorTy Start, IteratorTy End) {
973#ifdef EXPENSIVE_CHECKS
974 std::mt19937 Generator(std::random_device{}());
975 std::shuffle(Start, End, Generator);
976#endif
977 std::sort(Start, End);
978}
979
980template <typename Container> inline void sort(Container &&C) {
981 llvm::sort(adl_begin(C), adl_end(C));
982}
983
984template <typename IteratorTy, typename Compare>
985inline void sort(IteratorTy Start, IteratorTy End, Compare Comp) {
986#ifdef EXPENSIVE_CHECKS
987 std::mt19937 Generator(std::random_device{}());
988 std::shuffle(Start, End, Generator);
989#endif
990 std::sort(Start, End, Comp);
991}
992
993template <typename Container, typename Compare>
994inline void sort(Container &&C, Compare Comp) {
995 llvm::sort(adl_begin(C), adl_end(C), Comp);
996}
997
998//===----------------------------------------------------------------------===//
999// Extra additions to <algorithm>
1000//===----------------------------------------------------------------------===//
1001
1002/// For a container of pointers, deletes the pointers and then clears the
1003/// container.
1004template<typename Container>
1005void DeleteContainerPointers(Container &C) {
1006 for (auto V : C)
1007 delete V;
1008 C.clear();
1009}
1010
1011/// In a container of pairs (usually a map) whose second element is a pointer,
1012/// deletes the second elements and then clears the container.
1013template<typename Container>
1014void DeleteContainerSeconds(Container &C) {
1015 for (auto &V : C)
1016 delete V.second;
1017 C.clear();
1018}
1019
1020/// Get the size of a range. This is a wrapper function around std::distance
1021/// which is only enabled when the operation is O(1).
1022template <typename R>
1023auto size(R &&Range, typename std::enable_if<
1024 std::is_same<typename std::iterator_traits<decltype(
1025 Range.begin())>::iterator_category,
1026 std::random_access_iterator_tag>::value,
1027 void>::type * = nullptr)
1028 -> decltype(std::distance(Range.begin(), Range.end())) {
1029 return std::distance(Range.begin(), Range.end());
1030}
1031
1032/// Provide wrappers to std::for_each which take ranges instead of having to
1033/// pass begin/end explicitly.
1034template <typename R, typename UnaryPredicate>
1035UnaryPredicate for_each(R &&Range, UnaryPredicate P) {
1036 return std::for_each(adl_begin(Range), adl_end(Range), P);
1037}
1038
1039/// Provide wrappers to std::all_of which take ranges instead of having to pass
1040/// begin/end explicitly.
1041template <typename R, typename UnaryPredicate>
1042bool all_of(R &&Range, UnaryPredicate P) {
1043 return std::all_of(adl_begin(Range), adl_end(Range), P);
1044}
1045
1046/// Provide wrappers to std::any_of which take ranges instead of having to pass
1047/// begin/end explicitly.
1048template <typename R, typename UnaryPredicate>
1049bool any_of(R &&Range, UnaryPredicate P) {
1050 return std::any_of(adl_begin(Range), adl_end(Range), P);
1051}
1052
1053/// Provide wrappers to std::none_of which take ranges instead of having to pass
1054/// begin/end explicitly.
1055template <typename R, typename UnaryPredicate>
1056bool none_of(R &&Range, UnaryPredicate P) {
1057 return std::none_of(adl_begin(Range), adl_end(Range), P);
1058}
1059
1060/// Provide wrappers to std::find which take ranges instead of having to pass
1061/// begin/end explicitly.
1062template <typename R, typename T>
1063auto find(R &&Range, const T &Val) -> decltype(adl_begin(Range)) {
1064 return std::find(adl_begin(Range), adl_end(Range), Val);
1065}
1066
1067/// Provide wrappers to std::find_if which take ranges instead of having to pass
1068/// begin/end explicitly.
1069template <typename R, typename UnaryPredicate>
1070auto find_if(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range)) {
1071 return std::find_if(adl_begin(Range), adl_end(Range), P);
1072}
1073
1074template <typename R, typename UnaryPredicate>
1075auto find_if_not(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range)) {
1076 return std::find_if_not(adl_begin(Range), adl_end(Range), P);
1077}
1078
1079/// Provide wrappers to std::remove_if which take ranges instead of having to
1080/// pass begin/end explicitly.
1081template <typename R, typename UnaryPredicate>
1082auto remove_if(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range)) {
1083 return std::remove_if(adl_begin(Range), adl_end(Range), P);
1084}
1085
1086/// Provide wrappers to std::copy_if which take ranges instead of having to
1087/// pass begin/end explicitly.
1088template <typename R, typename OutputIt, typename UnaryPredicate>
1089OutputIt copy_if(R &&Range, OutputIt Out, UnaryPredicate P) {
1090 return std::copy_if(adl_begin(Range), adl_end(Range), Out, P);
1091}
1092
1093template <typename R, typename OutputIt>
1094OutputIt copy(R &&Range, OutputIt Out) {
1095 return std::copy(adl_begin(Range), adl_end(Range), Out);
1096}
1097
1098/// Wrapper function around std::find to detect if an element exists
1099/// in a container.
1100template <typename R, typename E>
1101bool is_contained(R &&Range, const E &Element) {
1102 return std::find(adl_begin(Range), adl_end(Range), Element) != adl_end(Range);
1103}
1104
1105/// Wrapper function around std::count to count the number of times an element
1106/// \p Element occurs in the given range \p Range.
1107template <typename R, typename E>
1108auto count(R &&Range, const E &Element) ->
1109 typename std::iterator_traits<decltype(adl_begin(Range))>::difference_type {
1110 return std::count(adl_begin(Range), adl_end(Range), Element);
1111}
1112
1113/// Wrapper function around std::count_if to count the number of times an
1114/// element satisfying a given predicate occurs in a range.
1115template <typename R, typename UnaryPredicate>
1116auto count_if(R &&Range, UnaryPredicate P) ->
1117 typename std::iterator_traits<decltype(adl_begin(Range))>::difference_type {
1118 return std::count_if(adl_begin(Range), adl_end(Range), P);
1119}
1120
1121/// Wrapper function around std::transform to apply a function to a range and
1122/// store the result elsewhere.
1123template <typename R, typename OutputIt, typename UnaryPredicate>
1124OutputIt transform(R &&Range, OutputIt d_first, UnaryPredicate P) {
1125 return std::transform(adl_begin(Range), adl_end(Range), d_first, P);
1126}
1127
1128/// Provide wrappers to std::partition which take ranges instead of having to
1129/// pass begin/end explicitly.
1130template <typename R, typename UnaryPredicate>
1131auto partition(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range)) {
1132 return std::partition(adl_begin(Range), adl_end(Range), P);
1133}
1134
1135/// Provide wrappers to std::lower_bound which take ranges instead of having to
1136/// pass begin/end explicitly.
1137template <typename R, typename ForwardIt>
1138auto lower_bound(R &&Range, ForwardIt I) -> decltype(adl_begin(Range)) {
1139 return std::lower_bound(adl_begin(Range), adl_end(Range), I);
1140}
1141
1142template <typename R, typename ForwardIt, typename Compare>
1143auto lower_bound(R &&Range, ForwardIt I, Compare C)
1144 -> decltype(adl_begin(Range)) {
1145 return std::lower_bound(adl_begin(Range), adl_end(Range), I, C);
1146}
1147
1148/// Provide wrappers to std::upper_bound which take ranges instead of having to
1149/// pass begin/end explicitly.
1150template <typename R, typename ForwardIt>
1151auto upper_bound(R &&Range, ForwardIt I) -> decltype(adl_begin(Range)) {
1152 return std::upper_bound(adl_begin(Range), adl_end(Range), I);
1153}
1154
1155template <typename R, typename ForwardIt, typename Compare>
1156auto upper_bound(R &&Range, ForwardIt I, Compare C)
1157 -> decltype(adl_begin(Range)) {
1158 return std::upper_bound(adl_begin(Range), adl_end(Range), I, C);
1159}
1160/// Wrapper function around std::equal to detect if all elements
1161/// in a container are same.
1162template <typename R>
1163bool is_splat(R &&Range) {
1164 size_t range_size = size(Range);
1165 return range_size != 0 && (range_size == 1 ||
1166 std::equal(adl_begin(Range) + 1, adl_end(Range), adl_begin(Range)));
1167}
1168
1169/// Given a range of type R, iterate the entire range and return a
1170/// SmallVector with elements of the vector. This is useful, for example,
1171/// when you want to iterate a range and then sort the results.
1172template <unsigned Size, typename R>
1173SmallVector<typename std::remove_const<detail::ValueOfRange<R>>::type, Size>
1174to_vector(R &&Range) {
1175 return {adl_begin(Range), adl_end(Range)};
1176}
1177
1178/// Provide a container algorithm similar to C++ Library Fundamentals v2's
1179/// `erase_if` which is equivalent to:
1180///
1181/// C.erase(remove_if(C, pred), C.end());
1182///
1183/// This version works for any container with an erase method call accepting
1184/// two iterators.
1185template <typename Container, typename UnaryPredicate>
1186void erase_if(Container &C, UnaryPredicate P) {
1187 C.erase(remove_if(C, P), C.end());
1188}
1189
1190//===----------------------------------------------------------------------===//
1191// Extra additions to <memory>
1192//===----------------------------------------------------------------------===//
1193
1194// Implement make_unique according to N3656.
1195
1196/// Constructs a `new T()` with the given args and returns a
1197/// `unique_ptr<T>` which owns the object.
1198///
1199/// Example:
1200///
1201/// auto p = make_unique<int>();
1202/// auto p = make_unique<std::tuple<int, int>>(0, 1);
1203template <class T, class... Args>
1204typename std::enable_if<!std::is_array<T>::value, std::unique_ptr<T>>::type
1205make_unique(Args &&... args) {
1206 return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
13
Memory is allocated
1207}
1208
1209/// Constructs a `new T[n]` with the given args and returns a
1210/// `unique_ptr<T[]>` which owns the object.
1211///
1212/// \param n size of the new array.
1213///
1214/// Example:
1215///
1216/// auto p = make_unique<int[]>(2); // value-initializes the array with 0's.
1217template <class T>
1218typename std::enable_if<std::is_array<T>::value && std::extent<T>::value == 0,
1219 std::unique_ptr<T>>::type
1220make_unique(size_t n) {
1221 return std::unique_ptr<T>(new typename std::remove_extent<T>::type[n]());
1222}
1223
1224/// This function isn't used and is only here to provide better compile errors.
1225template <class T, class... Args>
1226typename std::enable_if<std::extent<T>::value != 0>::type
1227make_unique(Args &&...) = delete;
1228
1229struct FreeDeleter {
1230 void operator()(void* v) {
1231 ::free(v);
1232 }
1233};
1234
1235template<typename First, typename Second>
1236struct pair_hash {
1237 size_t operator()(const std::pair<First, Second> &P) const {
1238 return std::hash<First>()(P.first) * 31 + std::hash<Second>()(P.second);
1239 }
1240};
1241
1242/// A functor like C++14's std::less<void> in its absence.
1243struct less {
1244 template <typename A, typename B> bool operator()(A &&a, B &&b) const {
1245 return std::forward<A>(a) < std::forward<B>(b);
1246 }
1247};
1248
1249/// A functor like C++14's std::equal<void> in its absence.
1250struct equal {
1251 template <typename A, typename B> bool operator()(A &&a, B &&b) const {
1252 return std::forward<A>(a) == std::forward<B>(b);
1253 }
1254};
1255
1256/// Binary functor that adapts to any other binary functor after dereferencing
1257/// operands.
1258template <typename T> struct deref {
1259 T func;
1260
1261 // Could be further improved to cope with non-derivable functors and
1262 // non-binary functors (should be a variadic template member function
1263 // operator()).
1264 template <typename A, typename B>
1265 auto operator()(A &lhs, B &rhs) const -> decltype(func(*lhs, *rhs)) {
1266 assert(lhs)((lhs) ? static_cast<void> (0) : __assert_fail ("lhs", "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/ADT/STLExtras.h"
, 1266, __PRETTY_FUNCTION__))
;
1267 assert(rhs)((rhs) ? static_cast<void> (0) : __assert_fail ("rhs", "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/ADT/STLExtras.h"
, 1267, __PRETTY_FUNCTION__))
;
1268 return func(*lhs, *rhs);
1269 }
1270};
1271
1272namespace detail {
1273
1274template <typename R> class enumerator_iter;
1275
1276template <typename R> struct result_pair {
1277 friend class enumerator_iter<R>;
1278
1279 result_pair() = default;
1280 result_pair(std::size_t Index, IterOfRange<R> Iter)
1281 : Index(Index), Iter(Iter) {}
1282
1283 result_pair<R> &operator=(const result_pair<R> &Other) {
1284 Index = Other.Index;
1285 Iter = Other.Iter;
1286 return *this;
1287 }
1288
1289 std::size_t index() const { return Index; }
1290 const ValueOfRange<R> &value() const { return *Iter; }
1291 ValueOfRange<R> &value() { return *Iter; }
1292
1293private:
1294 std::size_t Index = std::numeric_limits<std::size_t>::max();
1295 IterOfRange<R> Iter;
1296};
1297
1298template <typename R>
1299class enumerator_iter
1300 : public iterator_facade_base<
1301 enumerator_iter<R>, std::forward_iterator_tag, result_pair<R>,
1302 typename std::iterator_traits<IterOfRange<R>>::difference_type,
1303 typename std::iterator_traits<IterOfRange<R>>::pointer,
1304 typename std::iterator_traits<IterOfRange<R>>::reference> {
1305 using result_type = result_pair<R>;
1306
1307public:
1308 explicit enumerator_iter(IterOfRange<R> EndIter)
1309 : Result(std::numeric_limits<size_t>::max(), EndIter) {}
1310
1311 enumerator_iter(std::size_t Index, IterOfRange<R> Iter)
1312 : Result(Index, Iter) {}
1313
1314 result_type &operator*() { return Result; }
1315 const result_type &operator*() const { return Result; }
1316
1317 enumerator_iter<R> &operator++() {
1318 assert(Result.Index != std::numeric_limits<size_t>::max())((Result.Index != std::numeric_limits<size_t>::max()) ?
static_cast<void> (0) : __assert_fail ("Result.Index != std::numeric_limits<size_t>::max()"
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/ADT/STLExtras.h"
, 1318, __PRETTY_FUNCTION__))
;
1319 ++Result.Iter;
1320 ++Result.Index;
1321 return *this;
1322 }
1323
1324 bool operator==(const enumerator_iter<R> &RHS) const {
1325 // Don't compare indices here, only iterators. It's possible for an end
1326 // iterator to have different indices depending on whether it was created
1327 // by calling std::end() versus incrementing a valid iterator.
1328 return Result.Iter == RHS.Result.Iter;
1329 }
1330
1331 enumerator_iter<R> &operator=(const enumerator_iter<R> &Other) {
1332 Result = Other.Result;
1333 return *this;
1334 }
1335
1336private:
1337 result_type Result;
1338};
1339
1340template <typename R> class enumerator {
1341public:
1342 explicit enumerator(R &&Range) : TheRange(std::forward<R>(Range)) {}
1343
1344 enumerator_iter<R> begin() {
1345 return enumerator_iter<R>(0, std::begin(TheRange));
1346 }
1347
1348 enumerator_iter<R> end() {
1349 return enumerator_iter<R>(std::end(TheRange));
1350 }
1351
1352private:
1353 R TheRange;
1354};
1355
1356} // end namespace detail
1357
1358/// Given an input range, returns a new range whose values are are pair (A,B)
1359/// such that A is the 0-based index of the item in the sequence, and B is
1360/// the value from the original sequence. Example:
1361///
1362/// std::vector<char> Items = {'A', 'B', 'C', 'D'};
1363/// for (auto X : enumerate(Items)) {
1364/// printf("Item %d - %c\n", X.index(), X.value());
1365/// }
1366///
1367/// Output:
1368/// Item 0 - A
1369/// Item 1 - B
1370/// Item 2 - C
1371/// Item 3 - D
1372///
1373template <typename R> detail::enumerator<R> enumerate(R &&TheRange) {
1374 return detail::enumerator<R>(std::forward<R>(TheRange));
1375}
1376
1377namespace detail {
1378
1379template <typename F, typename Tuple, std::size_t... I>
1380auto apply_tuple_impl(F &&f, Tuple &&t, index_sequence<I...>)
1381 -> decltype(std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...)) {
1382 return std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...);
1383}
1384
1385} // end namespace detail
1386
1387/// Given an input tuple (a1, a2, ..., an), pass the arguments of the
1388/// tuple variadically to f as if by calling f(a1, a2, ..., an) and
1389/// return the result.
1390template <typename F, typename Tuple>
1391auto apply_tuple(F &&f, Tuple &&t) -> decltype(detail::apply_tuple_impl(
1392 std::forward<F>(f), std::forward<Tuple>(t),
1393 build_index_impl<
1394 std::tuple_size<typename std::decay<Tuple>::type>::value>{})) {
1395 using Indices = build_index_impl<
1396 std::tuple_size<typename std::decay<Tuple>::type>::value>;
1397
1398 return detail::apply_tuple_impl(std::forward<F>(f), std::forward<Tuple>(t),
1399 Indices{});
1400}
1401
1402} // end namespace llvm
1403
1404#endif // LLVM_ADT_STLEXTRAS_H