blob: 84854ab70516653ad8ae2c2babdedf88e602eb48 [file] [log] [blame]
Rui Ueyama411c63602015-05-28 19:09:30 +00001//===- 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"
Rui Ueyamaddf71fc2015-06-24 04:36:52 +000013#include "llvm/ADT/Hashing.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000014#include "llvm/ADT/STLExtras.h"
15#include "llvm/Object/COFF.h"
16#include "llvm/Support/COFF.h"
17#include "llvm/Support/Debug.h"
18#include "llvm/Support/Endian.h"
19#include "llvm/Support/raw_ostream.h"
Rui Ueyama5e31d0b2015-06-20 07:25:45 +000020#include <algorithm>
Rui Ueyama411c63602015-05-28 19:09:30 +000021
Rui Ueyamac6ea0572015-06-06 22:46:15 +000022using namespace llvm;
Rui Ueyama411c63602015-05-28 19:09:30 +000023using namespace llvm::object;
24using namespace llvm::support::endian;
25using namespace llvm::COFF;
Rui Ueyama411c63602015-05-28 19:09:30 +000026
27namespace lld {
28namespace coff {
29
Peter Collingbournebd3a29d2015-06-24 00:12:36 +000030SectionChunk::SectionChunk(ObjectFile *F, const coff_section *H)
Rui Ueyamaddf71fc2015-06-24 04:36:52 +000031 : File(F), Ptr(this), Header(H) {
Rui Ueyama411c63602015-05-28 19:09:30 +000032 // Initialize SectionName.
33 File->getCOFFObj()->getSectionName(Header, SectionName);
Rui Ueyama8b33f592015-06-10 04:21:47 +000034
Rui Ueyama2bf6a122015-06-14 21:50:50 +000035 // Bit [20:24] contains section alignment. Both 0 and 1 mean alignment 1.
36 unsigned Shift = (Header->Characteristics >> 20) & 0xF;
37 if (Shift > 0)
38 Align = uint32_t(1) << (Shift - 1);
Rui Ueyama8b33f592015-06-10 04:21:47 +000039
40 // When a new chunk is created, we don't if if it's going to make it
41 // to the final output. Initially all sections are unmarked in terms
42 // of garbage collection. The writer will call markLive() to mark
43 // all reachable section chunks.
44 Live = false;
45
46 // COMDAT sections are not GC root. Non-text sections are not
47 // subject of garbage collection (thus they are root).
48 if (!isCOMDAT() && !(Header->Characteristics & IMAGE_SCN_CNT_CODE))
49 Root = true;
Rui Ueyama411c63602015-05-28 19:09:30 +000050}
51
Rui Ueyamad6fefba42015-05-28 19:45:43 +000052void SectionChunk::writeTo(uint8_t *Buf) {
Rui Ueyama9aefa0c2015-05-28 20:04:51 +000053 if (!hasData())
54 return;
Rui Ueyama743afa02015-06-06 04:07:39 +000055 // Copy section contents from source object file to output file.
Rui Ueyama411c63602015-05-28 19:09:30 +000056 ArrayRef<uint8_t> Data;
57 File->getCOFFObj()->getSectionContents(Header, Data);
Rui Ueyamad6fefba42015-05-28 19:45:43 +000058 memcpy(Buf + FileOff, Data.data(), Data.size());
Rui Ueyama743afa02015-06-06 04:07:39 +000059
60 // Apply relocations.
61 for (const auto &I : getSectionRef().relocations()) {
62 const coff_relocation *Rel = File->getCOFFObj()->getCOFFRelocation(I);
63 applyReloc(Buf, Rel);
64 }
Rui Ueyama411c63602015-05-28 19:09:30 +000065}
66
Rui Ueyama8b33f592015-06-10 04:21:47 +000067void SectionChunk::mark() {
Rui Ueyama4108f3f2015-06-14 22:01:39 +000068 assert(!Live);
Rui Ueyama411c63602015-05-28 19:09:30 +000069 Live = true;
70
71 // Mark all symbols listed in the relocation table for this section.
72 for (const auto &I : getSectionRef().relocations()) {
73 const coff_relocation *Rel = File->getCOFFObj()->getCOFFRelocation(I);
74 SymbolBody *B = File->getSymbolBody(Rel->SymbolTableIndex);
75 if (auto *Def = dyn_cast<Defined>(B))
76 Def->markLive();
77 }
78
79 // Mark associative sections if any.
80 for (Chunk *C : AssocChildren)
81 C->markLive();
82}
83
84void SectionChunk::addAssociative(SectionChunk *Child) {
Rui Ueyama411c63602015-05-28 19:09:30 +000085 AssocChildren.push_back(Child);
Rui Ueyama8b33f592015-06-10 04:21:47 +000086 // Associative sections are live if their parent COMDATs are live,
87 // and vice versa, so they are not considered live by themselves.
88 Child->Root = false;
Rui Ueyama411c63602015-05-28 19:09:30 +000089}
90
Rui Ueyamaa6cd6c02015-06-07 23:10:50 +000091static void add16(uint8_t *P, int16_t V) { write16le(P, read16le(P) + V); }
Rui Ueyama411c63602015-05-28 19:09:30 +000092static void add32(uint8_t *P, int32_t V) { write32le(P, read32le(P) + V); }
93static void add64(uint8_t *P, int64_t V) { write64le(P, read64le(P) + V); }
94
95// Implements x64 PE/COFF relocations.
96void SectionChunk::applyReloc(uint8_t *Buf, const coff_relocation *Rel) {
Rui Ueyama411c63602015-05-28 19:09:30 +000097 uint8_t *Off = Buf + FileOff + Rel->VirtualAddress;
98 SymbolBody *Body = File->getSymbolBody(Rel->SymbolTableIndex);
99 uint64_t S = cast<Defined>(Body)->getRVA();
100 uint64_t P = RVA + Rel->VirtualAddress;
101 switch (Rel->Type) {
102 case IMAGE_REL_AMD64_ADDR32: add32(Off, S + Config->ImageBase); break;
103 case IMAGE_REL_AMD64_ADDR64: add64(Off, S + Config->ImageBase); break;
104 case IMAGE_REL_AMD64_ADDR32NB: add32(Off, S); break;
105 case IMAGE_REL_AMD64_REL32: add32(Off, S - P - 4); break;
106 case IMAGE_REL_AMD64_REL32_1: add32(Off, S - P - 5); break;
107 case IMAGE_REL_AMD64_REL32_2: add32(Off, S - P - 6); break;
108 case IMAGE_REL_AMD64_REL32_3: add32(Off, S - P - 7); break;
109 case IMAGE_REL_AMD64_REL32_4: add32(Off, S - P - 8); break;
110 case IMAGE_REL_AMD64_REL32_5: add32(Off, S - P - 9); break;
111 case IMAGE_REL_AMD64_SECTION: add16(Off, Out->getSectionIndex()); break;
112 case IMAGE_REL_AMD64_SECREL: add32(Off, S - Out->getRVA()); break;
113 default:
114 llvm::report_fatal_error("Unsupported relocation type");
115 }
116}
117
Rui Ueyama588e8322015-06-15 01:23:58 +0000118// Windows-specific.
119// Collect all locations that contain absolute 64-bit addresses,
120// which need to be fixed by the loader if load-time relocation is needed.
121// Only called when base relocation is enabled.
122void SectionChunk::getBaserels(std::vector<uint32_t> *Res, Defined *ImageBase) {
123 for (const auto &I : getSectionRef().relocations()) {
124 // ADDR64 relocations contain absolute addresses.
125 // Symbol __ImageBase is special -- it's an absolute symbol, but its
126 // address never changes even if image is relocated.
127 const coff_relocation *Rel = File->getCOFFObj()->getCOFFRelocation(I);
128 if (Rel->Type != IMAGE_REL_AMD64_ADDR64)
129 continue;
130 SymbolBody *Body = File->getSymbolBody(Rel->SymbolTableIndex);
131 if (Body == ImageBase)
132 continue;
133 Res->push_back(RVA + Rel->VirtualAddress);
134 }
135}
136
Rui Ueyama411c63602015-05-28 19:09:30 +0000137bool SectionChunk::hasData() const {
138 return !(Header->Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA);
139}
140
141uint32_t SectionChunk::getPermissions() const {
142 return Header->Characteristics & PermMask;
143}
144
145bool SectionChunk::isCOMDAT() const {
146 return Header->Characteristics & IMAGE_SCN_LNK_COMDAT;
147}
148
Rui Ueyama411c63602015-05-28 19:09:30 +0000149void SectionChunk::printDiscardedMessage() {
Rui Ueyamaddf71fc2015-06-24 04:36:52 +0000150 if (this == Ptr) {
151 // Removed by dead-stripping.
152 llvm::dbgs() << "Discarded " << Sym->getName() << "\n";
153 } else {
154 // Removed by ICF.
155 llvm::dbgs() << "Replaced " << Sym->getName() << "\n";
156 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000157}
158
Rui Ueyamaddf71fc2015-06-24 04:36:52 +0000159SectionRef SectionChunk::getSectionRef() const {
Rui Ueyama411c63602015-05-28 19:09:30 +0000160 DataRefImpl Ref;
161 Ref.p = uintptr_t(Header);
162 return SectionRef(Ref, File->getCOFFObj());
163}
164
Rui Ueyama6a60be72015-06-24 00:00:52 +0000165StringRef SectionChunk::getDebugName() {
166 return Sym->getName();
167}
168
Rui Ueyamaddf71fc2015-06-24 04:36:52 +0000169uint64_t SectionChunk::getHash() const {
170 ArrayRef<uint8_t> A;
171 File->getCOFFObj()->getSectionContents(Header, A);
172 return hash_combine(getPermissions(), llvm::hash_value(SectionName),
173 uint32_t(Header->SizeOfRawData),
174 uint32_t(Header->NumberOfRelocations),
175 hash_combine_range(A.data(), A.data() + A.size()));
176}
177
178// Returns true if this and a given chunk are identical COMDAT sections.
179bool SectionChunk::equals(const SectionChunk *X) const {
180 // Compare headers
181 if (getPermissions() != X->getPermissions())
182 return false;
183 if (SectionName != X->SectionName)
184 return false;
185 if (Header->SizeOfRawData != X->Header->SizeOfRawData)
186 return false;
187 if (Header->NumberOfRelocations != X->Header->NumberOfRelocations)
188 return false;
189
190 // Compare data
191 ArrayRef<uint8_t> A, B;
192 File->getCOFFObj()->getSectionContents(Header, A);
193 X->File->getCOFFObj()->getSectionContents(X->Header, B);
194 assert(A.size() == B.size());
195 if (memcmp(A.data(), B.data(), A.size()))
196 return false;
197
198 // Compare relocations
199 auto Range1 = getSectionRef().relocations();
200 auto Range2 = X->getSectionRef().relocations();
201 auto End = Range1.end();
202 for (auto I = Range1.begin(), J = Range2.begin(); I != End; ++I, ++J) {
203 const coff_relocation *Rel1 = File->getCOFFObj()->getCOFFRelocation(*I);
204 const coff_relocation *Rel2 = X->File->getCOFFObj()->getCOFFRelocation(*J);
205 if (Rel1->Type != Rel2->Type)
206 return false;
207 if (Rel1->VirtualAddress != Rel2->VirtualAddress)
208 return false;
209 SymbolBody *B1 = File->getSymbolBody(Rel1->SymbolTableIndex);
210 SymbolBody *B2 = X->File->getSymbolBody(Rel2->SymbolTableIndex);
211 if (auto *C1 = dyn_cast<DefinedCOMDAT>(B1))
212 if (auto *C2 = dyn_cast<DefinedCOMDAT>(B2))
213 if (C1->getChunk() == C2->getChunk())
214 continue;
215 if (B1 != B2)
216 return false;
217 }
218 return true;
219}
220
221// Returns a pointer to this chunk or its replacement.
222SectionChunk *SectionChunk::repl() {
223 while (Ptr != Ptr->Ptr)
224 Ptr = Ptr->Ptr;
225 return Ptr;
226}
227
228void SectionChunk::replaceWith(SectionChunk *Other) {
229 Ptr = Other;
230 Live = false;
231}
232
Rui Ueyama9cf1abb2015-06-08 03:17:07 +0000233CommonChunk::CommonChunk(const COFFSymbolRef S) : Sym(S) {
Rui Ueyama5e31d0b2015-06-20 07:25:45 +0000234 // Common symbols are aligned on natural boundaries up to 32 bytes.
235 // This is what MSVC link.exe does.
236 Align = std::min(uint64_t(32), NextPowerOf2(Sym.getValue()));
Rui Ueyama9cf1abb2015-06-08 03:17:07 +0000237}
238
Rui Ueyama411c63602015-05-28 19:09:30 +0000239uint32_t CommonChunk::getPermissions() const {
Rui Ueyama411c63602015-05-28 19:09:30 +0000240 return IMAGE_SCN_CNT_UNINITIALIZED_DATA | IMAGE_SCN_MEM_READ |
241 IMAGE_SCN_MEM_WRITE;
242}
243
Rui Ueyamad6fefba42015-05-28 19:45:43 +0000244void StringChunk::writeTo(uint8_t *Buf) {
245 memcpy(Buf + FileOff, Str.data(), Str.size());
246}
247
248void ImportThunkChunk::writeTo(uint8_t *Buf) {
249 memcpy(Buf + FileOff, ImportThunkData, sizeof(ImportThunkData));
Rui Ueyama743afa02015-06-06 04:07:39 +0000250 // The first two bytes is a JMP instruction. Fill its operand.
Rui Ueyama411c63602015-05-28 19:09:30 +0000251 uint32_t Operand = ImpSymbol->getRVA() - RVA - getSize();
Rui Ueyama411c63602015-05-28 19:09:30 +0000252 write32le(Buf + FileOff + 2, Operand);
253}
254
Rui Ueyama588e8322015-06-15 01:23:58 +0000255// Windows-specific.
256// This class represents a block in .reloc section.
257BaserelChunk::BaserelChunk(uint32_t Page, uint32_t *Begin, uint32_t *End) {
258 // Block header consists of 4 byte page RVA and 4 byte block size.
259 // Each entry is 2 byte. Last entry may be padding.
260 Data.resize(RoundUpToAlignment((End - Begin) * 2 + 8, 4));
261 uint8_t *P = Data.data();
262 write32le(P, Page);
263 write32le(P + 4, Data.size());
264 P += 8;
265 for (uint32_t *I = Begin; I != End; ++I) {
266 write16le(P, (IMAGE_REL_BASED_DIR64 << 12) | (*I - Page));
267 P += 2;
268 }
269}
270
271void BaserelChunk::writeTo(uint8_t *Buf) {
272 memcpy(Buf + FileOff, Data.data(), Data.size());
273}
274
Rui Ueyama411c63602015-05-28 19:09:30 +0000275} // namespace coff
276} // namespace lld