llvm.org GIT mirror llvm / 66f724e
[dsymutil, llvm-objcopy] Fix some Clang-tidy modernize and Include What You Use warnings; other minor fixes (NFC). git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@317123 91177308-0d34-0410-b5e6-96231b3b80d8 Eugene Zelenko 1 year, 11 months ago
10 changed file(s) with 532 addition(s) and 294 deletion(s). Raw diff Collapse all Expand all
55 // License. See LICENSE.TXT for details.
66 //
77 //===----------------------------------------------------------------------===//
8
89 #include "DebugMap.h"
910 #include "BinaryHolder.h"
10 #include "llvm/ADT/STLExtras.h"
11 #include "llvm/ADT/Optional.h"
12 #include "llvm/ADT/SmallString.h"
13 #include "llvm/ADT/StringMap.h"
14 #include "llvm/ADT/StringRef.h"
15 #include "llvm/ADT/Triple.h"
1116 #include "llvm/ADT/iterator_range.h"
12 #include "llvm/Support/DataTypes.h"
17 #include "llvm/BinaryFormat/MachO.h"
18 #include "llvm/Object/ObjectFile.h"
19 #include "llvm/Support/Chrono.h"
20 #include "llvm/Support/Error.h"
1321 #include "llvm/Support/Format.h"
22 #include "llvm/Support/MemoryBuffer.h"
23 #include "llvm/Support/Path.h"
24 #include "llvm/Support/YAMLTraits.h"
1425 #include "llvm/Support/raw_ostream.h"
1526 #include
27 #include
28 #include
29 #include
30 #include
31 #include
32 #include
1633
1734 namespace llvm {
35
1836 namespace dsymutil {
1937
2038 using namespace llvm::object;
3856 OS << getObjectFilename() << ":\n";
3957 // Sort the symbols in alphabetical order, like llvm-nm (and to get
4058 // deterministic output for testing).
41 typedef std::pair Entry;
59 using Entry = std::pair;
4260 std::vector Entries;
4361 Entries.reserve(Symbols.getNumItems());
4462 for (const auto &Sym : make_range(Symbols.begin(), Symbols.end()))
96114 #endif
97115
98116 namespace {
117
99118 struct YAMLContext {
100119 StringRef PrependPath;
101120 Triple BinaryTriple;
102121 };
103 }
122
123 } // end anonymous namespace
104124
105125 ErrorOr>>
106126 DebugMap::parseYAMLDebugMap(StringRef InputFile, StringRef PrependPath,
123143 Result.push_back(std::move(Res));
124144 return std::move(Result);
125145 }
126 }
146
147 } // end namespace dsymutil
127148
128149 namespace yaml {
129150
154175 io.mapRequired("symbols", Norm->Entries);
155176 }
156177
157 void ScalarTraits::output(const Triple &val, void *,
158 llvm::raw_ostream &out) {
178 void ScalarTraits::output(const Triple &val, void *, raw_ostream &out) {
159179 out << val.str();
160180 }
161181
220240 sys::path::append(Path, Filename);
221241 auto ErrOrObjectFiles = BinHolder.GetObjectFiles(Path);
222242 if (auto EC = ErrOrObjectFiles.getError()) {
223 llvm::errs() << "warning: Unable to open " << Path << " " << EC.message()
224 << '\n';
243 errs() << "warning: Unable to open " << Path << " " << EC.message() << '\n';
225244 } else if (auto ErrOrObjectFile = BinHolder.Get(Ctxt.BinaryTriple)) {
226245 // Rewrite the object file symbol addresses in the debug map. The
227246 // YAML input is mainly used to test llvm-dsymutil without
255274 }
256275 return Res;
257276 }
258 }
259 }
277
278 } // end namespace yaml
279
280 } // end namespace llvm
None //=== tools/dsymutil/DebugMap.h - Generic debug map representation -*- C++ -*-//
0 //=- tools/dsymutil/DebugMap.h - Generic debug map representation -*- C++ -*-=//
11 //
22 // The LLVM Linker
33 //
55 // License. See LICENSE.TXT for details.
66 //
77 //===----------------------------------------------------------------------===//
8 ///
8 //
99 /// \file
1010 ///
1111 /// This file contains the class declaration of the DebugMap
1515 /// The DebugMap is an input to the DwarfLinker class that will
1616 /// extract the Dwarf debug information from the referenced object
1717 /// files and link their usefull debug info together.
18 ///
18 //
1919 //===----------------------------------------------------------------------===//
20
2021 #ifndef LLVM_TOOLS_DSYMUTIL_DEBUGMAP_H
2122 #define LLVM_TOOLS_DSYMUTIL_DEBUGMAP_H
2223
2324 #include "llvm/ADT/DenseMap.h"
25 #include "llvm/ADT/Optional.h"
2426 #include "llvm/ADT/StringMap.h"
27 #include "llvm/ADT/StringRef.h"
2528 #include "llvm/ADT/Triple.h"
2629 #include "llvm/ADT/iterator_range.h"
27 #include "llvm/Object/ObjectFile.h"
2830 #include "llvm/Support/Chrono.h"
2931 #include "llvm/Support/ErrorOr.h"
30 #include "llvm/Support/Format.h"
31 #include "llvm/Support/Path.h"
3232 #include "llvm/Support/YAMLTraits.h"
33 #include
34 #include
35 #include
36 #include
37 #include
38 #include
3339 #include
3440
3541 namespace llvm {
42
3643 class raw_ostream;
3744
3845 namespace dsymutil {
46
3947 class DebugMapObject;
4048
4149 /// \brief The DebugMap object stores the list of object files to
6674 class DebugMap {
6775 Triple BinaryTriple;
6876 std::string BinaryPath;
69 typedef std::vector> ObjectContainer;
77
78 using ObjectContainer = std::vector>;
79
7080 ObjectContainer Objects;
7181
7282 /// For YAML IO support.
7383 ///@{
7484 friend yaml::MappingTraits>;
7585 friend yaml::MappingTraits;
86
7687 DebugMap() = default;
7788 ///@}
89
7890 public:
7991 DebugMap(const Triple &BinaryTriple, StringRef BinaryPath)
8092 : BinaryTriple(BinaryTriple), BinaryPath(BinaryPath) {}
8193
82 typedef ObjectContainer::const_iterator const_iterator;
94 using const_iterator = ObjectContainer::const_iterator;
8395
8496 iterator_range objects() const {
8597 return make_range(begin(), end());
121133 Optional ObjectAddress;
122134 yaml::Hex64 BinaryAddress;
123135 yaml::Hex32 Size;
136
124137 SymbolMapping(Optional ObjectAddr, uint64_t BinaryAddress,
125138 uint32_t Size)
126139 : BinaryAddress(BinaryAddress), Size(Size) {
127140 if (ObjectAddr)
128141 ObjectAddress = *ObjectAddr;
129142 }
143
130144 /// For YAML IO support
131145 SymbolMapping() = default;
132146 };
133147
134 typedef std::pair YAMLSymbolMapping;
135 typedef StringMapEntry DebugMapEntry;
148 using YAMLSymbolMapping = std::pair;
149 using DebugMapEntry = StringMapEntry;
136150
137151 /// \brief Adds a symbol mapping to this DebugMapObject.
138152 /// \returns false if the symbol was already registered. The request
139153 /// is discarded in this case.
140 bool addSymbol(llvm::StringRef SymName, Optional ObjectAddress,
154 bool addSymbol(StringRef SymName, Optional ObjectAddress,
141155 uint64_t LinkedAddress, uint32_t Size);
142156
143157 /// \brief Lookup a symbol mapping.
148162 /// \returns null if the address isn't found.
149163 const DebugMapEntry *lookupObjectAddress(uint64_t Address) const;
150164
151 llvm::StringRef getObjectFilename() const { return Filename; }
165 StringRef getObjectFilename() const { return Filename; }
152166
153167 sys::TimePoint getTimestamp() const {
154168 return Timestamp;
164178 #ifndef NDEBUG
165179 void dump() const;
166180 #endif
181
167182 private:
168183 friend class DebugMap;
184
169185 /// DebugMapObjects can only be constructed by the owning DebugMap.
170186 DebugMapObject(StringRef ObjectFilename,
171187 sys::TimePoint Timestamp, uint8_t Type);
180196 ///@{
181197 friend yaml::MappingTraits;
182198 friend yaml::SequenceTraits>>;
199
183200 DebugMapObject() = default;
184201
185202 public:
187204 DebugMapObject &operator=(DebugMapObject &&) = default;
188205 ///@}
189206 };
190 }
191 }
207
208 } // end namespace dsymutil
209
210 } // end namespace llvm
192211
193212 LLVM_YAML_IS_SEQUENCE_VECTOR(llvm::dsymutil::DebugMapObject::YAMLSymbolMapping)
194213
210229 };
211230
212231 template <> struct ScalarTraits {
213 static void output(const Triple &val, void *, llvm::raw_ostream &out);
232 static void output(const Triple &val, void *, raw_ostream &out);
214233 static StringRef input(StringRef scalar, void *, Triple &value);
215234 static bool mustQuote(StringRef) { return true; }
216235 };
231250 template <> struct MappingTraits> {
232251 static void mapping(IO &io, std::unique_ptr &DM);
233252 };
234 }
235 }
253
254 } // end namespace yaml
255 } // end namespace llvm
236256
237257 #endif // LLVM_TOOLS_DSYMUTIL_DEBUGMAP_H
55 // License. See LICENSE.TXT for details.
66 //
77 //===----------------------------------------------------------------------===//
8
89 #include "BinaryHolder.h"
910 #include "DebugMap.h"
1011 #include "MachOUtils.h"
1112 #include "NonRelocatableStringpool.h"
1213 #include "dsymutil.h"
14 #include "llvm/ADT/ArrayRef.h"
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/DenseMapInfo.h"
17 #include "llvm/ADT/DenseSet.h"
18 #include "llvm/ADT/FoldingSet.h"
19 #include "llvm/ADT/Hashing.h"
1320 #include "llvm/ADT/IntervalMap.h"
21 #include "llvm/ADT/None.h"
22 #include "llvm/ADT/Optional.h"
23 #include "llvm/ADT/PointerIntPair.h"
1424 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/SmallString.h"
1526 #include "llvm/ADT/StringMap.h"
27 #include "llvm/ADT/StringRef.h"
28 #include "llvm/ADT/Triple.h"
29 #include "llvm/ADT/Twine.h"
1630 #include "llvm/BinaryFormat/Dwarf.h"
31 #include "llvm/BinaryFormat/MachO.h"
1732 #include "llvm/CodeGen/AsmPrinter.h"
1833 #include "llvm/CodeGen/DIE.h"
1934 #include "llvm/Config/config.h"
35 #include "llvm/DebugInfo/DIContext.h"
36 #include "llvm/DebugInfo/DWARF/DWARFAbbreviationDeclaration.h"
2037 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
21 #include "llvm/DebugInfo/DWARF/DWARFDebugInfoEntry.h"
38 #include "llvm/DebugInfo/DWARF/DWARFDataExtractor.h"
39 #include "llvm/DebugInfo/DWARF/DWARFDebugLine.h"
40 #include "llvm/DebugInfo/DWARF/DWARFDebugRangeList.h"
41 #include "llvm/DebugInfo/DWARF/DWARFDie.h"
2242 #include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
43 #include "llvm/DebugInfo/DWARF/DWARFSection.h"
44 #include "llvm/DebugInfo/DWARF/DWARFUnit.h"
2345 #include "llvm/MC/MCAsmBackend.h"
2446 #include "llvm/MC/MCAsmInfo.h"
2547 #include "llvm/MC/MCCodeEmitter.h"
2850 #include "llvm/MC/MCInstrInfo.h"
2951 #include "llvm/MC/MCObjectFileInfo.h"
3052 #include "llvm/MC/MCRegisterInfo.h"
53 #include "llvm/MC/MCSection.h"
3154 #include "llvm/MC/MCStreamer.h"
3255 #include "llvm/MC/MCSubtargetInfo.h"
56 #include "llvm/MC/MCTargetOptions.h"
3357 #include "llvm/MC/MCTargetOptionsCommandFlags.h"
3458 #include "llvm/Object/MachO.h"
59 #include "llvm/Object/ObjectFile.h"
60 #include "llvm/Object/SymbolicFile.h"
61 #include "llvm/Support/Allocator.h"
62 #include "llvm/Support/Casting.h"
63 #include "llvm/Support/Compiler.h"
64 #include "llvm/Support/DataExtractor.h"
65 #include "llvm/Support/Error.h"
66 #include "llvm/Support/ErrorHandling.h"
67 #include "llvm/Support/ErrorOr.h"
68 #include "llvm/Support/FileSystem.h"
69 #include "llvm/Support/Format.h"
3570 #include "llvm/Support/LEB128.h"
71 #include "llvm/Support/MathExtras.h"
72 #include "llvm/Support/MemoryBuffer.h"
73 #include "llvm/Support/Path.h"
3674 #include "llvm/Support/TargetRegistry.h"
3775 #include "llvm/Support/ToolOutputFile.h"
76 #include "llvm/Support/raw_ostream.h"
3877 #include "llvm/Target/TargetMachine.h"
3978 #include "llvm/Target/TargetOptions.h"
79 #include
80 #include
81 #include
82 #include
83 #include
84 #include
85 #include
86 #include
87 #include
4088 #include
4189 #include
90 #include
4291 #include
92 #include
93 #include
4394
4495 namespace llvm {
4596 namespace dsymutil {
51102 IntervalMap::LeafSize,
52103 IntervalMapHalfOpenInfo>;
53104
54 typedef HalfOpenIntervalMap FunctionIntervals;
105 using FunctionIntervals = HalfOpenIntervalMap;
55106
56107 // FIXME: Delete this structure.
57108 struct PatchLocation {
94145 /// specific DeclContext using a separate DenseMap keyed on the hash
95146 /// of the fully qualified name of the context.
96147 class DeclContext {
148 friend DeclMapInfo;
149
97150 unsigned QualifiedNameHash = 0;
98151 uint32_t Line = 0;
99152 uint32_t ByteSize = 0;
106159 uint32_t LastSeenCompileUnitID = 0;
107160 uint32_t CanonicalDIEOffset = 0;
108161
109 friend DeclMapInfo;
110
111162 public:
112 typedef DenseSet Map;
163 using Map = DenseSet;
113164
114165 DeclContext() : DefinedInClangModule(0), Parent(*this) {}
115166
185236 public:
186237 /// Information gathered about a DIE in the object file.
187238 struct DIEInfo {
188 int64_t AddrAdjust; ///< Address offset to apply to the described entity.
189 DeclContext *Ctxt; ///< ODR Declaration context.
190 DIE *Clone; ///< Cloned version of that DIE.
191 uint32_t ParentIdx; ///< The index of this DIE's parent.
192 bool Keep : 1; ///< Is the DIE part of the linked output?
193 bool InDebugMap : 1; ///< Was this DIE's entity found in the map?
194 bool Prune : 1; ///< Is this a pure forward declaration we can strip?
195 bool Incomplete : 1; ///< Does DIE transitively refer an incomplete decl?
239 /// Address offset to apply to the described entity.
240 int64_t AddrAdjust;
241
242 /// ODR Declaration context.
243 DeclContext *Ctxt;
244
245 /// Cloned version of that DIE.
246 DIE *Clone;
247
248 /// The index of this DIE's parent.
249 uint32_t ParentIdx;
250
251 /// Is the DIE part of the linked output?
252 bool Keep : 1;
253
254 /// Was this DIE's entity found in the map?
255 bool InDebugMap : 1;
256
257 /// Is this a pure forward declaration we can strip?
258 bool Prune : 1;
259
260 /// Does DIE transitively refer an incomplete decl?
261 bool Incomplete : 1;
196262 };
197263
198264 CompileUnit(DWARFUnit &OrigUnit, unsigned ID, bool CanUseODR,
199265 StringRef ClangModuleName)
200 : OrigUnit(OrigUnit), ID(ID), LowPc(UINT64_MAX), HighPc(0), RangeAlloc(),
201 Ranges(RangeAlloc), ClangModuleName(ClangModuleName) {
266 : OrigUnit(OrigUnit), ID(ID), Ranges(RangeAlloc),
267 ClangModuleName(ClangModuleName) {
202268 Info.resize(OrigUnit.getNumDIEs());
203269
204270 auto CUDie = OrigUnit.getUnitDIE(false);
244310 Optional getUnitRangesAttribute() const {
245311 return UnitRangeAttribute;
246312 }
313
247314 const FunctionIntervals &getFunctionRanges() const { return Ranges; }
315
248316 const std::vector &getRangesAttributes() const {
249317 return RangeAttributes;
250318 }
336404 uint64_t StartOffset;
337405 uint64_t NextUnitOffset;
338406
339 uint64_t LowPc;
340 uint64_t HighPc;
407 uint64_t LowPc = std::numeric_limits::max();
408 uint64_t HighPc = 0;
341409
342410 /// A list of attributes to fixup with the absolute offset of
343411 /// a DIE in the debug_info section.
349417 PatchLocation>> ForwardDIEReferences;
350418
351419 FunctionIntervals::Allocator RangeAlloc;
420
352421 /// The ranges in that interval map are the PC ranges for
353422 /// functions in this unit, associated with the PC offset to apply
354423 /// to the addresses to get the linked address.
382451
383452 /// Is this unit subject to the ODR rule?
384453 bool HasODR;
454
385455 /// Did a DIE actually contain a valid reloc?
386456 bool HasInterestingContent;
457
387458 /// If this is a Clang module, this holds the module's name.
388459 std::string ClangModuleName;
389460 };
461
462 } // end anonymous namespace
390463
391464 void CompileUnit::markEverythingAsKept() {
392465 for (auto &I : Info)
457530 uint32_t Offset) {
458531 Pubtypes.emplace_back(Name, Die, Offset, false);
459532 }
533
534 namespace {
460535
461536 /// The Dwarf streaming logic
462537 ///
571646
572647 uint32_t getFrameSectionSize() const { return FrameSectionSize; }
573648 };
649
650 } // end anonymous namespace
574651
575652 bool DwarfStreamer::init(Triple TheTriple, StringRef OutputFilename) {
576653 std::string ErrorStr;
918995 if (Rows.empty()) {
919996 // We only have the dummy entry, dsymutil emits an entry with a 0
920997 // address in that case.
921 MCDwarfLineAddr::Encode(*MC, Params, INT64_MAX, 0, EncodingOS);
998 MCDwarfLineAddr::Encode(*MC, Params, std::numeric_limits::max(), 0,
999 EncodingOS);
9221000 MS->EmitBytes(EncodingOS.str());
9231001 LineSectionSize += EncodingBuffer.size();
9241002 MS->EmitLabel(LineEndSym);
10181096 MS->EmitULEB128IntValue(AddressDelta);
10191097 LineSectionSize += 1 + getULEB128Size(AddressDelta);
10201098 }
1021 MCDwarfLineAddr::Encode(*MC, Params, INT64_MAX, 0, EncodingOS);
1099 MCDwarfLineAddr::Encode(*MC, Params, std::numeric_limits::max(),
1100 0, EncodingOS);
10221101 MS->EmitBytes(EncodingOS.str());
10231102 LineSectionSize += EncodingBuffer.size();
10241103 EncodingBuffer.resize(0);
10291108 }
10301109
10311110 if (RowsSinceLastSequence) {
1032 MCDwarfLineAddr::Encode(*MC, Params, INT64_MAX, 0, EncodingOS);
1111 MCDwarfLineAddr::Encode(*MC, Params, std::numeric_limits::max(), 0,
1112 EncodingOS);
10331113 MS->EmitBytes(EncodingOS.str());
10341114 LineSectionSize += EncodingBuffer.size();
10351115 EncodingBuffer.resize(0);
11101190 MS->EmitBytes(FDEBytes);
11111191 FrameSectionSize += FDEBytes.size() + 8 + AddrSize;
11121192 }
1193
1194 namespace {
11131195
11141196 /// The core of the Dwarf linking logic.
11151197 ///
11781260 /// ValidRelocs is sorted by file offset, keeping this index
11791261 /// uptodate is all we have to do to have a cheap lookup during the
11801262 /// root DIE selection and during DIE cloning.
1181 unsigned NextValidReloc;
1263 unsigned NextValidReloc = 0;
11821264
11831265 public:
1184 RelocationManager(DwarfLinker &Linker)
1185 : Linker(Linker), NextValidReloc(0) {}
1266 RelocationManager(DwarfLinker &Linker) : Linker(Linker) {}
11861267
11871268 bool hasValidRelocs() const { return !ValidRelocs.empty(); }
1269
11881270 /// Reset the NextValidReloc counter.
11891271 void resetValidRelocs() { NextValidReloc = 0; }
11901272
12831365 class DIECloner {
12841366 DwarfLinker &Linker;
12851367 RelocationManager &RelocMgr;
1368
12861369 /// Allocator used for all the DIEValue objects.
12871370 BumpPtrAllocator &DIEAlloc;
1371
12881372 std::vector> &CompileUnits;
12891373 LinkOptions Options;
12901374
13171401 void cloneAllCompileUnits(DWARFContext &DwarfContext);
13181402
13191403 private:
1320 typedef DWARFAbbreviationDeclaration::AttributeSpec AttributeSpec;
1404 using AttributeSpec = DWARFAbbreviationDeclaration::AttributeSpec;
13211405
13221406 /// Information gathered and exchanged between the various
13231407 /// clone*Attributes helpers about the attributes of a particular DIE.
13241408 struct AttributesInfo {
1325 const char *Name, *MangledName; ///< Names.
1326 uint32_t NameOffset, MangledNameOffset; ///< Offsets in the string pool.
1327
1328 uint64_t OrigLowPc; ///< Value of AT_low_pc in the input DIE
1329 uint64_t OrigHighPc; ///< Value of AT_high_pc in the input DIE
1330 int64_t PCOffset; ///< Offset to apply to PC addresses inside a function.
1331
1332 bool HasLowPc; ///< Does the DIE have a low_pc attribute?
1333 bool IsDeclaration; ///< Is this DIE only a declaration?
1334
1335 AttributesInfo()
1336 : Name(nullptr), MangledName(nullptr), NameOffset(0),
1337 MangledNameOffset(0), OrigLowPc(UINT64_MAX), OrigHighPc(0),
1338 PCOffset(0), HasLowPc(false), IsDeclaration(false) {}
1409 /// Names.
1410 const char *Name = nullptr;
1411 const char *MangledName = nullptr;
1412
1413 /// Offsets in the string pool.
1414 uint32_t NameOffset = 0;
1415 uint32_t MangledNameOffset = 0;
1416
1417 /// Value of AT_low_pc in the input DIE
1418 uint64_t OrigLowPc = std::numeric_limits::max();
1419
1420 /// Value of AT_high_pc in the input DIE
1421 uint64_t OrigHighPc = 0;
1422
1423 /// Offset to apply to PC addresses inside a function.
1424 int64_t PCOffset = 0;
1425
1426 /// Does the DIE have a low_pc attribute?
1427 bool HasLowPc = false;
1428
1429 /// Is this DIE only a declaration?
1430 bool IsDeclaration = false;
1431
1432 AttributesInfo() = default;
13391433 };
13401434
13411435 /// Helper for cloneDIE.
13961490 /// Assign an abbreviation number to \p Abbrev
13971491 void AssignAbbrev(DIEAbbrev &Abbrev);
13981492
1493 /// Compute and emit debug_ranges section for \p Unit, and
1494 /// patch the attributes referencing it.
1495 void patchRangesForUnit(const CompileUnit &Unit, DWARFContext &Dwarf) const;
1496
1497 /// Generate and emit the DW_AT_ranges attribute for a
1498 /// compile_unit if it had one.
1499 void generateUnitRanges(CompileUnit &Unit) const;
1500
1501 /// Extract the line tables fromt he original dwarf, extract
1502 /// the relevant parts according to the linked function ranges and
1503 /// emit the result in the debug_line section.
1504 void patchLineTableForUnit(CompileUnit &Unit, DWARFContext &OrigDwarf);
1505
1506 /// Emit the accelerator entries for \p Unit.
1507 void emitAcceleratorEntriesForUnit(CompileUnit &Unit);
1508
1509 /// Patch the frame info for an object file and emit it.
1510 void patchFrameInfoForObject(const DebugMapObject &, DWARFContext &,
1511 unsigned AddressSize);
1512
13991513 /// FoldingSet that uniques the abbreviations.
14001514 FoldingSet AbbreviationsSet;
1515
14011516 /// Storage for the unique Abbreviations.
14021517 /// This is passed to AsmPrinter::emitDwarfAbbrevs(), thus it cannot
14031518 /// be changed to a vecot of unique_ptrs.
14041519 std::vector> Abbreviations;
14051520
1406 /// Compute and emit debug_ranges section for \p Unit, and
1407 /// patch the attributes referencing it.
1408 void patchRangesForUnit(const CompileUnit &Unit, DWARFContext &Dwarf) const;
1409
1410 /// Generate and emit the DW_AT_ranges attribute for a
1411 /// compile_unit if it had one.
1412 void generateUnitRanges(CompileUnit &Unit) const;
1413
1414 /// Extract the line tables fromt he original dwarf, extract
1415 /// the relevant parts according to the linked function ranges and
1416 /// emit the result in the debug_line section.
1417 void patchLineTableForUnit(CompileUnit &Unit, DWARFContext &OrigDwarf);
1418
1419 /// Emit the accelerator entries for \p Unit.
1420 void emitAcceleratorEntriesForUnit(CompileUnit &Unit);
1421
1422 /// Patch the frame info for an object file and emit it.
1423 void patchFrameInfoForObject(const DebugMapObject &, DWARFContext &,
1424 unsigned AddressSize);
1425
14261521 /// DIELoc objects that need to be destructed (but not freed!).
14271522 std::vector DIELocs;
1523
14281524 /// DIEBlock objects that need to be destructed (but not freed!).
14291525 std::vector DIEBlocks;
1526
14301527 /// Allocator used for all the DIEValue objects.
14311528 BumpPtrAllocator DIEAlloc;
14321529 /// @}
14501547 BinaryHolder BinHolder;
14511548 std::unique_ptr Streamer;
14521549 uint64_t OutputDebugInfoSize;
1453 unsigned UnitID; ///< A unique ID that identifies each compile unit.
1550
1551 /// A unique ID that identifies each compile unit.
1552 unsigned UnitID;
1553
14541554 unsigned MaxDwarfVersion = 0;
14551555
14561556 /// The units of the current debug map object.
14571557 std::vector> Units;
1458
14591558
14601559 /// The debug map object currently under consideration.
14611560 DebugMapObject *CurrentDebugObject;
14871586 bool ModuleCacheHintDisplayed = false;
14881587 bool ArchiveHintDisplayed = false;
14891588 };
1589
1590 } // end anonymous namespace
14901591
14911592 /// Similar to DWARFUnitSection::getUnitForOffset(), but returning our
14921593 /// CompileUnit object instead.
16321733 return PointerIntPair(nullptr);
16331734
16341735 unsigned Line = 0;
1635 unsigned ByteSize = UINT32_MAX;
1736 unsigned ByteSize = std::numeric_limits::max();
16361737
16371738 if (!InClangModule) {
16381739 // Gather some discriminating data about the DeclContext we will be
16421743 // namespaces, use these additional data points to make the process
16431744 // safer. This is disabled for clang modules, because forward
16441745 // declarations of module-defined types do not have a file and line.
1645 ByteSize = dwarf::toUnsigned(DIE.find(dwarf::DW_AT_byte_size), UINT64_MAX);
1746 ByteSize = dwarf::toUnsigned(DIE.find(dwarf::DW_AT_byte_size),
1747 std::numeric_limits::max());
16461748 if (Tag != dwarf::DW_TAG_namespace || !Name) {
16471749 if (unsigned FileNum = dwarf::toUnsigned(DIE.find(dwarf::DW_AT_decl_file), 0)) {
16481750 if (const auto *LT = U.getOrigUnit().getContext().getLineTableForUnit(
20622164
20632165 const auto &ValidReloc = ValidRelocs[NextValidReloc++];
20642166 const auto &Mapping = ValidReloc.Mapping->getValue();
2065 uint64_t ObjectAddress =
2066 Mapping.ObjectAddress ? uint64_t(*Mapping.ObjectAddress) : UINT64_MAX;
2167 uint64_t ObjectAddress = Mapping.ObjectAddress
2168 ? uint64_t(*Mapping.ObjectAddress)
2169 : std::numeric_limits::max();
20672170 if (Linker.Options.Verbose)
20682171 outs() << "Found valid debug map entry: " << ValidReloc.Mapping->getKey()
20692172 << " " << format("\t%016" PRIx64 " => %016" PRIx64, ObjectAddress,
25382641 // relocated because it happens to match the low_pc of the
25392642 // enclosing subprogram. To prevent issues with that, always use
25402643 // the low_pc from the input DIE if relocations have been applied.
2541 Addr = (Info.OrigLowPc != UINT64_MAX ? Info.OrigLowPc : Addr) +
2644 Addr = (Info.OrigLowPc != std::numeric_limits::max()
2645 ? Info.OrigLowPc
2646 : Addr) +
25422647 Info.PCOffset;
25432648 else if (Die.getTag() == dwarf::DW_TAG_compile_unit) {
25442649 Addr = Unit.getLowPc();
2545 if (Addr == UINT64_MAX)
2650 if (Addr == std::numeric_limits::max())
25462651 return 0;
25472652 }
25482653 Info.HasLowPc = true;
28192924 // Also store the low_pc. It might get relocated in an
28202925 // inline_subprogram that happens at the beginning of its
28212926 // inlining function.
2822 AttrInfo.OrigLowPc =
2823 dwarf::toAddress(InputDIE.find(dwarf::DW_AT_low_pc), UINT64_MAX);
2927 AttrInfo.OrigLowPc = dwarf::toAddress(InputDIE.find(dwarf::DW_AT_low_pc),
2928 std::numeric_limits::max());
28242929 }
28252930
28262931 // Reset the Offset to 0 as we will be working on the local copy of
34783583 }
34793584
34803585 bool DwarfLinker::link(const DebugMap &Map) {
3481
34823586 if (!createStreamer(Map.getTriple(), OutputFilename))
34833587 return false;
34843588
35933697
35943698 return Options.NoOutput ? true : Streamer->finish(Map);
35953699 }
3596 }
35973700
35983701 /// Get the offset of string \p S in the string table. This
35993702 /// can insert a new element or return the offset of a preexisitng
36453748 DwarfLinker Linker(OutputFilename, Options);
36463749 return Linker.link(DM);
36473750 }
3648 }
3649 }
3751
3752 } // end namespace dsymutil
3753 } // end namespace llvm
None //===-- NonRelocatableStringpool.h - A simple stringpool -----------------===//
0 //===- NonRelocatableStringpool.h - A simple stringpool --------*- C++ -*-===//
11 //
22 // The LLVM Compiler Infrastructure
33 //
55 // License. See LICENSE.TXT for details.
66 //
77 //===----------------------------------------------------------------------===//
8
89 #ifndef LLVM_TOOLS_DSYMUTIL_NONRELOCATABLESTRINGPOOL_H
910 #define LLVM_TOOLS_DSYMUTIL_NONRELOCATABLESTRINGPOOL_H
1011
1112 #include "llvm/ADT/StringMap.h"
13 #include "llvm/ADT/StringRef.h"
14 #include "llvm/Support/Allocator.h"
15 #include
16 #include
1217
1318 namespace llvm {
1419 namespace dsymutil {
2429 /// \brief Entries are stored into the StringMap and simply linked
2530 /// together through the second element of this pair in order to
2631 /// keep track of insertion order.
27 typedef StringMap, BumpPtrAllocator>
28 MapTy;
32 using MapTy =
33 StringMap, BumpPtrAllocator>;
2934
30 NonRelocatableStringpool()
31 : CurrentEndOffset(0), Sentinel(0), Last(&Sentinel) {
35 NonRelocatableStringpool() : Sentinel(0), Last(&Sentinel) {
3236 // Legacy dsymutil puts an empty string at the start of the line
3337 // table.
3438 getStringOffset("");
6064
6165 private:
6266 MapTy Strings;
63 uint32_t CurrentEndOffset;
67 uint32_t CurrentEndOffset = 0;
6468 MapTy::MapEntryTy Sentinel, *Last;
6569 };
66 }
67 }
6870
69 #endif
71 } // end namespace dsymutil
72 } // end namespace llvm
73
74 #endif // LLVM_TOOLS_DSYMUTIL_NONRELOCATABLESTRINGPOOL_H
None //===-- dsymutil.cpp - Debug info dumping utility for llvm ----------------===//
0 //===- dsymutil.cpp - Debug info dumping utility for llvm -----------------===//
11 //
22 // The LLVM Compiler Infrastructure
33 //
1414 #include "dsymutil.h"
1515 #include "DebugMap.h"
1616 #include "MachOUtils.h"
17 #include "llvm/ADT/SmallString.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/StringRef.h"
20 #include "llvm/ADT/Triple.h"
1721 #include "llvm/Object/MachO.h"
22 #include "llvm/Support/CommandLine.h"
1823 #include "llvm/Support/FileSystem.h"
19 #include "llvm/Support/FileUtilities.h"
2024 #include "llvm/Support/ManagedStatic.h"
21 #include "llvm/Support/Options.h"
25 #include "llvm/Support/Path.h"
2226 #include "llvm/Support/PrettyStackTrace.h"
2327 #include "llvm/Support/Signals.h"
2428 #include "llvm/Support/TargetSelect.h"
2529 #include "llvm/Support/ThreadPool.h"
2630 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/Support/thread.h"
32 #include
2733 #include
34 #include
2835 #include
29
36 #include
37
38 using namespace llvm::cl;
3039 using namespace llvm::dsymutil;
3140
32 namespace {
33 using namespace llvm::cl;
34
35 OptionCategory DsymCategory("Specific Options");
41 static OptionCategory DsymCategory("Specific Options");
3642 static opt Help("h", desc("Alias for -help"), Hidden);
3743 static opt Version("v", desc("Alias for -version"), Hidden);
3844
7682 NoOutput("no-output",
7783 desc("Do the link in memory, but do not emit the result file."),
7884 init(false), cat(DsymCategory));
85
7986 static opt
8087 NoTimestamp("no-swiftmodule-timestamp",
8188 desc("Don't check timestamp for swiftmodule files."),
8289 init(false), cat(DsymCategory));
90
8391 static list ArchFlags(
8492 "arch",
8593 desc("Link DWARF debug information only for specified CPU architecture\n"
102110 static opt InputIsYAMLDebugMap(
103111 "y", desc("Treat the input file is a YAML debug map rather than a binary."),
104112 init(false), cat(DsymCategory));
105 }
106113
107114 static bool createPlistFile(llvm::StringRef BundleRoot) {
108115 if (NoOutput)
55 // License. See LICENSE.TXT for details.
66 //
77 //===----------------------------------------------------------------------===//
8 ///
8 //
99 /// \file
1010 ///
1111 /// This file contains the class declaration for the code that parses STABS
1212 /// debug maps that are embedded in the binaries symbol tables.
13 ///
13 //
1414 //===----------------------------------------------------------------------===//
15
1516 #ifndef LLVM_TOOLS_DSYMUTIL_DSYMUTIL_H
1617 #define LLVM_TOOLS_DSYMUTIL_DSYMUTIL_H
1718
1819 #include "DebugMap.h"
20 #include "llvm/ADT/ArrayRef.h"
1921 #include "llvm/ADT/StringRef.h"
22 #include "llvm/Support/Compiler.h"
2023 #include "llvm/Support/ErrorOr.h"
2124 #include
25 #include
26 #include
2227
2328 namespace llvm {
2429 namespace dsymutil {
2530
2631 struct LinkOptions {
27 bool Verbose; ///< Verbosity
28 bool NoOutput; ///< Skip emitting output
29 bool NoODR; ///< Do not unique types according to ODR
30 bool NoTimestamp; ///< Do not check swiftmodule timestamp
31 std::string PrependPath; ///< -oso-prepend-path
32 /// Verbosity
33 bool Verbose = false;
3234
33 LinkOptions() : Verbose(false), NoOutput(false), NoTimestamp(false) {}
35 /// Skip emitting output
36 bool NoOutput = false;
37
38 /// Do not unique types according to ODR
39 bool NoODR;
40
41 /// Do not check swiftmodule timestamp
42 bool NoTimestamp = false;
43
44 /// -oso-prepend-path
45 std::string PrependPath;
46
47 LinkOptions() = default;
3448 };
3549
3650 /// \brief Extract the DebugMaps from the given file.
3751 /// The file has to be a MachO object file. Multiple debug maps can be
3852 /// returned when the file is universal (aka fat) binary.
39 llvm::ErrorOr>>
53 ErrorOr>>
4054 parseDebugMap(StringRef InputFile, ArrayRef Archs,
4155 StringRef PrependPath, bool Verbose, bool InputIsYAML);
4256
5670
5771 void warn(const Twine &Warning, const Twine &Context);
5872 bool error(const Twine &Error, const Twine &Context);
59 }
60 }
73
74 } // end namespace dsymutil
75 } // end namespace llvm
76
6177 #endif // LLVM_TOOLS_DSYMUTIL_DSYMUTIL_H
None //===- Object.cpp -----------------------------------------------*- C++ -*-===//
0 //===- Object.cpp ---------------------------------------------------------===//
11 //
22 // The LLVM Compiler Infrastructure
33 //
55 // License. See LICENSE.TXT for details.
66 //
77 //===----------------------------------------------------------------------===//
8
89 #include "Object.h"
910 #include "llvm-objcopy.h"
11 #include "llvm/ADT/ArrayRef.h"
12 #include "llvm/ADT/STLExtras.h"
13 #include "llvm/ADT/StringRef.h"
14 #include "llvm/ADT/Twine.h"
15 #include "llvm/ADT/iterator_range.h"
16 #include "llvm/BinaryFormat/ELF.h"
17 #include "llvm/Object/ELFObjectFile.h"
18 #include "llvm/Support/ErrorHandling.h"
19 #include "llvm/Support/FileOutputBuffer.h"
20 #include
21 #include
22 #include
23 #include
24 #include
25 #include
1026
1127 using namespace llvm;
1228 using namespace object;
1329 using namespace ELF;
1430
1531 template void Segment::writeHeader(FileOutputBuffer &Out) const {
16 typedef typename ELFT::Ehdr Elf_Ehdr;
17 typedef typename ELFT::Phdr Elf_Phdr;
32 using Elf_Ehdr = typename ELFT::Ehdr;
33 using Elf_Phdr = typename ELFT::Phdr;
1834
1935 uint8_t *Buf = Out.getBufferStart();
2036 Buf += sizeof(Elf_Ehdr) + Index * sizeof(Elf_Phdr);
190206 }
191207
192208 template
193 void SymbolTableSectionImpl::writeSection(
194 llvm::FileOutputBuffer &Out) const {
209 void SymbolTableSectionImpl::writeSection(FileOutputBuffer &Out) const {
195210 uint8_t *Buf = Out.getBufferStart();
196211 Buf += Offset;
197212 typename ELFT::Sym *Sym = reinterpret_cast(Buf);
211226 void RelocSectionWithSymtabBase::removeSectionReferences(
212227 const SectionBase *Sec) {
213228 if (Symbols == Sec) {
214 error("Symbol table " + Symbols->Name + " cannot be removed because it is "
215 "referenced by the relocation "
216 "section " +
229 error("Symbol table " + Symbols->Name +
230 " cannot be removed because it is "
231 "referenced by the relocation "
232 "section " +
217233 this->Name);
218234 }
219235 }
228244 " is not a symbol table"));
229245
230246 if (Info != SHN_UNDEF)
231 setSection(SecTable.getSection(Info,
232 "Info field value " + Twine(Info) +
233 " in section " + Name + " is invalid"));
247 setSection(SecTable.getSection(Info, "Info field value " + Twine(Info) +
248 " in section " + Name +
249 " is invalid"));
234250 else
235251 setSection(nullptr);
236252 }
262278 }
263279
264280 template
265 void RelocationSection::writeSection(llvm::FileOutputBuffer &Out) const {
281 void RelocationSection::writeSection(FileOutputBuffer &Out) const {
266282 uint8_t *Buf = Out.getBufferStart() + Offset;
267283 if (Type == SHT_REL)
268284 writeRel(reinterpret_cast(Buf));
270286 writeRel(reinterpret_cast(Buf));
271287 }
272288
273 void DynamicRelocationSection::writeSection(llvm::FileOutputBuffer &Out) const {
289 void DynamicRelocationSection::writeSection(FileOutputBuffer &Out) const {
274290 std::copy(std::begin(Contents), std::end(Contents),
275291 Out.getBufferStart() + Offset);
276292 }
277293
278294 void SectionWithStrTab::removeSectionReferences(const SectionBase *Sec) {
279295 if (StrTab == Sec) {
280 error("String table " + StrTab->Name + " cannot be removed because it is "
281 "referenced by the section " +
296 error("String table " + StrTab->Name +
297 " cannot be removed because it is "
298 "referenced by the section " +
282299 this->Name);
283300 }
284301 }
288305 }
289306
290307 void SectionWithStrTab::initialize(SectionTableRef SecTable) {
291 auto StrTab = SecTable.getSection(Link,
292 "Link field value " + Twine(Link) +
293 " in section " + Name + " is invalid");
308 auto StrTab =
309 SecTable.getSection(Link, "Link field value " + Twine(Link) +
310 " in section " + Name + " is invalid");
294311 if (StrTab->Type != SHT_STRTAB) {
295312 error("Link field value " + Twine(Link) + " in section " + Name +
296313 " is not a string table");
376393 }
377394
378395 template
379 void Object::initSymbolTable(const llvm::object::ELFFile &ElfFile,
396 void Object::initSymbolTable(const object::ELFFile &ElfFile,
380397 SymbolTableSection *SymTab,
381398 SectionTableRef SecTable) {
382
383399 const Elf_Shdr &Shdr = *unwrapOrError(ElfFile.getSection(SymTab->Index));
384400 StringRef StrTabData = unwrapOrError(ElfFile.getStringTableForSymtab(Shdr));
385401
396412 }
397413 } else if (Sym.st_shndx != SHN_UNDEF) {
398414 DefSection = SecTable.getSection(
399 Sym.st_shndx,
400 "Symbol '" + Name + "' is defined in invalid section with index " +
401 Twine(Sym.st_shndx));
415 Sym.st_shndx, "Symbol '" + Name +
416 "' is defined in invalid section with index " +
417 Twine(Sym.st_shndx));
402418 }
403419
404420 SymTab->addSymbol(Name, Sym.getBinding(), Sym.getType(), DefSection,
436452 template
437453 T *SectionTableRef::getSectionOfType(uint16_t Index, Twine IndexErrMsg,
438454 Twine TypeErrMsg) {
439 if (T *Sec = llvm::dyn_cast(getSection(Index, IndexErrMsg)))
455 if (T *Sec = dyn_cast(getSection(Index, IndexErrMsg)))
440456 return Sec;
441457 error(TypeErrMsg);
442458 }
443459
444460 template
445461 std::unique_ptr
446 Object::makeSection(const llvm::object::ELFFile &ElfFile,
462 Object::makeSection(const object::ELFFile &ElfFile,
447463 const Elf_Shdr &Shdr) {
448464 ArrayRef Data;
449465 switch (Shdr.sh_type) {
620636 template
621637 void Object::writeSectionData(FileOutputBuffer &Out) const {
622638 for (auto &Section : Sections)
623 Section->writeSection(Out);
639 Section->writeSection(Out);
624640 }
625641
626642 template
796812 for (auto &Segment : this->Segments) {
797813 // GNU objcopy does not output segments that do not cover a section. Such
798814 // segments can sometimes be produced by LLD due to how LLD handles PT_PHDR.
799 if (Segment->Type == llvm::ELF::PT_LOAD &&
800 Segment->firstSection() != nullptr) {
815 if (Segment->Type == PT_LOAD && Segment->firstSection() != nullptr) {
801816 Segment->writeSegment(Out);
802817 }
803818 }
804819 }
805820
806821 template void BinaryObject::finalize() {
807
808822 // Put all segments in offset order.
809823 auto CompareSegments = [](const SegPtr &A, const SegPtr &B) {
810824 return A->Offset < B->Offset;
814828
815829 uint64_t Offset = 0;
816830 for (auto &Segment : this->Segments) {
817 if (Segment->Type == llvm::ELF::PT_LOAD &&
818 Segment->firstSection() != nullptr) {
831 if (Segment->Type == PT_LOAD && Segment->firstSection() != nullptr) {
819832 Offset = alignTo(Offset, Segment->Align);
820833 Segment->Offset = Offset;
821834 Offset += Segment->FileSize;
823836 }
824837 TotalSize = Offset;
825838 }
839
840 namespace llvm {
826841
827842 template class Object;
828843 template class Object;
838853 template class BinaryObject;
839854 template class BinaryObject;
840855 template class BinaryObject;
856
857 } // end namespace llvm
66 //
77 //===----------------------------------------------------------------------===//
88
9 #ifndef LLVM_OBJCOPY_OBJECT_H
10 #define LLVM_OBJCOPY_OBJECT_H
11
9 #ifndef LLVM_TOOLS_OBJCOPY_OBJECT_H
10 #define LLVM_TOOLS_OBJCOPY_OBJECT_H
11
12 #include "llvm/ADT/ArrayRef.h"
13 #include "llvm/ADT/StringRef.h"
14 #include "llvm/ADT/Twine.h"
15 #include "llvm/BinaryFormat/ELF.h"
1216 #include "llvm/MC/StringTableBuilder.h"
1317 #include "llvm/Object/ELFObjectFile.h"
14 #include "llvm/Support/FileOutputBuffer.h"
15
18 #include
19 #include
20 #include
1621 #include
1722 #include
18
23 #include
24
25 namespace llvm {
26
27 class FileOutputBuffer;
28 class SectionBase;
1929 class Segment;
20 class SectionBase;
2130
2231 class SectionTableRef {
2332 private:
24 llvm::ArrayRef> Sections;
25
26 public:
27 SectionTableRef(llvm::ArrayRef> Secs)
33 ArrayRef> Sections;
34
35 public:
36 SectionTableRef(ArrayRef> Secs)
2837 : Sections(Secs) {}
2938 SectionTableRef(const SectionTableRef &) = default;
3039
31 SectionBase *getSection(uint16_t Index, llvm::Twine ErrMsg);
40 SectionBase *getSection(uint16_t Index, Twine ErrMsg);
3241
3342 template
34 T *getSectionOfType(uint16_t Index, llvm::Twine IndexErrMsg,
35 llvm::Twine TypeErrMsg);
43 T *getSectionOfType(uint16_t Index, Twine IndexErrMsg, Twine TypeErrMsg);
3644 };
3745
3846 class SectionBase {
3947 public:
40 llvm::StringRef Name;
48 StringRef Name;
4149 Segment *ParentSegment = nullptr;
4250 uint64_t HeaderOffset;
4351 uint64_t OriginalOffset;
4856 uint32_t EntrySize = 0;
4957 uint64_t Flags = 0;
5058 uint64_t Info = 0;
51 uint64_t Link = llvm::ELF::SHN_UNDEF;
59 uint64_t Link = ELF::SHN_UNDEF;
5260 uint64_t NameIndex = 0;
5361 uint64_t Offset = 0;
5462 uint64_t Size = 0;
55 uint64_t Type = llvm::ELF::SHT_NULL;
56
57 virtual ~SectionBase() {}
63 uint64_t Type = ELF::SHT_NULL;
64
65 virtual ~SectionBase() = default;
66
5867 virtual void initialize(SectionTableRef SecTable);
5968 virtual void finalize();
6069 virtual void removeSectionReferences(const SectionBase *Sec);
61 template void writeHeader(llvm::FileOutputBuffer &Out) const;
62 virtual void writeSection(llvm::FileOutputBuffer &Out) const = 0;
70 template void writeHeader(FileOutputBuffer &Out) const;
71 virtual void writeSection(FileOutputBuffer &Out) const = 0;
6372 };
6473
6574 class Segment {
7685 };
7786
7887 std::set Sections;
79 llvm::ArrayRef Contents;
88 ArrayRef Contents;
8089
8190 public:
8291 uint64_t Align;
92101 uint64_t OriginalOffset;
93102 Segment *ParentSegment = nullptr;
94103
95 Segment(llvm::ArrayRef Data) : Contents(Data) {}
104 Segment(ArrayRef Data) : Contents(Data) {}
105
96106 const SectionBase *firstSection() const {
97107 if (!Sections.empty())
98108 return *Sections.begin();
99109 return nullptr;
100110 }
111
101112 void removeSection(const SectionBase *Sec) { Sections.erase(Sec); }
102113 void addSection(const SectionBase *Sec) { Sections.insert(Sec); }
103 template void writeHeader(llvm::FileOutputBuffer &Out) const;
104 void writeSegment(llvm::FileOutputBuffer &Out) const;
114 template void writeHeader(FileOutputBuffer &Out) const;
115 void writeSegment(FileOutputBuffer &Out) const;
105116 };
106117
107118 class Section : public SectionBase {
108119 private:
109 llvm::ArrayRef Contents;
110
111 public:
112 Section(llvm::ArrayRef Data) : Contents(Data) {}
113 void writeSection(llvm::FileOutputBuffer &Out) const override;
120 ArrayRef Contents;
121
122 public:
123 Section(ArrayRef Data) : Contents(Data) {}
124
125 void writeSection(FileOutputBuffer &Out) const override;
114126 };
115127
116128 // There are two types of string tables that can exist, dynamic and not dynamic.
123135 // then agrees with the makeSection method used to construct most sections.
124136 class StringTableSection : public SectionBase {
125137 private:
126 llvm::StringTableBuilder StrTabBuilder;
127
128 public:
129 StringTableSection() : StrTabBuilder(llvm::StringTableBuilder::ELF) {
130 Type = llvm::ELF::SHT_STRTAB;
131 }
132
133 void addString(llvm::StringRef Name);
134 uint32_t findIndex(llvm::StringRef Name) const;
135 void finalize() override;
136 void writeSection(llvm::FileOutputBuffer &Out) const override;
137 static bool classof(const SectionBase *S) {
138 if (S->Flags & llvm::ELF::SHF_ALLOC)
138 StringTableBuilder StrTabBuilder;
139
140 public:
141 StringTableSection() : StrTabBuilder(StringTableBuilder::ELF) {
142 Type = ELF::SHT_STRTAB;
143 }
144
145 void addString(StringRef Name);
146 uint32_t findIndex(StringRef Name) const;
147 void finalize() override;
148 void writeSection(FileOutputBuffer &Out) const override;
149
150 static bool classof(const SectionBase *S) {
151 if (S->Flags & ELF::SHF_ALLOC)
139152 return false;
140 return S->Type == llvm::ELF::SHT_STRTAB;
153 return S->Type == ELF::SHT_STRTAB;
141154 }
142155 };
143156
147160 // SYMBOL_SIMPLE_INDEX means that the st_shndx is just an index of a section.
148161 enum SymbolShndxType {
149162 SYMBOL_SIMPLE_INDEX = 0,
150 SYMBOL_ABS = llvm::ELF::SHN_ABS,
151 SYMBOL_COMMON = llvm::ELF::SHN_COMMON,
152 SYMBOL_HEXAGON_SCOMMON = llvm::ELF::SHN_HEXAGON_SCOMMON,
153 SYMBOL_HEXAGON_SCOMMON_2 = llvm::ELF::SHN_HEXAGON_SCOMMON_2,
154 SYMBOL_HEXAGON_SCOMMON_4 = llvm::ELF::SHN_HEXAGON_SCOMMON_4,
155 SYMBOL_HEXAGON_SCOMMON_8 = llvm::ELF::SHN_HEXAGON_SCOMMON_8,
163 SYMBOL_ABS = ELF::SHN_ABS,
164 SYMBOL_COMMON = ELF::SHN_COMMON,
165 SYMBOL_HEXAGON_SCOMMON = ELF::SHN_HEXAGON_SCOMMON,
166 SYMBOL_HEXAGON_SCOMMON_2 = ELF::SHN_HEXAGON_SCOMMON_2,
167 SYMBOL_HEXAGON_SCOMMON_4 = ELF::SHN_HEXAGON_SCOMMON_4,
168 SYMBOL_HEXAGON_SCOMMON_8 = ELF::SHN_HEXAGON_SCOMMON_8,
156169 };
157170
158171 struct Symbol {
160173 SectionBase *DefinedIn = nullptr;
161174 SymbolShndxType ShndxType;
162175 uint32_t Index;
163 llvm::StringRef Name;
176 StringRef Name;
164177 uint32_t NameIndex;
165178 uint64_t Size;
166179 uint8_t Type;
174187 std::vector> Symbols;
175188 StringTableSection *SymbolNames = nullptr;
176189
177 typedef std::unique_ptr SymPtr;
190 using SymPtr = std::unique_ptr;
178191
179192 public:
180193 void setStrTab(StringTableSection *StrTab) { SymbolNames = StrTab; }
181 void addSymbol(llvm::StringRef Name, uint8_t Bind, uint8_t Type,
194 void addSymbol(StringRef Name, uint8_t Bind, uint8_t Type,
182195 SectionBase *DefinedIn, uint64_t Value, uint16_t Shndx,
183196 uint64_t Sz);
184197 void addSymbolNames();
186199 void removeSectionReferences(const SectionBase *Sec) override;
187200 void initialize(SectionTableRef SecTable) override;
188201 void finalize() override;
189 static bool classof(const SectionBase *S) {
190 return S->Type == llvm::ELF::SHT_SYMTAB;
202
203 static bool classof(const SectionBase *S) {
204 return S->Type == ELF::SHT_SYMTAB;
191205 }
192206 };
193207
194208 // Only writeSection depends on the ELF type so we implement it in a subclass.
195209 template class SymbolTableSectionImpl : public SymbolTableSection {
196 void writeSection(llvm::FileOutputBuffer &Out) const override;
210 void writeSection(FileOutputBuffer &Out) const override;
197211 };
198212
199213 struct Relocation {
221235 void setSection(SectionBase *Sec) { SecToApplyRel = Sec; }
222236
223237 static bool classof(const SectionBase *S) {
224 return S->Type == llvm::ELF::SHT_REL || S->Type == llvm::ELF::SHT_RELA;
238 return S->Type == ELF::SHT_REL || S->Type == ELF::SHT_RELA;
225239 }
226240 };
227241
233247 SymTabType *Symbols = nullptr;
234248
235249 protected:
236 RelocSectionWithSymtabBase() {}
250 RelocSectionWithSymtabBase() = default;
237251
238252 public:
239253 void setSymTab(SymTabType *StrTab) { Symbols = StrTab; }
240
241254 void removeSectionReferences(const SectionBase *Sec) override;
242255 void initialize(SectionTableRef SecTable) override;
243256 void finalize() override;
247260 class RelocationSection
248261 : public RelocSectionWithSymtabBase {
249262 private:
250 typedef typename ELFT::Rel Elf_Rel;
251 typedef typename ELFT::Rela Elf_Rela;
263 using Elf_Rel = typename ELFT::Rel;
264 using Elf_Rela = typename ELFT::Rela;
252265
253266 std::vector Relocations;
254267
256269
257270 public:
258271 void addRelocation(Relocation Rel) { Relocations.push_back(Rel); }
259 void writeSection(llvm::FileOutputBuffer &Out) const override;
260
261 static bool classof(const SectionBase *S) {
262 if (S->Flags & llvm::ELF::SHF_ALLOC)
272 void writeSection(FileOutputBuffer &Out) const override;
273
274 static bool classof(const SectionBase *S) {
275 if (S->Flags & ELF::SHF_ALLOC)
263276 return false;
264 return S->Type == llvm::ELF::SHT_REL || S->Type == llvm::ELF::SHT_RELA;
277 return S->Type == ELF::SHT_REL || S->Type == ELF::SHT_RELA;
265278 }
266279 };
267280
270283 const SectionBase *StrTab = nullptr;
271284
272285 public:
273 SectionWithStrTab(llvm::ArrayRef Data) : Section(Data) {}
286 SectionWithStrTab(ArrayRef Data) : Section(Data) {}
287
274288 void setStrTab(const SectionBase *StringTable) { StrTab = StringTable; }
275289 void removeSectionReferences(const SectionBase *Sec) override;
276290 void initialize(SectionTableRef SecTable) override;
280294
281295 class DynamicSymbolTableSection : public SectionWithStrTab {
282296 public:
283 DynamicSymbolTableSection(llvm::ArrayRef Data)
284 : SectionWithStrTab(Data) {}
285 static bool classof(const SectionBase *S) {
286 return S->Type == llvm::ELF::SHT_DYNSYM;
297 DynamicSymbolTableSection(ArrayRef Data) : SectionWithStrTab(Data) {}
298
299 static bool classof(const SectionBase *S) {
300 return S->Type == ELF::SHT_DYNSYM;
287301 }
288302 };
289303
290304 class DynamicSection : public SectionWithStrTab {
291305 public:
292 DynamicSection(llvm::ArrayRef Data) : SectionWithStrTab(Data) {}
293 static bool classof(const SectionBase *S) {
294 return S->Type == llvm::ELF::SHT_DYNAMIC;
306 DynamicSection(ArrayRef Data) : SectionWithStrTab(Data) {}
307
308 static bool classof(const SectionBase *S) {
309 return S->Type == ELF::SHT_DYNAMIC;
295310 }
296311 };
297312
298313 class DynamicRelocationSection
299314 : public RelocSectionWithSymtabBase {
300315 private:
301 llvm::ArrayRef Contents;
302
303 public:
304 DynamicRelocationSection(llvm::ArrayRef Data) : Contents(Data) {}
305 void writeSection(llvm::FileOutputBuffer &Out) const override;
306 static bool classof(const SectionBase *S) {
307 if (!(S->Flags & llvm::ELF::SHF_ALLOC))
316 ArrayRef Contents;
317
318 public:
319 DynamicRelocationSection(ArrayRef Data) : Contents(Data) {}
320
321 void writeSection(FileOutputBuffer &Out) const override;
322
323 static bool classof(const SectionBase *S) {
324 if (!(S->Flags & ELF::SHF_ALLOC))
308325 return false;
309 return S->Type == llvm::ELF::SHT_REL || S->Type == llvm::ELF::SHT_RELA;
326 return S->Type == ELF::SHT_REL || S->Type == ELF::SHT_RELA;
310327 }
311328 };
312329
313330 template class Object {
314331 private:
315 typedef std::unique_ptr SecPtr;
316 typedef std::unique_ptr SegPtr;
317
318 typedef typename ELFT::Shdr Elf_Shdr;
319 typedef typename ELFT::Ehdr Elf_Ehdr;
320 typedef typename ELFT::Phdr Elf_Phdr;
321
322 void initSymbolTable(const llvm::object::ELFFile &ElfFile,
332 using SecPtr = std::unique_ptr;
333 using SegPtr = std::unique_ptr;
334
335 using Elf_Shdr = typename ELFT::Shdr;
336 using Elf_Ehdr = typename ELFT::Ehdr;
337 using Elf_Phdr = typename ELFT::Phdr;
338
339 void initSymbolTable(const object::ELFFile &ElfFile,
323340 SymbolTableSection *SymTab, SectionTableRef SecTable);
324 SecPtr makeSection(const llvm::object::ELFFile &ElfFile,
341 SecPtr makeSection(const object::ELFFile &ElfFile,
325342 const Elf_Shdr &Shdr);
326 void readProgramHeaders(const llvm::object::ELFFile &ElfFile);
327 SectionTableRef readSectionHeaders(const llvm::object::ELFFile &ElfFile);
343 void readProgramHeaders(const object::ELFFile &ElfFile);
344 SectionTableRef readSectionHeaders(const object::ELFFile &ElfFile);
328345
329346 protected:
330347 StringTableSection *SectionNames = nullptr;
332349 std::vector Sections;
333350 std::vector Segments;
334351
335 void writeHeader(llvm::FileOutputBuffer &Out) const;
336 void writeProgramHeaders(llvm::FileOutputBuffer &Out) const;
337 void writeSectionData(llvm::FileOutputBuffer &Out) const;
338 void writeSectionHeaders(llvm::FileOutputBuffer &Out) const;
352 void writeHeader(FileOutputBuffer &Out) const;
353 void writeProgramHeaders(FileOutputBuffer &Out) const;
354 void writeSectionData(FileOutputBuffer &Out) const;
355 void writeSectionHeaders(FileOutputBuffer &Out) const;
339356
340357 public:
341358 uint8_t Ident[16];
347364 uint32_t Flags;
348365 bool WriteSectionHeaders = true;
349366
350 Object(const llvm::object::ELFObjectFile &Obj);
367 Object(const object::ELFObjectFile &Obj);
368 virtual ~Object() = default;
369
351370 void removeSections(std::function ToRemove);
352371 virtual size_t totalSize() const = 0;
353372 virtual void finalize() = 0;
354 virtual void write(llvm::FileOutputBuffer &Out) const = 0;
355 virtual ~Object() = default;
373 virtual void write(FileOutputBuffer &Out) const = 0;
356374 };
357375
358376 template class ELFObject : public Object {
359377 private:
360 typedef std::unique_ptr SecPtr;
361 typedef std::unique_ptr SegPtr;
362
363 typedef typename ELFT::Shdr Elf_Shdr;
364 typedef typename ELFT::Ehdr Elf_Ehdr;
365 typedef typename ELFT::Phdr Elf_Phdr;
378 using SecPtr = std::unique_ptr;
379 using SegPtr = std::unique_ptr;
380
381 using Elf_Shdr = typename ELFT::Shdr;
382 using Elf_Ehdr = typename ELFT::Ehdr;
383 using Elf_Phdr = typename ELFT::Phdr;
366384
367385 void sortSections();
368386 void assignOffsets();
369387
370388 public:
371 ELFObject(const llvm::object::ELFObjectFile &Obj) : Object(Obj) {}
389 ELFObject(const object::ELFObjectFile &Obj) : Object(Obj) {}
390
372391 void finalize() override;
373392 size_t totalSize() const override;
374 void write(llvm::FileOutputBuffer &Out) const override;
393 void write(FileOutputBuffer &Out) const override;
375394 };
376395
377396 template class BinaryObject : public Object {
378397 private:
379 typedef std::unique_ptr SecPtr;
380 typedef std::unique_ptr SegPtr;
398 using SecPtr = std::unique_ptr;
399 using SegPtr = std::unique_ptr;
381400
382401 uint64_t TotalSize;
383402
384403 public:
385 BinaryObject(const llvm::object::ELFObjectFile &Obj)
386 : Object(Obj) {}
404 BinaryObject(const object::ELFObjectFile &Obj) : Object(Obj) {}
405
387406 void finalize() override;
388407 size_t totalSize() const override;
389 void write(llvm::FileOutputBuffer &Out) const override;
390 };
391 #endif
408 void write(FileOutputBuffer &Out) const override;
409 };
410
411 } // end namespace llvm
412
413 #endif // LLVM_TOOLS_OBJCOPY_OBJECT_H
None //===- llvm-objcopy.cpp -----------------------------------------*- C++ -*-===//
0 //===- llvm-objcopy.cpp ---------------------------------------------------===//
11 //
22 // The LLVM Compiler Infrastructure
33 //
55 // License. See LICENSE.TXT for details.
66 //
77 //===----------------------------------------------------------------------===//
8
89 #include "llvm-objcopy.h"
910 #include "Object.h"
11 #include "llvm/ADT/STLExtras.h"
12 #include "llvm/ADT/StringRef.h"
13 #include "llvm/ADT/Twine.h"
14 #include "llvm/BinaryFormat/ELF.h"
15 #include "llvm/Object/Binary.h"
16 #include "llvm/Object/ELFObjectFile.h"
17 #include "llvm/Object/ELFTypes.h"
18 #include "llvm/Object/Error.h"
19 #include "llvm/Support/Casting.h"
1020 #include "llvm/Support/CommandLine.h"
21 #include "llvm/Support/Compiler.h"
22 #include "llvm/Support/Error.h"
23 #include "llvm/Support/ErrorHandling.h"
24 #include "llvm/Support/ErrorOr.h"
1125 #include "llvm/Support/FileOutputBuffer.h"
26 #include "llvm/Support/ManagedStatic.h"
1227 #include "llvm/Support/PrettyStackTrace.h"
1328 #include "llvm/Support/Signals.h"
14 #include "llvm/Support/ToolOutputFile.h"
15
29 #include "llvm/Support/raw_ostream.h"
30 #include
31 #include
32 #include
33 #include
34 #include
1635 #include
1736 #include
1837 #include
38 #include
1939
2040 using namespace llvm;
2141 using namespace object;
3858 exit(1);
3959 }
4060
41 LLVM_ATTRIBUTE_NORETURN void reportError(StringRef File, llvm::Error E) {
61 LLVM_ATTRIBUTE_NORETURN void reportError(StringRef File, Error E) {
4262 assert(E);
4363 std::string Buf;
4464 raw_string_ostream OS(Buf);
4767 errs() << ToolName << ": '" << File << "': " << Buf;
4868 exit(1);
4969 }
50 }
5170
52 cl::opt InputFilename(cl::Positional, cl::desc(""));
53 cl::opt OutputFilename(cl::Positional, cl::desc(""),
71 } // end namespace llvm
72
73 static cl::opt InputFilename(cl::Positional, cl::desc(""));
74 static cl::opt OutputFilename(cl::Positional, cl::desc(""),
5475 cl::init("-"));
55 cl::opt
76 static cl::opt
5677 OutputFormat("O", cl::desc("set output format to one of the following:"
5778 "\n\tbinary"));
58 cl::list ToRemove("remove-section",
59 cl::desc("Remove a specific section"));
60 cl::alias ToRemoveA("R", cl::desc("Alias for remove-section"),
61 cl::aliasopt(ToRemove));
62 cl::opt StripSections("strip-sections",
63 cl::desc("Remove all section headers"));
79 static cl::list ToRemove("remove-section",
80 cl::desc("Remove a specific section"));
81 static cl::alias ToRemoveA("R", cl::desc("Alias for remove-section"),
82 cl::aliasopt(ToRemove));
83 static cl::opt StripSections("strip-sections",
84 cl::desc("Remove all section headers"));
6485
65 typedef std::function SectionPred;
86 using SectionPred = std::function;
6687
6788 void CopyBinary(const ELFObjectFile &ObjFile) {
6889 std::unique_ptr Buffer;
55 // License. See LICENSE.TXT for details.
66 //
77 //===----------------------------------------------------------------------===//
8 #ifndef LLVM_OBJCOPY_H
9 #define LLVM_OBJCOPY_H
8
9 #ifndef LLVM_TOOLS_OBJCOPY_OBJCOPY_H
10 #define LLVM_TOOLS_OBJCOPY_OBJCOPY_H
1011
1112 #include "llvm/ADT/Twine.h"
13 #include "llvm/Support/Compiler.h"
1214 #include "llvm/Support/Error.h"
15 #include "llvm/Support/raw_ostream.h"
16 #include
1317
1418 namespace llvm {
1519
2630 OS.flush();
2731 error(Buf);
2832 }
29 }
3033
31 #endif
34 } // end namespace llvm
35
36 #endif // LLVM_TOOLS_OBJCOPY_OBJCOPY_H