1 //===- Chunks.h -------------------------------------------------*- C++ -*-===//
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #ifndef LLD_COFF_CHUNKS_H
11 #define LLD_COFF_CHUNKS_H
14 #include "InputFiles.h"
15 #include "lld/Common/LLVM.h"
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/ADT/iterator.h"
18 #include "llvm/ADT/iterator_range.h"
19 #include "llvm/MC/StringTableBuilder.h"
20 #include "llvm/Object/COFF.h"
27 using llvm::COFF::ImportDirectoryTableEntry;
28 using llvm::object::COFFSymbolRef;
29 using llvm::object::SectionRef;
30 using llvm::object::coff_relocation;
31 using llvm::object::coff_section;
35 class DefinedImportData;
41 // Mask for permissions (discardable, writable, readable, executable, etc).
42 const uint32_t PermMask = 0xFE000000;
44 // Mask for section types (code, data, bss).
45 const uint32_t TypeMask = 0x000000E0;
47 // A Chunk represents a chunk of data that will occupy space in the
48 // output (if the resolver chose that). It may or may not be backed by
49 // a section of an input file. It could be linker-created data, or
50 // doesn't even have actual data (if common or bss).
53 enum Kind { SectionKind, OtherKind };
54 Kind kind() const { return ChunkKind; }
55 virtual ~Chunk() = default;
57 // Returns the size of this chunk (even if this is a common or BSS.)
58 virtual size_t getSize() const = 0;
60 // Write this chunk to a mmap'ed file, assuming Buf is pointing to
61 // beginning of the file. Because this function may use RVA values
62 // of other chunks for relocations, you need to set them properly
63 // before calling this function.
64 virtual void writeTo(uint8_t *Buf) const {}
66 // Called by the writer after an RVA is assigned, but before calling
68 virtual void finalizeContents() {}
70 // The writer sets and uses the addresses.
71 uint64_t getRVA() const { return RVA; }
72 void setRVA(uint64_t V) { RVA = V; }
74 // Returns true if this has non-zero data. BSS chunks return
75 // false. If false is returned, the space occupied by this chunk
76 // will be filled with zeros.
77 virtual bool hasData() const { return true; }
79 // Returns readable/writable/executable bits.
80 virtual uint32_t getOutputCharacteristics() const { return 0; }
82 // Returns the section name if this is a section chunk.
83 // It is illegal to call this function on non-section chunks.
84 virtual StringRef getSectionName() const {
85 llvm_unreachable("unimplemented getSectionName");
88 // An output section has pointers to chunks in the section, and each
89 // chunk has a back pointer to an output section.
90 void setOutputSection(OutputSection *O) { Out = O; }
91 OutputSection *getOutputSection() const { return Out; }
94 // Collect all locations that contain absolute addresses for base relocations.
95 virtual void getBaserels(std::vector<Baserel> *Res) {}
97 // Returns a human-readable name of this chunk. Chunks are unnamed chunks of
98 // bytes, so this is used only for logging or debugging.
99 virtual StringRef getDebugName() { return ""; }
101 // The alignment of this chunk. The writer uses the value.
102 uint32_t Alignment = 1;
105 Chunk(Kind K = OtherKind) : ChunkKind(K) {}
106 const Kind ChunkKind;
108 // The RVA of this chunk in the output. The writer sets a value.
111 // The output section for this chunk.
112 OutputSection *Out = nullptr;
115 // The offset from beginning of the output section. The writer sets a value.
116 uint64_t OutputSectionOff = 0;
119 // A chunk corresponding a section of an input file.
120 class SectionChunk final : public Chunk {
121 // Identical COMDAT Folding feature accesses section internal data.
125 class symbol_iterator : public llvm::iterator_adaptor_base<
126 symbol_iterator, const coff_relocation *,
127 std::random_access_iterator_tag, Symbol *> {
132 symbol_iterator(ObjFile *File, const coff_relocation *I)
133 : symbol_iterator::iterator_adaptor_base(I), File(File) {}
136 symbol_iterator() = default;
138 Symbol *operator*() const { return File->getSymbol(I->SymbolTableIndex); }
141 SectionChunk(ObjFile *File, const coff_section *Header);
142 static bool classof(const Chunk *C) { return C->kind() == SectionKind; }
143 size_t getSize() const override { return Header->SizeOfRawData; }
144 ArrayRef<uint8_t> getContents() const;
145 void writeTo(uint8_t *Buf) const override;
146 bool hasData() const override;
147 uint32_t getOutputCharacteristics() const override;
148 StringRef getSectionName() const override { return SectionName; }
149 void getBaserels(std::vector<Baserel> *Res) override;
150 bool isCOMDAT() const;
151 void applyRelX64(uint8_t *Off, uint16_t Type, OutputSection *OS, uint64_t S,
153 void applyRelX86(uint8_t *Off, uint16_t Type, OutputSection *OS, uint64_t S,
155 void applyRelARM(uint8_t *Off, uint16_t Type, OutputSection *OS, uint64_t S,
157 void applyRelARM64(uint8_t *Off, uint16_t Type, OutputSection *OS, uint64_t S,
160 // Called if the garbage collector decides to not include this chunk
161 // in a final output. It's supposed to print out a log message to stdout.
162 void printDiscardedMessage() const;
164 // Adds COMDAT associative sections to this COMDAT section. A chunk
165 // and its children are treated as a group by the garbage collector.
166 void addAssociative(SectionChunk *Child);
168 StringRef getDebugName() override;
170 // Returns true if the chunk was not dropped by GC.
171 bool isLive() { return Live; }
173 // Used by the garbage collector.
175 assert(Config->DoGC && "should only mark things live from GC");
176 assert(!isLive() && "Cannot mark an already live section!");
180 // True if this is a codeview debug info chunk. These will not be laid out in
181 // the image. Instead they will end up in the PDB, if one is requested.
182 bool isCodeView() const {
183 return SectionName == ".debug" || SectionName.startswith(".debug$");
186 // True if this is a DWARF debug info or exception handling chunk.
187 bool isDWARF() const {
188 return SectionName.startswith(".debug_") || SectionName == ".eh_frame";
191 // Allow iteration over the bodies of this chunk's relocated symbols.
192 llvm::iterator_range<symbol_iterator> symbols() const {
193 return llvm::make_range(symbol_iterator(File, Relocs.begin()),
194 symbol_iterator(File, Relocs.end()));
197 // Allow iteration over the associated child chunks for this section.
198 ArrayRef<SectionChunk *> children() const { return AssocChildren; }
200 // A pointer pointing to a replacement for this chunk.
201 // Initially it points to "this" object. If this chunk is merged
202 // with other chunk by ICF, it points to another chunk,
203 // and this chunk is considrered as dead.
206 // The CRC of the contents as described in the COFF spec 4.5.5.
207 // Auxiliary Format 5: Section Definitions. Used for ICF.
208 uint32_t Checksum = 0;
210 const coff_section *Header;
212 // The file that this chunk was created from.
215 // The COMDAT leader symbol if this is a COMDAT chunk.
216 DefinedRegular *Sym = nullptr;
218 ArrayRef<coff_relocation> Relocs;
221 StringRef SectionName;
222 std::vector<SectionChunk *> AssocChildren;
224 // Used by the garbage collector.
227 // Used for ICF (Identical COMDAT Folding)
228 void replace(SectionChunk *Other);
229 uint32_t Class[2] = {0, 0};
232 // This class is used to implement an lld-specific feature (not implemented in
233 // MSVC) that minimizes the output size by finding string literals sharing tail
234 // parts and merging them.
236 // If string tail merging is enabled and a section is identified as containing a
237 // string literal, it is added to a MergeChunk with an appropriate alignment.
238 // The MergeChunk then tail merges the strings using the StringTableBuilder
239 // class and assigns RVAs and section offsets to each of the member chunks based
240 // on the offsets assigned by the StringTableBuilder.
241 class MergeChunk : public Chunk {
243 MergeChunk(uint32_t Alignment);
244 static void addSection(SectionChunk *C);
245 void finalizeContents() override;
247 uint32_t getOutputCharacteristics() const override;
248 StringRef getSectionName() const override { return ".rdata"; }
249 size_t getSize() const override;
250 void writeTo(uint8_t *Buf) const override;
252 static std::map<uint32_t, MergeChunk *> Instances;
253 std::vector<SectionChunk *> Sections;
256 llvm::StringTableBuilder Builder;
259 // A chunk for common symbols. Common chunks don't have actual data.
260 class CommonChunk : public Chunk {
262 CommonChunk(const COFFSymbolRef Sym);
263 size_t getSize() const override { return Sym.getValue(); }
264 bool hasData() const override { return false; }
265 uint32_t getOutputCharacteristics() const override;
266 StringRef getSectionName() const override { return ".bss"; }
269 const COFFSymbolRef Sym;
272 // A chunk for linker-created strings.
273 class StringChunk : public Chunk {
275 explicit StringChunk(StringRef S) : Str(S) {}
276 size_t getSize() const override { return Str.size() + 1; }
277 void writeTo(uint8_t *Buf) const override;
283 static const uint8_t ImportThunkX86[] = {
284 0xff, 0x25, 0x00, 0x00, 0x00, 0x00, // JMP *0x0
287 static const uint8_t ImportThunkARM[] = {
288 0x40, 0xf2, 0x00, 0x0c, // mov.w ip, #0
289 0xc0, 0xf2, 0x00, 0x0c, // mov.t ip, #0
290 0xdc, 0xf8, 0x00, 0xf0, // ldr.w pc, [ip]
293 static const uint8_t ImportThunkARM64[] = {
294 0x10, 0x00, 0x00, 0x90, // adrp x16, #0
295 0x10, 0x02, 0x40, 0xf9, // ldr x16, [x16]
296 0x00, 0x02, 0x1f, 0xd6, // br x16
300 // A chunk for DLL import jump table entry. In a final output, it's
301 // contents will be a JMP instruction to some __imp_ symbol.
302 class ImportThunkChunkX64 : public Chunk {
304 explicit ImportThunkChunkX64(Defined *S);
305 size_t getSize() const override { return sizeof(ImportThunkX86); }
306 void writeTo(uint8_t *Buf) const override;
312 class ImportThunkChunkX86 : public Chunk {
314 explicit ImportThunkChunkX86(Defined *S) : ImpSymbol(S) {}
315 size_t getSize() const override { return sizeof(ImportThunkX86); }
316 void getBaserels(std::vector<Baserel> *Res) override;
317 void writeTo(uint8_t *Buf) const override;
323 class ImportThunkChunkARM : public Chunk {
325 explicit ImportThunkChunkARM(Defined *S) : ImpSymbol(S) {}
326 size_t getSize() const override { return sizeof(ImportThunkARM); }
327 void getBaserels(std::vector<Baserel> *Res) override;
328 void writeTo(uint8_t *Buf) const override;
334 class ImportThunkChunkARM64 : public Chunk {
336 explicit ImportThunkChunkARM64(Defined *S) : ImpSymbol(S) {}
337 size_t getSize() const override { return sizeof(ImportThunkARM64); }
338 void writeTo(uint8_t *Buf) const override;
345 // See comments for DefinedLocalImport class.
346 class LocalImportChunk : public Chunk {
348 explicit LocalImportChunk(Defined *S) : Sym(S) {
349 Alignment = Config->is64() ? 8 : 4;
351 size_t getSize() const override;
352 void getBaserels(std::vector<Baserel> *Res) override;
353 void writeTo(uint8_t *Buf) const override;
359 // Duplicate RVAs are not allowed in RVA tables, so unique symbols by chunk and
360 // offset into the chunk. Order does not matter as the RVA table will be sorted
362 struct ChunkAndOffset {
366 struct DenseMapInfo {
367 static ChunkAndOffset getEmptyKey() {
368 return {llvm::DenseMapInfo<Chunk *>::getEmptyKey(), 0};
370 static ChunkAndOffset getTombstoneKey() {
371 return {llvm::DenseMapInfo<Chunk *>::getTombstoneKey(), 0};
373 static unsigned getHashValue(const ChunkAndOffset &CO) {
374 return llvm::DenseMapInfo<std::pair<Chunk *, uint32_t>>::getHashValue(
375 {CO.InputChunk, CO.Offset});
377 static bool isEqual(const ChunkAndOffset &LHS, const ChunkAndOffset &RHS) {
378 return LHS.InputChunk == RHS.InputChunk && LHS.Offset == RHS.Offset;
383 using SymbolRVASet = llvm::DenseSet<ChunkAndOffset>;
385 // Table which contains symbol RVAs. Used for /safeseh and /guard:cf.
386 class RVATableChunk : public Chunk {
388 explicit RVATableChunk(SymbolRVASet S) : Syms(std::move(S)) {}
389 size_t getSize() const override { return Syms.size() * 4; }
390 void writeTo(uint8_t *Buf) const override;
397 // This class represents a block in .reloc section.
398 // See the PE/COFF spec 5.6 for details.
399 class BaserelChunk : public Chunk {
401 BaserelChunk(uint32_t Page, Baserel *Begin, Baserel *End);
402 size_t getSize() const override { return Data.size(); }
403 void writeTo(uint8_t *Buf) const override;
406 std::vector<uint8_t> Data;
411 Baserel(uint32_t V, uint8_t Ty) : RVA(V), Type(Ty) {}
412 explicit Baserel(uint32_t V) : Baserel(V, getDefaultType()) {}
413 uint8_t getDefaultType();
419 void applyMOV32T(uint8_t *Off, uint32_t V);
420 void applyBranch24T(uint8_t *Off, int32_t V);
427 struct DenseMapInfo<lld::coff::ChunkAndOffset>
428 : lld::coff::ChunkAndOffset::DenseMapInfo {};