blob: 372471faf846b376afd323d927630c45d27f59bc [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 Ueyama411c63602015-05-28 19:09:30 +000013#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
Rui Ueyamac6ea0572015-06-06 22:46:15 +000020using namespace llvm;
Rui Ueyama411c63602015-05-28 19:09:30 +000021using namespace llvm::object;
22using namespace llvm::support::endian;
23using namespace llvm::COFF;
24using llvm::RoundUpToAlignment;
25
26namespace lld {
27namespace coff {
28
Rui Ueyamac6ea0572015-06-06 22:46:15 +000029const size_t LookupChunk::Size = sizeof(uint64_t);
30const size_t DirectoryChunk::Size = sizeof(ImportDirectoryTableEntry);
31
Rui Ueyama411c63602015-05-28 19:09:30 +000032SectionChunk::SectionChunk(ObjectFile *F, const coff_section *H, uint32_t SI)
33 : File(F), Header(H), SectionIndex(SI) {
34 // Initialize SectionName.
35 File->getCOFFObj()->getSectionName(Header, SectionName);
36 // Bit [20:24] contains section alignment.
37 unsigned Shift = ((Header->Characteristics & 0xF00000) >> 20) - 1;
38 Align = uint32_t(1) << Shift;
39}
40
Rui Ueyamad6fefba42015-05-28 19:45:43 +000041void SectionChunk::writeTo(uint8_t *Buf) {
Rui Ueyama9aefa0c2015-05-28 20:04:51 +000042 if (!hasData())
43 return;
Rui Ueyama743afa02015-06-06 04:07:39 +000044 // Copy section contents from source object file to output file.
Rui Ueyama411c63602015-05-28 19:09:30 +000045 ArrayRef<uint8_t> Data;
46 File->getCOFFObj()->getSectionContents(Header, Data);
Rui Ueyamad6fefba42015-05-28 19:45:43 +000047 memcpy(Buf + FileOff, Data.data(), Data.size());
Rui Ueyama743afa02015-06-06 04:07:39 +000048
49 // Apply relocations.
50 for (const auto &I : getSectionRef().relocations()) {
51 const coff_relocation *Rel = File->getCOFFObj()->getCOFFRelocation(I);
52 applyReloc(Buf, Rel);
53 }
Rui Ueyama411c63602015-05-28 19:09:30 +000054}
55
56// Returns true if this chunk should be considered as a GC root.
57bool SectionChunk::isRoot() {
58 // COMDAT sections are live only when they are referenced by something else.
59 if (isCOMDAT())
60 return false;
61
62 // Associative sections are live if their parent COMDATs are live,
63 // and vice versa, so they are not considered live by themselves.
64 if (IsAssocChild)
65 return false;
66
67 // Only code is subject of dead-stripping.
68 return !(Header->Characteristics & IMAGE_SCN_CNT_CODE);
69}
70
71void SectionChunk::markLive() {
72 if (Live)
73 return;
74 Live = true;
75
76 // Mark all symbols listed in the relocation table for this section.
77 for (const auto &I : getSectionRef().relocations()) {
78 const coff_relocation *Rel = File->getCOFFObj()->getCOFFRelocation(I);
79 SymbolBody *B = File->getSymbolBody(Rel->SymbolTableIndex);
80 if (auto *Def = dyn_cast<Defined>(B))
81 Def->markLive();
82 }
83
84 // Mark associative sections if any.
85 for (Chunk *C : AssocChildren)
86 C->markLive();
87}
88
89void SectionChunk::addAssociative(SectionChunk *Child) {
90 Child->IsAssocChild = true;
91 AssocChildren.push_back(Child);
92}
93
Rui Ueyama411c63602015-05-28 19:09:30 +000094static void add16(uint8_t *P, int32_t V) { write16le(P, read16le(P) + V); }
95static void add32(uint8_t *P, int32_t V) { write32le(P, read32le(P) + V); }
96static void add64(uint8_t *P, int64_t V) { write64le(P, read64le(P) + V); }
97
98// Implements x64 PE/COFF relocations.
99void SectionChunk::applyReloc(uint8_t *Buf, const coff_relocation *Rel) {
100 using namespace llvm::COFF;
101 uint8_t *Off = Buf + FileOff + Rel->VirtualAddress;
102 SymbolBody *Body = File->getSymbolBody(Rel->SymbolTableIndex);
103 uint64_t S = cast<Defined>(Body)->getRVA();
104 uint64_t P = RVA + Rel->VirtualAddress;
105 switch (Rel->Type) {
106 case IMAGE_REL_AMD64_ADDR32: add32(Off, S + Config->ImageBase); break;
107 case IMAGE_REL_AMD64_ADDR64: add64(Off, S + Config->ImageBase); break;
108 case IMAGE_REL_AMD64_ADDR32NB: add32(Off, S); break;
109 case IMAGE_REL_AMD64_REL32: add32(Off, S - P - 4); break;
110 case IMAGE_REL_AMD64_REL32_1: add32(Off, S - P - 5); break;
111 case IMAGE_REL_AMD64_REL32_2: add32(Off, S - P - 6); break;
112 case IMAGE_REL_AMD64_REL32_3: add32(Off, S - P - 7); break;
113 case IMAGE_REL_AMD64_REL32_4: add32(Off, S - P - 8); break;
114 case IMAGE_REL_AMD64_REL32_5: add32(Off, S - P - 9); break;
115 case IMAGE_REL_AMD64_SECTION: add16(Off, Out->getSectionIndex()); break;
116 case IMAGE_REL_AMD64_SECREL: add32(Off, S - Out->getRVA()); break;
117 default:
118 llvm::report_fatal_error("Unsupported relocation type");
119 }
120}
121
122bool SectionChunk::hasData() const {
123 return !(Header->Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA);
124}
125
126uint32_t SectionChunk::getPermissions() const {
127 return Header->Characteristics & PermMask;
128}
129
130bool SectionChunk::isCOMDAT() const {
131 return Header->Characteristics & IMAGE_SCN_LNK_COMDAT;
132}
133
134// Prints "Discarded <symbol>" for all external function symbols.
135void SectionChunk::printDiscardedMessage() {
136 uint32_t E = File->getCOFFObj()->getNumberOfSymbols();
137 for (uint32_t I = 0; I < E; ++I) {
138 auto SrefOrErr = File->getCOFFObj()->getSymbol(I);
139 COFFSymbolRef Sym = SrefOrErr.get();
140 if (uint32_t(Sym.getSectionNumber()) != SectionIndex)
141 continue;
142 if (!Sym.isFunctionDefinition())
143 continue;
144 StringRef SymbolName;
145 File->getCOFFObj()->getSymbolName(Sym, SymbolName);
146 llvm::dbgs() << "Discarded " << SymbolName << " from "
147 << File->getShortName() << "\n";
148 I += Sym.getNumberOfAuxSymbols();
149 }
150}
151
152SectionRef SectionChunk::getSectionRef() {
153 DataRefImpl Ref;
154 Ref.p = uintptr_t(Header);
155 return SectionRef(Ref, File->getCOFFObj());
156}
157
158uint32_t CommonChunk::getPermissions() const {
159 using namespace llvm::COFF;
160 return IMAGE_SCN_CNT_UNINITIALIZED_DATA | IMAGE_SCN_MEM_READ |
161 IMAGE_SCN_MEM_WRITE;
162}
163
Rui Ueyamad6fefba42015-05-28 19:45:43 +0000164void StringChunk::writeTo(uint8_t *Buf) {
165 memcpy(Buf + FileOff, Str.data(), Str.size());
166}
167
168void ImportThunkChunk::writeTo(uint8_t *Buf) {
169 memcpy(Buf + FileOff, ImportThunkData, sizeof(ImportThunkData));
Rui Ueyama743afa02015-06-06 04:07:39 +0000170 // The first two bytes is a JMP instruction. Fill its operand.
Rui Ueyama411c63602015-05-28 19:09:30 +0000171 uint32_t Operand = ImpSymbol->getRVA() - RVA - getSize();
Rui Ueyama411c63602015-05-28 19:09:30 +0000172 write32le(Buf + FileOff + 2, Operand);
173}
174
Rui Ueyama5b25edd2015-06-01 03:55:04 +0000175size_t HintNameChunk::getSize() const {
176 // Starts with 2 byte Hint field, followed by a null-terminated string,
177 // ends with 0 or 1 byte padding.
178 return RoundUpToAlignment(Name.size() + 3, 2);
179}
Rui Ueyamad6fefba42015-05-28 19:45:43 +0000180
181void HintNameChunk::writeTo(uint8_t *Buf) {
Rui Ueyamac9bfe322015-05-29 15:45:35 +0000182 write16le(Buf + FileOff, Hint);
Rui Ueyamad6fefba42015-05-28 19:45:43 +0000183 memcpy(Buf + FileOff + 2, Name.data(), Name.size());
Rui Ueyama411c63602015-05-28 19:09:30 +0000184}
185
Rui Ueyama743afa02015-06-06 04:07:39 +0000186void LookupChunk::writeTo(uint8_t *Buf) {
Rui Ueyama411c63602015-05-28 19:09:30 +0000187 write32le(Buf + FileOff, HintName->getRVA());
188}
189
Rui Ueyamafd99e012015-06-01 21:05:27 +0000190void OrdinalOnlyChunk::writeTo(uint8_t *Buf) {
191 // An import-by-ordinal slot has MSB 1 to indicate that
192 // this is import-by-ordinal (and not import-by-name).
193 write64le(Buf + FileOff, (uint64_t(1) << 63) | Ordinal);
194}
195
Rui Ueyama743afa02015-06-06 04:07:39 +0000196void DirectoryChunk::writeTo(uint8_t *Buf) {
Rui Ueyama411c63602015-05-28 19:09:30 +0000197 auto *E = (coff_import_directory_table_entry *)(Buf + FileOff);
198 E->ImportLookupTableRVA = LookupTab->getRVA();
199 E->NameRVA = DLLName->getRVA();
200 E->ImportAddressTableRVA = AddressTab->getRVA();
201}
202
Rui Ueyamac6ea0572015-06-06 22:46:15 +0000203// Returns a list of .idata contents.
204// See Microsoft PE/COFF spec 5.4 for details.
205std::vector<Chunk *> IdataContents::getChunks() {
206 create();
207 std::vector<Chunk *> V;
208 // The loader assumes a specific order of data.
209 // Add each type in the correct order.
210 for (std::unique_ptr<Chunk> &C : Dirs)
211 V.push_back(C.get());
212 for (std::unique_ptr<Chunk> &C : Lookups)
213 V.push_back(C.get());
214 for (std::unique_ptr<Chunk> &C : Addresses)
215 V.push_back(C.get());
216 for (std::unique_ptr<Chunk> &C : Hints)
217 V.push_back(C.get());
218 for (auto &P : DLLNames) {
219 std::unique_ptr<Chunk> &C = P.second;
220 V.push_back(C.get());
Rui Ueyama411c63602015-05-28 19:09:30 +0000221 }
Rui Ueyamac6ea0572015-06-06 22:46:15 +0000222 return V;
223}
224
225void IdataContents::create() {
226 // Group DLL-imported symbols by DLL name because that's how
227 // symbols are layed out in the import descriptor table.
228 std::map<StringRef, std::vector<DefinedImportData *>> Map;
229 for (DefinedImportData *Sym : Imports)
230 Map[Sym->getDLLName()].push_back(Sym);
231
232 // Create .idata contents for each DLL.
233 for (auto &P : Map) {
234 StringRef Name = P.first;
235 std::vector<DefinedImportData *> &Syms = P.second;
236
237 // Sort symbols by name for each group.
238 std::sort(Syms.begin(), Syms.end(),
239 [](DefinedImportData *A, DefinedImportData *B) {
240 return A->getName() < B->getName();
241 });
242
243 // Create lookup and address tables. If they have external names,
244 // we need to create HintName chunks to store the names.
245 // If they don't (if they are import-by-ordinals), we store only
246 // ordinal values to the table.
247 size_t Base = Lookups.size();
248 for (DefinedImportData *S : Syms) {
249 uint16_t Ord = S->getOrdinal();
250 if (S->getExternalName().empty()) {
251 Lookups.push_back(make_unique<OrdinalOnlyChunk>(Ord));
252 Addresses.push_back(make_unique<OrdinalOnlyChunk>(Ord));
253 continue;
254 }
255 auto C = make_unique<HintNameChunk>(S->getExternalName(), Ord);
256 Lookups.push_back(make_unique<LookupChunk>(C.get()));
257 Addresses.push_back(make_unique<LookupChunk>(C.get()));
258 Hints.push_back(std::move(C));
259 }
260 // Terminate with null values.
261 Lookups.push_back(make_unique<NullChunk>(sizeof(uint64_t)));
262 Addresses.push_back(make_unique<NullChunk>(sizeof(uint64_t)));
263
264 for (int I = 0, E = Syms.size(); I < E; ++I)
265 Syms[I]->setLocation(Addresses[Base + I].get());
266
267 // Create the import table header.
268 if (!DLLNames.count(Name))
269 DLLNames[Name] = make_unique<StringChunk>(Name);
270 auto Dir = make_unique<DirectoryChunk>(DLLNames[Name].get());
271 Dir->LookupTab = Lookups[Base].get();
272 Dir->AddressTab = Addresses[Base].get();
273 Dirs.push_back(std::move(Dir));
274 }
275 // Add null terminator.
276 Dirs.push_back(make_unique<NullChunk>(DirectoryChunk::Size));
Rui Ueyama411c63602015-05-28 19:09:30 +0000277}
278
279} // namespace coff
280} // namespace lld