xref: /llvm-project-15.0.7/lld/COFF/Chunks.cpp (revision 95213c31)
1 //===- Chunks.cpp ---------------------------------------------------------===//
2 //
3 //                             The LLVM Linker
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "Chunks.h"
11 #include "InputFiles.h"
12 #include "Writer.h"
13 #include "llvm/ADT/STLExtras.h"
14 #include "llvm/Object/COFF.h"
15 #include "llvm/Support/COFF.h"
16 #include "llvm/Support/Debug.h"
17 #include "llvm/Support/Endian.h"
18 #include "llvm/Support/raw_ostream.h"
19 
20 using namespace llvm;
21 using namespace llvm::object;
22 using namespace llvm::support::endian;
23 using namespace llvm::COFF;
24 using llvm::RoundUpToAlignment;
25 
26 namespace lld {
27 namespace coff {
28 
29 SectionChunk::SectionChunk(ObjectFile *F, const coff_section *H, uint32_t SI)
30     : File(F), Header(H), SectionIndex(SI) {
31   // Initialize SectionName.
32   File->getCOFFObj()->getSectionName(Header, SectionName);
33 
34   // Bit [20:24] contains section alignment.
35   unsigned Shift = ((Header->Characteristics & 0xF00000) >> 20) - 1;
36   Align = uint32_t(1) << Shift;
37 
38   // When a new chunk is created, we don't if if it's going to make it
39   // to the final output. Initially all sections are unmarked in terms
40   // of garbage collection. The writer will call markLive() to mark
41   // all reachable section chunks.
42   Live = false;
43 
44   // COMDAT sections are not GC root. Non-text sections are not
45   // subject of garbage collection (thus they are root).
46   if (!isCOMDAT() && !(Header->Characteristics & IMAGE_SCN_CNT_CODE))
47     Root = true;
48 }
49 
50 void SectionChunk::writeTo(uint8_t *Buf) {
51   if (!hasData())
52     return;
53   // Copy section contents from source object file to output file.
54   ArrayRef<uint8_t> Data;
55   File->getCOFFObj()->getSectionContents(Header, Data);
56   memcpy(Buf + FileOff, Data.data(), Data.size());
57 
58   // Apply relocations.
59   for (const auto &I : getSectionRef().relocations()) {
60     const coff_relocation *Rel = File->getCOFFObj()->getCOFFRelocation(I);
61     applyReloc(Buf, Rel);
62   }
63 }
64 
65 void SectionChunk::mark() {
66   if (Live)
67     return;
68   Live = true;
69 
70   // Mark all symbols listed in the relocation table for this section.
71   for (const auto &I : getSectionRef().relocations()) {
72     const coff_relocation *Rel = File->getCOFFObj()->getCOFFRelocation(I);
73     SymbolBody *B = File->getSymbolBody(Rel->SymbolTableIndex);
74     if (auto *Def = dyn_cast<Defined>(B))
75       Def->markLive();
76   }
77 
78   // Mark associative sections if any.
79   for (Chunk *C : AssocChildren)
80     C->markLive();
81 }
82 
83 void SectionChunk::addAssociative(SectionChunk *Child) {
84   AssocChildren.push_back(Child);
85   // Associative sections are live if their parent COMDATs are live,
86   // and vice versa, so they are not considered live by themselves.
87   Child->Root = false;
88 }
89 
90 static void add16(uint8_t *P, int16_t V) { write16le(P, read16le(P) + V); }
91 static void add32(uint8_t *P, int32_t V) { write32le(P, read32le(P) + V); }
92 static void add64(uint8_t *P, int64_t V) { write64le(P, read64le(P) + V); }
93 
94 // Implements x64 PE/COFF relocations.
95 void SectionChunk::applyReloc(uint8_t *Buf, const coff_relocation *Rel) {
96   uint8_t *Off = Buf + FileOff + Rel->VirtualAddress;
97   SymbolBody *Body = File->getSymbolBody(Rel->SymbolTableIndex);
98   uint64_t S = cast<Defined>(Body)->getRVA();
99   uint64_t P = RVA + Rel->VirtualAddress;
100   switch (Rel->Type) {
101   case IMAGE_REL_AMD64_ADDR32:   add32(Off, S + Config->ImageBase); break;
102   case IMAGE_REL_AMD64_ADDR64:   add64(Off, S + Config->ImageBase); break;
103   case IMAGE_REL_AMD64_ADDR32NB: add32(Off, S); break;
104   case IMAGE_REL_AMD64_REL32:    add32(Off, S - P - 4); break;
105   case IMAGE_REL_AMD64_REL32_1:  add32(Off, S - P - 5); break;
106   case IMAGE_REL_AMD64_REL32_2:  add32(Off, S - P - 6); break;
107   case IMAGE_REL_AMD64_REL32_3:  add32(Off, S - P - 7); break;
108   case IMAGE_REL_AMD64_REL32_4:  add32(Off, S - P - 8); break;
109   case IMAGE_REL_AMD64_REL32_5:  add32(Off, S - P - 9); break;
110   case IMAGE_REL_AMD64_SECTION:  add16(Off, Out->getSectionIndex()); break;
111   case IMAGE_REL_AMD64_SECREL:   add32(Off, S - Out->getRVA()); break;
112   default:
113     llvm::report_fatal_error("Unsupported relocation type");
114   }
115 }
116 
117 bool SectionChunk::hasData() const {
118   return !(Header->Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA);
119 }
120 
121 uint32_t SectionChunk::getPermissions() const {
122   return Header->Characteristics & PermMask;
123 }
124 
125 bool SectionChunk::isCOMDAT() const {
126   return Header->Characteristics & IMAGE_SCN_LNK_COMDAT;
127 }
128 
129 // Prints "Discarded <symbol>" for all external function symbols.
130 void SectionChunk::printDiscardedMessage() {
131   uint32_t E = File->getCOFFObj()->getNumberOfSymbols();
132   for (uint32_t I = 0; I < E; ++I) {
133     auto SrefOrErr = File->getCOFFObj()->getSymbol(I);
134     COFFSymbolRef Sym = SrefOrErr.get();
135     if (uint32_t(Sym.getSectionNumber()) != SectionIndex)
136       continue;
137     if (!Sym.isFunctionDefinition())
138       continue;
139     StringRef SymbolName;
140     File->getCOFFObj()->getSymbolName(Sym, SymbolName);
141     llvm::outs() << "Discarded " << SymbolName << " from "
142                  << File->getShortName() << "\n";
143     I += Sym.getNumberOfAuxSymbols();
144   }
145 }
146 
147 SectionRef SectionChunk::getSectionRef() {
148   DataRefImpl Ref;
149   Ref.p = uintptr_t(Header);
150   return SectionRef(Ref, File->getCOFFObj());
151 }
152 
153 CommonChunk::CommonChunk(const COFFSymbolRef S) : Sym(S) {
154   // Alignment is a section attribute, but common symbols don't
155   // belong to any section. How do we know common data alignments?
156   // Needs investigating. For now, we set a large number as an alignment.
157   Align = 16;
158 }
159 
160 uint32_t CommonChunk::getPermissions() const {
161   return IMAGE_SCN_CNT_UNINITIALIZED_DATA | IMAGE_SCN_MEM_READ |
162          IMAGE_SCN_MEM_WRITE;
163 }
164 
165 void StringChunk::writeTo(uint8_t *Buf) {
166   memcpy(Buf + FileOff, Str.data(), Str.size());
167 }
168 
169 void ImportThunkChunk::writeTo(uint8_t *Buf) {
170   memcpy(Buf + FileOff, ImportThunkData, sizeof(ImportThunkData));
171   // The first two bytes is a JMP instruction. Fill its operand.
172   uint32_t Operand = ImpSymbol->getRVA() - RVA - getSize();
173   write32le(Buf + FileOff + 2, Operand);
174 }
175 
176 } // namespace coff
177 } // namespace lld
178