]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm-project/lld/COFF/InputFiles.h
Merge ^/vendor/lld/dist up to its last change, and resolve conflicts.
[FreeBSD/FreeBSD.git] / contrib / llvm-project / lld / COFF / InputFiles.h
1 //===- InputFiles.h ---------------------------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8
9 #ifndef LLD_COFF_INPUT_FILES_H
10 #define LLD_COFF_INPUT_FILES_H
11
12 #include "Config.h"
13 #include "lld/Common/DWARF.h"
14 #include "lld/Common/LLVM.h"
15 #include "llvm/ADT/ArrayRef.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/DenseSet.h"
18 #include "llvm/BinaryFormat/Magic.h"
19 #include "llvm/DebugInfo/CodeView/TypeRecord.h"
20 #include "llvm/LTO/LTO.h"
21 #include "llvm/Object/Archive.h"
22 #include "llvm/Object/COFF.h"
23 #include "llvm/Support/StringSaver.h"
24 #include <memory>
25 #include <set>
26 #include <vector>
27
28 namespace llvm {
29 struct DILineInfo;
30 namespace pdb {
31 class DbiModuleDescriptorBuilder;
32 }
33 }
34
35 namespace lld {
36 namespace coff {
37
38 std::vector<MemoryBufferRef> getArchiveMembers(llvm::object::Archive *file);
39
40 using llvm::COFF::IMAGE_FILE_MACHINE_UNKNOWN;
41 using llvm::COFF::MachineTypes;
42 using llvm::object::Archive;
43 using llvm::object::COFFObjectFile;
44 using llvm::object::COFFSymbolRef;
45 using llvm::object::coff_import_header;
46 using llvm::object::coff_section;
47
48 class Chunk;
49 class Defined;
50 class DefinedImportData;
51 class DefinedImportThunk;
52 class DefinedRegular;
53 class SectionChunk;
54 class Symbol;
55 class Undefined;
56 class TpiSource;
57
58 // The root class of input files.
59 class InputFile {
60 public:
61   enum Kind {
62     ArchiveKind,
63     ObjectKind,
64     LazyObjectKind,
65     ImportKind,
66     BitcodeKind
67   };
68   Kind kind() const { return fileKind; }
69   virtual ~InputFile() {}
70
71   // Returns the filename.
72   StringRef getName() const { return mb.getBufferIdentifier(); }
73
74   // Reads a file (the constructor doesn't do that).
75   virtual void parse() = 0;
76
77   // Returns the CPU type this file was compiled to.
78   virtual MachineTypes getMachineType() { return IMAGE_FILE_MACHINE_UNKNOWN; }
79
80   MemoryBufferRef mb;
81
82   // An archive file name if this file is created from an archive.
83   StringRef parentName;
84
85   // Returns .drectve section contents if exist.
86   StringRef getDirectives() { return directives; }
87
88 protected:
89   InputFile(Kind k, MemoryBufferRef m) : mb(m), fileKind(k) {}
90
91   StringRef directives;
92
93 private:
94   const Kind fileKind;
95 };
96
97 // .lib or .a file.
98 class ArchiveFile : public InputFile {
99 public:
100   explicit ArchiveFile(MemoryBufferRef m);
101   static bool classof(const InputFile *f) { return f->kind() == ArchiveKind; }
102   void parse() override;
103
104   // Enqueues an archive member load for the given symbol. If we've already
105   // enqueued a load for the same archive member, this function does nothing,
106   // which ensures that we don't load the same member more than once.
107   void addMember(const Archive::Symbol &sym);
108
109 private:
110   std::unique_ptr<Archive> file;
111   llvm::DenseSet<uint64_t> seen;
112 };
113
114 // .obj or .o file between -start-lib and -end-lib.
115 class LazyObjFile : public InputFile {
116 public:
117   explicit LazyObjFile(MemoryBufferRef m) : InputFile(LazyObjectKind, m) {}
118   static bool classof(const InputFile *f) {
119     return f->kind() == LazyObjectKind;
120   }
121   // Makes this object file part of the link.
122   void fetch();
123   // Adds the symbols in this file to the symbol table as LazyObject symbols.
124   void parse() override;
125
126 private:
127   std::vector<Symbol *> symbols;
128 };
129
130 // .obj or .o file. This may be a member of an archive file.
131 class ObjFile : public InputFile {
132 public:
133   explicit ObjFile(MemoryBufferRef m) : InputFile(ObjectKind, m) {}
134   explicit ObjFile(MemoryBufferRef m, std::vector<Symbol *> &&symbols)
135       : InputFile(ObjectKind, m), symbols(std::move(symbols)) {}
136   static bool classof(const InputFile *f) { return f->kind() == ObjectKind; }
137   void parse() override;
138   MachineTypes getMachineType() override;
139   ArrayRef<Chunk *> getChunks() { return chunks; }
140   ArrayRef<SectionChunk *> getDebugChunks() { return debugChunks; }
141   ArrayRef<SectionChunk *> getSXDataChunks() { return sXDataChunks; }
142   ArrayRef<SectionChunk *> getGuardFidChunks() { return guardFidChunks; }
143   ArrayRef<SectionChunk *> getGuardLJmpChunks() { return guardLJmpChunks; }
144   ArrayRef<Symbol *> getSymbols() { return symbols; }
145
146   ArrayRef<uint8_t> getDebugSection(StringRef secName);
147
148   // Returns a Symbol object for the symbolIndex'th symbol in the
149   // underlying object file.
150   Symbol *getSymbol(uint32_t symbolIndex) {
151     return symbols[symbolIndex];
152   }
153
154   // Returns the underlying COFF file.
155   COFFObjectFile *getCOFFObj() { return coffObj.get(); }
156
157   // Add a symbol for a range extension thunk. Return the new symbol table
158   // index. This index can be used to modify a relocation.
159   uint32_t addRangeThunkSymbol(Symbol *thunk) {
160     symbols.push_back(thunk);
161     return symbols.size() - 1;
162   }
163
164   void includeResourceChunks();
165
166   bool isResourceObjFile() const { return !resourceChunks.empty(); }
167
168   static std::vector<ObjFile *> instances;
169
170   // Flags in the absolute @feat.00 symbol if it is present. These usually
171   // indicate if an object was compiled with certain security features enabled
172   // like stack guard, safeseh, /guard:cf, or other things.
173   uint32_t feat00Flags = 0;
174
175   // True if this object file is compatible with SEH.  COFF-specific and
176   // x86-only. COFF spec 5.10.1. The .sxdata section.
177   bool hasSafeSEH() { return feat00Flags & 0x1; }
178
179   // True if this file was compiled with /guard:cf.
180   bool hasGuardCF() { return feat00Flags & 0x800; }
181
182   // Pointer to the PDB module descriptor builder. Various debug info records
183   // will reference object files by "module index", which is here. Things like
184   // source files and section contributions are also recorded here. Will be null
185   // if we are not producing a PDB.
186   llvm::pdb::DbiModuleDescriptorBuilder *moduleDBI = nullptr;
187
188   const coff_section *addrsigSec = nullptr;
189
190   // When using Microsoft precompiled headers, this is the PCH's key.
191   // The same key is used by both the precompiled object, and objects using the
192   // precompiled object. Any difference indicates out-of-date objects.
193   llvm::Optional<uint32_t> pchSignature;
194
195   // Whether this file was compiled with /hotpatch.
196   bool hotPatchable = false;
197
198   // Whether the object was already merged into the final PDB.
199   bool mergedIntoPDB = false;
200
201   // If the OBJ has a .debug$T stream, this tells how it will be handled.
202   TpiSource *debugTypesObj = nullptr;
203
204   // The .debug$T stream if there's one.
205   llvm::Optional<llvm::codeview::CVTypeArray> debugTypes;
206
207   llvm::Optional<std::pair<StringRef, uint32_t>>
208   getVariableLocation(StringRef var);
209
210   llvm::Optional<llvm::DILineInfo> getDILineInfo(uint32_t offset,
211                                                  uint32_t sectionIndex);
212
213 private:
214   const coff_section* getSection(uint32_t i);
215   const coff_section *getSection(COFFSymbolRef sym) {
216     return getSection(sym.getSectionNumber());
217   }
218
219   void initializeChunks();
220   void initializeSymbols();
221   void initializeFlags();
222   void initializeDependencies();
223
224   SectionChunk *
225   readSection(uint32_t sectionNumber,
226               const llvm::object::coff_aux_section_definition *def,
227               StringRef leaderName);
228
229   void readAssociativeDefinition(
230       COFFSymbolRef coffSym,
231       const llvm::object::coff_aux_section_definition *def);
232
233   void readAssociativeDefinition(
234       COFFSymbolRef coffSym,
235       const llvm::object::coff_aux_section_definition *def,
236       uint32_t parentSection);
237
238   void recordPrevailingSymbolForMingw(
239       COFFSymbolRef coffSym,
240       llvm::DenseMap<StringRef, uint32_t> &prevailingSectionMap);
241
242   void maybeAssociateSEHForMingw(
243       COFFSymbolRef sym, const llvm::object::coff_aux_section_definition *def,
244       const llvm::DenseMap<StringRef, uint32_t> &prevailingSectionMap);
245
246   // Given a new symbol Sym with comdat selection Selection, if the new
247   // symbol is not (yet) Prevailing and the existing comdat leader set to
248   // Leader, emits a diagnostic if the new symbol and its selection doesn't
249   // match the existing symbol and its selection. If either old or new
250   // symbol have selection IMAGE_COMDAT_SELECT_LARGEST, Sym might replace
251   // the existing leader. In that case, Prevailing is set to true.
252   void handleComdatSelection(COFFSymbolRef sym,
253                              llvm::COFF::COMDATType &selection,
254                              bool &prevailing, DefinedRegular *leader);
255
256   llvm::Optional<Symbol *>
257   createDefined(COFFSymbolRef sym,
258                 std::vector<const llvm::object::coff_aux_section_definition *>
259                     &comdatDefs,
260                 bool &prevailingComdat);
261   Symbol *createRegular(COFFSymbolRef sym);
262   Symbol *createUndefined(COFFSymbolRef sym);
263
264   std::unique_ptr<COFFObjectFile> coffObj;
265
266   // List of all chunks defined by this file. This includes both section
267   // chunks and non-section chunks for common symbols.
268   std::vector<Chunk *> chunks;
269
270   std::vector<SectionChunk *> resourceChunks;
271
272   // CodeView debug info sections.
273   std::vector<SectionChunk *> debugChunks;
274
275   // Chunks containing symbol table indices of exception handlers. Only used for
276   // 32-bit x86.
277   std::vector<SectionChunk *> sXDataChunks;
278
279   // Chunks containing symbol table indices of address taken symbols and longjmp
280   // targets.  These are not linked into the final binary when /guard:cf is set.
281   std::vector<SectionChunk *> guardFidChunks;
282   std::vector<SectionChunk *> guardLJmpChunks;
283
284   // This vector contains the same chunks as Chunks, but they are
285   // indexed such that you can get a SectionChunk by section index.
286   // Nonexistent section indices are filled with null pointers.
287   // (Because section number is 1-based, the first slot is always a
288   // null pointer.)
289   std::vector<SectionChunk *> sparseChunks;
290
291   // This vector contains a list of all symbols defined or referenced by this
292   // file. They are indexed such that you can get a Symbol by symbol
293   // index. Nonexistent indices (which are occupied by auxiliary
294   // symbols in the real symbol table) are filled with null pointers.
295   std::vector<Symbol *> symbols;
296
297   DWARFCache *dwarf = nullptr;
298 };
299
300 // This type represents import library members that contain DLL names
301 // and symbols exported from the DLLs. See Microsoft PE/COFF spec. 7
302 // for details about the format.
303 class ImportFile : public InputFile {
304 public:
305   explicit ImportFile(MemoryBufferRef m) : InputFile(ImportKind, m) {}
306
307   static bool classof(const InputFile *f) { return f->kind() == ImportKind; }
308
309   static std::vector<ImportFile *> instances;
310
311   Symbol *impSym = nullptr;
312   Symbol *thunkSym = nullptr;
313   std::string dllName;
314
315 private:
316   void parse() override;
317
318 public:
319   StringRef externalName;
320   const coff_import_header *hdr;
321   Chunk *location = nullptr;
322
323   // We want to eliminate dllimported symbols if no one actually refers them.
324   // These "Live" bits are used to keep track of which import library members
325   // are actually in use.
326   //
327   // If the Live bit is turned off by MarkLive, Writer will ignore dllimported
328   // symbols provided by this import library member. We also track whether the
329   // imported symbol is used separately from whether the thunk is used in order
330   // to avoid creating unnecessary thunks.
331   bool live = !config->doGC;
332   bool thunkLive = !config->doGC;
333 };
334
335 // Used for LTO.
336 class BitcodeFile : public InputFile {
337 public:
338   BitcodeFile(MemoryBufferRef mb, StringRef archiveName,
339               uint64_t offsetInArchive)
340       : BitcodeFile(mb, archiveName, offsetInArchive, {}) {}
341   explicit BitcodeFile(MemoryBufferRef m, StringRef archiveName,
342                        uint64_t offsetInArchive,
343                        std::vector<Symbol *> &&symbols);
344   static bool classof(const InputFile *f) { return f->kind() == BitcodeKind; }
345   ArrayRef<Symbol *> getSymbols() { return symbols; }
346   MachineTypes getMachineType() override;
347   static std::vector<BitcodeFile *> instances;
348   std::unique_ptr<llvm::lto::InputFile> obj;
349
350 private:
351   void parse() override;
352
353   std::vector<Symbol *> symbols;
354 };
355
356 inline bool isBitcode(MemoryBufferRef mb) {
357   return identify_magic(mb.getBuffer()) == llvm::file_magic::bitcode;
358 }
359
360 std::string replaceThinLTOSuffix(StringRef path);
361 } // namespace coff
362
363 std::string toString(const coff::InputFile *file);
364 } // namespace lld
365
366 #endif