blob: 6bdfd4faa82649829c20a40a73335add75d68c06 [file] [log] [blame]
Rui Ueyama411c63602015-05-28 19:09:30 +00001//===- InputFiles.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"
Rui Ueyama8fd9fb92015-06-01 02:58:15 +000011#include "Error.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000012#include "InputFiles.h"
13#include "Writer.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000014#include "llvm/ADT/STLExtras.h"
Peter Collingbourne60c16162015-06-01 20:10:10 +000015#include "llvm/LTO/LTOModule.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000016#include "llvm/Object/COFF.h"
17#include "llvm/Support/COFF.h"
18#include "llvm/Support/Debug.h"
19#include "llvm/Support/Endian.h"
20#include "llvm/Support/raw_ostream.h"
Rui Ueyamaadcde532015-07-05 22:50:00 +000021#include <mutex>
Rui Ueyama411c63602015-05-28 19:09:30 +000022
23using namespace llvm::object;
24using namespace llvm::support::endian;
25using llvm::COFF::ImportHeader;
Rui Ueyama80141a42015-06-08 05:00:42 +000026using llvm::COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
Rui Ueyamaa2994882015-06-26 00:42:21 +000027using llvm::COFF::IMAGE_FILE_MACHINE_AMD64;
28using llvm::COFF::IMAGE_FILE_MACHINE_UNKNOWN;
Rui Ueyama411c63602015-05-28 19:09:30 +000029using llvm::RoundUpToAlignment;
30using llvm::sys::fs::identify_magic;
31using llvm::sys::fs::file_magic;
32
33namespace lld {
34namespace coff {
35
Rui Ueyama65813ed2015-07-02 20:33:48 +000036int InputFile::NextIndex = 0;
37
Rui Ueyama411c63602015-05-28 19:09:30 +000038// Returns the last element of a path, which is supposed to be a filename.
39static StringRef getBasename(StringRef Path) {
Rui Ueyamaea63a282015-06-18 20:16:26 +000040 size_t Pos = Path.find_last_of("\\/");
Rui Ueyama411c63602015-05-28 19:09:30 +000041 if (Pos == StringRef::npos)
42 return Path;
43 return Path.substr(Pos + 1);
44}
45
46// Returns a string in the format of "foo.obj" or "foo.obj(bar.lib)".
47std::string InputFile::getShortName() {
48 if (ParentName == "")
49 return getName().lower();
50 std::string Res = (getBasename(ParentName) + "(" +
51 getBasename(getName()) + ")").str();
52 return StringRef(Res).lower();
53}
54
55std::error_code ArchiveFile::parse() {
Rui Ueyamad7c2f582015-05-31 21:04:56 +000056 // Parse a MemoryBufferRef as an archive file.
57 auto ArchiveOrErr = Archive::create(MB);
Rui Ueyama411c63602015-05-28 19:09:30 +000058 if (auto EC = ArchiveOrErr.getError())
59 return EC;
60 File = std::move(ArchiveOrErr.get());
61
62 // Allocate a buffer for Lazy objects.
Rui Ueyama605e1f62015-06-26 23:51:45 +000063 size_t NumSyms = File->getNumberOfSymbols();
64 size_t BufSize = NumSyms * sizeof(Lazy);
Rui Ueyama411c63602015-05-28 19:09:30 +000065 Lazy *Buf = (Lazy *)Alloc.Allocate(BufSize, llvm::alignOf<Lazy>());
Rui Ueyama8d3010a2015-06-30 19:35:21 +000066 LazySymbols.reserve(NumSyms);
Rui Ueyama411c63602015-05-28 19:09:30 +000067
68 // Read the symbol table to construct Lazy objects.
69 uint32_t I = 0;
70 for (const Archive::Symbol &Sym : File->symbols()) {
Rui Ueyama29792a82015-06-19 21:25:44 +000071 auto *B = new (&Buf[I++]) Lazy(this, Sym);
Rui Ueyama411c63602015-05-28 19:09:30 +000072 // Skip special symbol exists in import library files.
Rui Ueyama29792a82015-06-19 21:25:44 +000073 if (B->getName() != "__NULL_IMPORT_DESCRIPTOR")
Rui Ueyama8d3010a2015-06-30 19:35:21 +000074 LazySymbols.push_back(B);
Rui Ueyama411c63602015-05-28 19:09:30 +000075 }
76 return std::error_code();
77}
78
79// Returns a buffer pointing to a member file containing a given symbol.
Rui Ueyamaadcde532015-07-05 22:50:00 +000080// This function is thread-safe.
Rui Ueyama411c63602015-05-28 19:09:30 +000081ErrorOr<MemoryBufferRef> ArchiveFile::getMember(const Archive::Symbol *Sym) {
Rui Ueyamaadcde532015-07-05 22:50:00 +000082 static std::mutex Mu;
Rui Ueyama411c63602015-05-28 19:09:30 +000083 auto ItOrErr = Sym->getMember();
84 if (auto EC = ItOrErr.getError())
85 return EC;
86 Archive::child_iterator It = ItOrErr.get();
87
88 // Return an empty buffer if we have already returned the same buffer.
89 const char *StartAddr = It->getBuffer().data();
Rui Ueyamaadcde532015-07-05 22:50:00 +000090 Mu.lock();
Rui Ueyama411c63602015-05-28 19:09:30 +000091 auto Pair = Seen.insert(StartAddr);
Rui Ueyamaadcde532015-07-05 22:50:00 +000092 Mu.unlock();
Rui Ueyama411c63602015-05-28 19:09:30 +000093 if (!Pair.second)
94 return MemoryBufferRef();
95 return It->getMemoryBufferRef();
96}
97
98std::error_code ObjectFile::parse() {
Rui Ueyama411c63602015-05-28 19:09:30 +000099 // Parse a memory buffer as a COFF file.
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000100 auto BinOrErr = createBinary(MB);
Rui Ueyama411c63602015-05-28 19:09:30 +0000101 if (auto EC = BinOrErr.getError())
102 return EC;
103 std::unique_ptr<Binary> Bin = std::move(BinOrErr.get());
104
105 if (auto *Obj = dyn_cast<COFFObjectFile>(Bin.get())) {
106 Bin.release();
107 COFFObj.reset(Obj);
108 } else {
Rui Ueyama8fd9fb92015-06-01 02:58:15 +0000109 llvm::errs() << getName() << " is not a COFF file.\n";
110 return make_error_code(LLDError::InvalidFile);
Rui Ueyama411c63602015-05-28 19:09:30 +0000111 }
Rui Ueyamaa2994882015-06-26 00:42:21 +0000112 if (COFFObj->getMachine() != IMAGE_FILE_MACHINE_AMD64 &&
113 COFFObj->getMachine() != IMAGE_FILE_MACHINE_UNKNOWN) {
114 llvm::errs() << getName() << " is not an x64 object file.\n";
115 return make_error_code(LLDError::InvalidFile);
116 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000117
118 // Read section and symbol tables.
119 if (auto EC = initializeChunks())
120 return EC;
121 return initializeSymbols();
122}
123
Rui Ueyama411c63602015-05-28 19:09:30 +0000124std::error_code ObjectFile::initializeChunks() {
125 uint32_t NumSections = COFFObj->getNumberOfSections();
126 Chunks.reserve(NumSections);
127 SparseChunks.resize(NumSections + 1);
128 for (uint32_t I = 1; I < NumSections + 1; ++I) {
129 const coff_section *Sec;
130 StringRef Name;
Rui Ueyama8fd9fb92015-06-01 02:58:15 +0000131 if (auto EC = COFFObj->getSection(I, Sec)) {
132 llvm::errs() << "getSection failed: " << Name << ": "
133 << EC.message() << "\n";
134 return make_error_code(LLDError::BrokenFile);
135 }
136 if (auto EC = COFFObj->getSectionName(Sec, Name)) {
137 llvm::errs() << "getSectionName failed: " << Name << ": "
138 << EC.message() << "\n";
139 return make_error_code(LLDError::BrokenFile);
140 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000141 if (Name == ".drectve") {
142 ArrayRef<uint8_t> Data;
143 COFFObj->getSectionContents(Sec, Data);
Rui Ueyama0569ecf2015-07-04 03:27:46 +0000144 Directives = std::string((const char *)Data.data(), Data.size());
Rui Ueyama411c63602015-05-28 19:09:30 +0000145 continue;
146 }
147 if (Name.startswith(".debug"))
148 continue;
149 if (Sec->Characteristics & llvm::COFF::IMAGE_SCN_LNK_REMOVE)
150 continue;
Peter Collingbournebd3a29d2015-06-24 00:12:36 +0000151 auto *C = new (Alloc) SectionChunk(this, Sec);
Rui Ueyama411c63602015-05-28 19:09:30 +0000152 Chunks.push_back(C);
153 SparseChunks[I] = C;
154 }
155 return std::error_code();
156}
157
158std::error_code ObjectFile::initializeSymbols() {
159 uint32_t NumSymbols = COFFObj->getNumberOfSymbols();
160 SymbolBodies.reserve(NumSymbols);
161 SparseSymbolBodies.resize(NumSymbols);
162 int32_t LastSectionNumber = 0;
163 for (uint32_t I = 0; I < NumSymbols; ++I) {
164 // Get a COFFSymbolRef object.
165 auto SymOrErr = COFFObj->getSymbol(I);
Rui Ueyama8fd9fb92015-06-01 02:58:15 +0000166 if (auto EC = SymOrErr.getError()) {
167 llvm::errs() << "broken object file: " << getName() << ": "
168 << EC.message() << "\n";
169 return make_error_code(LLDError::BrokenFile);
170 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000171 COFFSymbolRef Sym = SymOrErr.get();
172
Rui Ueyama411c63602015-05-28 19:09:30 +0000173 const void *AuxP = nullptr;
174 if (Sym.getNumberOfAuxSymbols())
175 AuxP = COFFObj->getSymbol(I + 1)->getRawPtr();
176 bool IsFirst = (LastSectionNumber != Sym.getSectionNumber());
177
Rui Ueyamadae16612015-06-29 22:16:21 +0000178 SymbolBody *Body = nullptr;
179 if (Sym.isUndefined()) {
180 Body = createUndefined(Sym);
181 } else if (Sym.isWeakExternal()) {
182 Body = createWeakExternal(Sym, AuxP);
183 } else {
184 Body = createDefined(Sym, AuxP, IsFirst);
185 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000186 if (Body) {
187 SymbolBodies.push_back(Body);
188 SparseSymbolBodies[I] = Body;
189 }
190 I += Sym.getNumberOfAuxSymbols();
191 LastSectionNumber = Sym.getSectionNumber();
192 }
193 return std::error_code();
194}
195
Rui Ueyamadae16612015-06-29 22:16:21 +0000196Undefined *ObjectFile::createUndefined(COFFSymbolRef Sym) {
Rui Ueyama57fe78d2015-06-08 19:43:59 +0000197 StringRef Name;
Rui Ueyamadae16612015-06-29 22:16:21 +0000198 COFFObj->getSymbolName(Sym, Name);
199 return new (Alloc) Undefined(Name);
200}
201
202Undefined *ObjectFile::createWeakExternal(COFFSymbolRef Sym, const void *AuxP) {
203 StringRef Name;
204 COFFObj->getSymbolName(Sym, Name);
Rui Ueyama48975962015-07-01 22:32:23 +0000205 auto *U = new (Alloc) Undefined(Name);
Rui Ueyamadae16612015-06-29 22:16:21 +0000206 auto *Aux = (const coff_aux_weak_external *)AuxP;
Peter Collingbourneda2f0942015-07-03 22:03:36 +0000207 U->WeakAlias = SparseSymbolBodies[Aux->TagIndex];
Rui Ueyama48975962015-07-01 22:32:23 +0000208 return U;
Rui Ueyamadae16612015-06-29 22:16:21 +0000209}
210
211Defined *ObjectFile::createDefined(COFFSymbolRef Sym, const void *AuxP,
212 bool IsFirst) {
213 StringRef Name;
Rui Ueyama411c63602015-05-28 19:09:30 +0000214 if (Sym.isCommon()) {
Rui Ueyamafc510f42015-06-25 19:10:58 +0000215 auto *C = new (Alloc) CommonChunk(Sym);
Rui Ueyama411c63602015-05-28 19:09:30 +0000216 Chunks.push_back(C);
Rui Ueyama68633f12015-06-25 23:22:00 +0000217 return new (Alloc) DefinedCommon(this, Sym, C);
Rui Ueyama411c63602015-05-28 19:09:30 +0000218 }
Rui Ueyama57fe78d2015-06-08 19:43:59 +0000219 if (Sym.isAbsolute()) {
220 COFFObj->getSymbolName(Sym, Name);
221 // Skip special symbols.
222 if (Name == "@comp.id" || Name == "@feat.00")
223 return nullptr;
Rui Ueyamaccde19d2015-06-26 03:09:23 +0000224 return new (Alloc) DefinedAbsolute(Name, Sym);
Rui Ueyama57fe78d2015-06-08 19:43:59 +0000225 }
Peter Collingbournec7b685d2015-06-24 00:05:50 +0000226 if (Sym.getSectionNumber() == llvm::COFF::IMAGE_SYM_DEBUG)
227 return nullptr;
Chandler Carruthee5bf522015-06-29 21:32:37 +0000228
229 // Nothing else to do without a section chunk.
230 auto *SC = cast_or_null<SectionChunk>(SparseChunks[Sym.getSectionNumber()]);
231 if (!SC)
232 return nullptr;
233
Rui Ueyama80141a42015-06-08 05:00:42 +0000234 // Handle associative sections
Rui Ueyama411c63602015-05-28 19:09:30 +0000235 if (IsFirst && AuxP) {
Chandler Carruthee5bf522015-06-29 21:32:37 +0000236 auto *Aux = reinterpret_cast<const coff_aux_section_definition *>(AuxP);
237 if (Aux->Selection == IMAGE_COMDAT_SELECT_ASSOCIATIVE)
238 if (auto *ParentSC = cast_or_null<SectionChunk>(
239 SparseChunks[Aux->getNumber(Sym.isBigObj())]))
240 ParentSC->addAssociative(SC);
Rui Ueyama411c63602015-05-28 19:09:30 +0000241 }
Chandler Carruthee5bf522015-06-29 21:32:37 +0000242
243 auto *B = new (Alloc) DefinedRegular(this, Sym, SC);
244 if (SC->isCOMDAT() && Sym.getValue() == 0 && !AuxP)
245 SC->setSymbol(B);
246
247 return B;
Rui Ueyama411c63602015-05-28 19:09:30 +0000248}
249
250std::error_code ImportFile::parse() {
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000251 const char *Buf = MB.getBufferStart();
252 const char *End = MB.getBufferEnd();
Rui Ueyama411c63602015-05-28 19:09:30 +0000253 const auto *Hdr = reinterpret_cast<const coff_import_header *>(Buf);
254
255 // Check if the total size is valid.
Denis Protivensky68336902015-06-01 09:26:32 +0000256 if ((size_t)(End - Buf) != (sizeof(*Hdr) + Hdr->SizeOfData)) {
Rui Ueyama8fd9fb92015-06-01 02:58:15 +0000257 llvm::errs() << "broken import library\n";
258 return make_error_code(LLDError::BrokenFile);
259 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000260
261 // Read names and create an __imp_ symbol.
262 StringRef Name = StringAlloc.save(StringRef(Buf + sizeof(*Hdr)));
263 StringRef ImpName = StringAlloc.save(Twine("__imp_") + Name);
264 StringRef DLLName(Buf + sizeof(coff_import_header) + Name.size() + 1);
Rui Ueyamafd99e012015-06-01 21:05:27 +0000265 StringRef ExternalName = Name;
266 if (Hdr->getNameType() == llvm::COFF::IMPORT_ORDINAL)
267 ExternalName = "";
268 auto *ImpSym = new (Alloc) DefinedImportData(DLLName, ImpName, ExternalName,
269 Hdr);
Rui Ueyama411c63602015-05-28 19:09:30 +0000270 SymbolBodies.push_back(ImpSym);
271
272 // If type is function, we need to create a thunk which jump to an
273 // address pointed by the __imp_ symbol. (This allows you to call
274 // DLL functions just like regular non-DLL functions.)
275 if (Hdr->getType() == llvm::COFF::IMPORT_CODE)
276 SymbolBodies.push_back(new (Alloc) DefinedImportThunk(Name, ImpSym));
277 return std::error_code();
278}
279
Peter Collingbourne60c16162015-06-01 20:10:10 +0000280std::error_code BitcodeFile::parse() {
281 std::string Err;
Rui Ueyama81b030c2015-06-01 21:19:43 +0000282 M.reset(LTOModule::createFromBuffer(MB.getBufferStart(),
283 MB.getBufferSize(),
284 llvm::TargetOptions(), Err));
Peter Collingbourne60c16162015-06-01 20:10:10 +0000285 if (!Err.empty()) {
286 llvm::errs() << Err << '\n';
287 return make_error_code(LLDError::BrokenFile);
288 }
289
Rui Ueyama223fe1b2015-06-18 20:29:41 +0000290 llvm::BumpPtrStringSaver Saver(Alloc);
Peter Collingbourne60c16162015-06-01 20:10:10 +0000291 for (unsigned I = 0, E = M->getSymbolCount(); I != E; ++I) {
Peter Collingbournedf637ea2015-06-08 20:21:28 +0000292 lto_symbol_attributes Attrs = M->getSymbolAttributes(I);
293 if ((Attrs & LTO_SYMBOL_SCOPE_MASK) == LTO_SYMBOL_SCOPE_INTERNAL)
294 continue;
295
Rui Ueyama223fe1b2015-06-18 20:29:41 +0000296 StringRef SymName = Saver.save(M->getSymbolName(I));
Peter Collingbournedf637ea2015-06-08 20:21:28 +0000297 int SymbolDef = Attrs & LTO_SYMBOL_DEFINITION_MASK;
298 if (SymbolDef == LTO_SYMBOL_DEFINITION_UNDEFINED) {
Peter Collingbourne60c16162015-06-01 20:10:10 +0000299 SymbolBodies.push_back(new (Alloc) Undefined(SymName));
300 } else {
Peter Collingbourne2612a322015-07-04 05:28:41 +0000301 bool Replaceable =
302 (SymbolDef == LTO_SYMBOL_DEFINITION_TENTATIVE || // common
303 (Attrs & LTO_SYMBOL_COMDAT) || // comdat
304 (SymbolDef == LTO_SYMBOL_DEFINITION_WEAK && // weak external
305 (Attrs & LTO_SYMBOL_ALIAS)));
Peter Collingbournef7b27d12015-06-30 00:47:52 +0000306 SymbolBodies.push_back(new (Alloc) DefinedBitcode(this, SymName,
307 Replaceable));
Peter Collingbourne60c16162015-06-01 20:10:10 +0000308 }
309 }
Peter Collingbourneace2f092015-06-06 02:00:45 +0000310
Peter Collingbourne79cfd432015-06-29 23:26:28 +0000311 Directives = M->getLinkerOpts();
Peter Collingbourne60c16162015-06-01 20:10:10 +0000312 return std::error_code();
313}
Rui Ueyama81b030c2015-06-01 21:19:43 +0000314
Rui Ueyama411c63602015-05-28 19:09:30 +0000315} // namespace coff
316} // namespace lld