blob: 3e6a6b90776025f3d491b050660217cb310803b1 [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
Rui Ueyama1c79ce92015-07-08 20:22:50 +000023using namespace llvm::COFF;
Rui Ueyama411c63602015-05-28 19:09:30 +000024using namespace llvm::object;
25using namespace llvm::support::endian;
Rui Ueyama411c63602015-05-28 19:09:30 +000026using llvm::RoundUpToAlignment;
Rui Ueyamaea533cd2015-07-09 19:54:13 +000027using llvm::Triple;
Rui Ueyamacd3f99b2015-07-24 23:51:14 +000028using llvm::support::ulittle32_t;
Rui Ueyama411c63602015-05-28 19:09:30 +000029using llvm::sys::fs::file_magic;
Rui Ueyamaea533cd2015-07-09 19:54:13 +000030using llvm::sys::fs::identify_magic;
Rui Ueyama411c63602015-05-28 19:09:30 +000031
32namespace lld {
33namespace coff {
34
Rui Ueyama65813ed2015-07-02 20:33:48 +000035int InputFile::NextIndex = 0;
36
Rui Ueyama411c63602015-05-28 19:09:30 +000037// Returns the last element of a path, which is supposed to be a filename.
38static StringRef getBasename(StringRef Path) {
Rui Ueyamaea63a282015-06-18 20:16:26 +000039 size_t Pos = Path.find_last_of("\\/");
Rui Ueyama411c63602015-05-28 19:09:30 +000040 if (Pos == StringRef::npos)
41 return Path;
42 return Path.substr(Pos + 1);
43}
44
45// Returns a string in the format of "foo.obj" or "foo.obj(bar.lib)".
46std::string InputFile::getShortName() {
47 if (ParentName == "")
48 return getName().lower();
49 std::string Res = (getBasename(ParentName) + "(" +
50 getBasename(getName()) + ")").str();
51 return StringRef(Res).lower();
52}
53
54std::error_code ArchiveFile::parse() {
Rui Ueyamad7c2f582015-05-31 21:04:56 +000055 // Parse a MemoryBufferRef as an archive file.
56 auto ArchiveOrErr = Archive::create(MB);
Rui Ueyama411c63602015-05-28 19:09:30 +000057 if (auto EC = ArchiveOrErr.getError())
58 return EC;
59 File = std::move(ArchiveOrErr.get());
60
61 // Allocate a buffer for Lazy objects.
Rui Ueyama605e1f62015-06-26 23:51:45 +000062 size_t NumSyms = File->getNumberOfSymbols();
63 size_t BufSize = NumSyms * sizeof(Lazy);
Rui Ueyama411c63602015-05-28 19:09:30 +000064 Lazy *Buf = (Lazy *)Alloc.Allocate(BufSize, llvm::alignOf<Lazy>());
Rui Ueyama8d3010a2015-06-30 19:35:21 +000065 LazySymbols.reserve(NumSyms);
Rui Ueyama411c63602015-05-28 19:09:30 +000066
67 // Read the symbol table to construct Lazy objects.
68 uint32_t I = 0;
69 for (const Archive::Symbol &Sym : File->symbols()) {
Rui Ueyama29792a82015-06-19 21:25:44 +000070 auto *B = new (&Buf[I++]) Lazy(this, Sym);
Rui Ueyama411c63602015-05-28 19:09:30 +000071 // Skip special symbol exists in import library files.
Rui Ueyama29792a82015-06-19 21:25:44 +000072 if (B->getName() != "__NULL_IMPORT_DESCRIPTOR")
Rui Ueyama8d3010a2015-06-30 19:35:21 +000073 LazySymbols.push_back(B);
Rui Ueyama411c63602015-05-28 19:09:30 +000074 }
Rui Ueyama159fb4cd2015-07-14 03:09:59 +000075
76 // Seen is a map from member files to boolean values. Initially
77 // all members are mapped to false, which indicates all these files
78 // are not read yet.
79 for (const Archive::Child &Child : File->children())
Rafael Espindola9f141ef2015-07-14 21:28:07 +000080 Seen[Child.getChildOffset()].clear();
Rui Ueyama411c63602015-05-28 19:09:30 +000081 return std::error_code();
82}
83
84// Returns a buffer pointing to a member file containing a given symbol.
Rui Ueyamaadcde532015-07-05 22:50:00 +000085// This function is thread-safe.
Rui Ueyama411c63602015-05-28 19:09:30 +000086ErrorOr<MemoryBufferRef> ArchiveFile::getMember(const Archive::Symbol *Sym) {
87 auto ItOrErr = Sym->getMember();
88 if (auto EC = ItOrErr.getError())
89 return EC;
90 Archive::child_iterator It = ItOrErr.get();
91
92 // Return an empty buffer if we have already returned the same buffer.
Rafael Espindola9f141ef2015-07-14 21:28:07 +000093 if (Seen[It->getChildOffset()].test_and_set())
Rui Ueyama411c63602015-05-28 19:09:30 +000094 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 }
112
113 // Read section and symbol tables.
114 if (auto EC = initializeChunks())
115 return EC;
Rui Ueyamacd3f99b2015-07-24 23:51:14 +0000116 if (auto EC = initializeSymbols())
117 return EC;
118 return initializeSEH();
Rui Ueyama411c63602015-05-28 19:09:30 +0000119}
120
Rui Ueyama411c63602015-05-28 19:09:30 +0000121std::error_code ObjectFile::initializeChunks() {
122 uint32_t NumSections = COFFObj->getNumberOfSections();
123 Chunks.reserve(NumSections);
124 SparseChunks.resize(NumSections + 1);
125 for (uint32_t I = 1; I < NumSections + 1; ++I) {
126 const coff_section *Sec;
127 StringRef Name;
Rui Ueyama8fd9fb92015-06-01 02:58:15 +0000128 if (auto EC = COFFObj->getSection(I, Sec)) {
129 llvm::errs() << "getSection failed: " << Name << ": "
130 << EC.message() << "\n";
131 return make_error_code(LLDError::BrokenFile);
132 }
133 if (auto EC = COFFObj->getSectionName(Sec, Name)) {
134 llvm::errs() << "getSectionName failed: " << Name << ": "
135 << EC.message() << "\n";
136 return make_error_code(LLDError::BrokenFile);
137 }
Rui Ueyamacd3f99b2015-07-24 23:51:14 +0000138 if (Name == ".sxdata") {
139 SXData = Sec;
140 continue;
141 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000142 if (Name == ".drectve") {
143 ArrayRef<uint8_t> Data;
144 COFFObj->getSectionContents(Sec, Data);
Rui Ueyama0569ecf2015-07-04 03:27:46 +0000145 Directives = std::string((const char *)Data.data(), Data.size());
Rui Ueyama411c63602015-05-28 19:09:30 +0000146 continue;
147 }
David Majnemer2c345a32015-07-08 16:37:50 +0000148 // We want to preserve DWARF debug sections only when /debug is on.
149 if (!Config->Debug && Name.startswith(".debug"))
Rui Ueyama411c63602015-05-28 19:09:30 +0000150 continue;
151 if (Sec->Characteristics & llvm::COFF::IMAGE_SCN_LNK_REMOVE)
152 continue;
Peter Collingbournebd3a29d2015-06-24 00:12:36 +0000153 auto *C = new (Alloc) SectionChunk(this, Sec);
Rui Ueyama411c63602015-05-28 19:09:30 +0000154 Chunks.push_back(C);
155 SparseChunks[I] = C;
156 }
157 return std::error_code();
158}
159
160std::error_code ObjectFile::initializeSymbols() {
161 uint32_t NumSymbols = COFFObj->getNumberOfSymbols();
162 SymbolBodies.reserve(NumSymbols);
163 SparseSymbolBodies.resize(NumSymbols);
164 int32_t LastSectionNumber = 0;
165 for (uint32_t I = 0; I < NumSymbols; ++I) {
166 // Get a COFFSymbolRef object.
167 auto SymOrErr = COFFObj->getSymbol(I);
Rui Ueyama8fd9fb92015-06-01 02:58:15 +0000168 if (auto EC = SymOrErr.getError()) {
169 llvm::errs() << "broken object file: " << getName() << ": "
170 << EC.message() << "\n";
171 return make_error_code(LLDError::BrokenFile);
172 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000173 COFFSymbolRef Sym = SymOrErr.get();
174
Rui Ueyama411c63602015-05-28 19:09:30 +0000175 const void *AuxP = nullptr;
176 if (Sym.getNumberOfAuxSymbols())
177 AuxP = COFFObj->getSymbol(I + 1)->getRawPtr();
178 bool IsFirst = (LastSectionNumber != Sym.getSectionNumber());
179
Rui Ueyamadae16612015-06-29 22:16:21 +0000180 SymbolBody *Body = nullptr;
181 if (Sym.isUndefined()) {
182 Body = createUndefined(Sym);
183 } else if (Sym.isWeakExternal()) {
184 Body = createWeakExternal(Sym, AuxP);
185 } else {
186 Body = createDefined(Sym, AuxP, IsFirst);
187 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000188 if (Body) {
189 SymbolBodies.push_back(Body);
190 SparseSymbolBodies[I] = Body;
191 }
192 I += Sym.getNumberOfAuxSymbols();
193 LastSectionNumber = Sym.getSectionNumber();
194 }
195 return std::error_code();
196}
197
Rui Ueyamadae16612015-06-29 22:16:21 +0000198Undefined *ObjectFile::createUndefined(COFFSymbolRef Sym) {
Rui Ueyama57fe78d2015-06-08 19:43:59 +0000199 StringRef Name;
Rui Ueyamadae16612015-06-29 22:16:21 +0000200 COFFObj->getSymbolName(Sym, Name);
201 return new (Alloc) Undefined(Name);
202}
203
204Undefined *ObjectFile::createWeakExternal(COFFSymbolRef Sym, const void *AuxP) {
205 StringRef Name;
206 COFFObj->getSymbolName(Sym, Name);
Rui Ueyama48975962015-07-01 22:32:23 +0000207 auto *U = new (Alloc) Undefined(Name);
Rui Ueyamadae16612015-06-29 22:16:21 +0000208 auto *Aux = (const coff_aux_weak_external *)AuxP;
Peter Collingbourneda2f0942015-07-03 22:03:36 +0000209 U->WeakAlias = SparseSymbolBodies[Aux->TagIndex];
Rui Ueyama48975962015-07-01 22:32:23 +0000210 return U;
Rui Ueyamadae16612015-06-29 22:16:21 +0000211}
212
213Defined *ObjectFile::createDefined(COFFSymbolRef Sym, const void *AuxP,
214 bool IsFirst) {
215 StringRef Name;
Rui Ueyama411c63602015-05-28 19:09:30 +0000216 if (Sym.isCommon()) {
Rui Ueyamafc510f42015-06-25 19:10:58 +0000217 auto *C = new (Alloc) CommonChunk(Sym);
Rui Ueyama411c63602015-05-28 19:09:30 +0000218 Chunks.push_back(C);
Rui Ueyama68633f12015-06-25 23:22:00 +0000219 return new (Alloc) DefinedCommon(this, Sym, C);
Rui Ueyama411c63602015-05-28 19:09:30 +0000220 }
Rui Ueyama57fe78d2015-06-08 19:43:59 +0000221 if (Sym.isAbsolute()) {
222 COFFObj->getSymbolName(Sym, Name);
223 // Skip special symbols.
Rui Ueyamacd3f99b2015-07-24 23:51:14 +0000224 if (Name == "@comp.id")
Rui Ueyama57fe78d2015-06-08 19:43:59 +0000225 return nullptr;
Rui Ueyamacd3f99b2015-07-24 23:51:14 +0000226 // COFF spec 5.10.1. The .sxdata section.
227 if (Name == "@feat.00") {
228 if (Sym.getValue() & 1)
229 SEHCompat = true;
230 return nullptr;
231 }
Rui Ueyamaccde19d2015-06-26 03:09:23 +0000232 return new (Alloc) DefinedAbsolute(Name, Sym);
Rui Ueyama57fe78d2015-06-08 19:43:59 +0000233 }
Peter Collingbournec7b685d2015-06-24 00:05:50 +0000234 if (Sym.getSectionNumber() == llvm::COFF::IMAGE_SYM_DEBUG)
235 return nullptr;
Chandler Carruthee5bf522015-06-29 21:32:37 +0000236
237 // Nothing else to do without a section chunk.
238 auto *SC = cast_or_null<SectionChunk>(SparseChunks[Sym.getSectionNumber()]);
239 if (!SC)
240 return nullptr;
241
Rui Ueyama80141a42015-06-08 05:00:42 +0000242 // Handle associative sections
Rui Ueyama411c63602015-05-28 19:09:30 +0000243 if (IsFirst && AuxP) {
Chandler Carruthee5bf522015-06-29 21:32:37 +0000244 auto *Aux = reinterpret_cast<const coff_aux_section_definition *>(AuxP);
245 if (Aux->Selection == IMAGE_COMDAT_SELECT_ASSOCIATIVE)
246 if (auto *ParentSC = cast_or_null<SectionChunk>(
247 SparseChunks[Aux->getNumber(Sym.isBigObj())]))
248 ParentSC->addAssociative(SC);
Rui Ueyama411c63602015-05-28 19:09:30 +0000249 }
Chandler Carruthee5bf522015-06-29 21:32:37 +0000250
251 auto *B = new (Alloc) DefinedRegular(this, Sym, SC);
252 if (SC->isCOMDAT() && Sym.getValue() == 0 && !AuxP)
253 SC->setSymbol(B);
254
255 return B;
Rui Ueyama411c63602015-05-28 19:09:30 +0000256}
257
Rui Ueyamacd3f99b2015-07-24 23:51:14 +0000258std::error_code ObjectFile::initializeSEH() {
259 if (!SEHCompat || !SXData)
260 return std::error_code();
261 ArrayRef<uint8_t> A;
262 COFFObj->getSectionContents(SXData, A);
263 if (A.size() % 4 != 0) {
264 llvm::errs() << ".sxdata must be an array of symbol table indices\n";
265 return make_error_code(LLDError::BrokenFile);
266 }
267 auto *I = reinterpret_cast<const ulittle32_t *>(A.data());
268 auto *E = reinterpret_cast<const ulittle32_t *>(A.data() + A.size());
269 for (; I != E; ++I)
270 SEHandlers.insert(SparseSymbolBodies[*I]);
271 return std::error_code();
272}
273
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000274MachineTypes ObjectFile::getMachineType() {
275 if (COFFObj)
276 return static_cast<MachineTypes>(COFFObj->getMachine());
277 return IMAGE_FILE_MACHINE_UNKNOWN;
278}
279
Rui Ueyamaa841bb02015-07-09 20:22:41 +0000280StringRef ltrim1(StringRef S, const char *Chars) {
281 if (!S.empty() && strchr(Chars, S[0]))
282 return S.substr(1);
283 return S;
284}
285
Rui Ueyama411c63602015-05-28 19:09:30 +0000286std::error_code ImportFile::parse() {
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000287 const char *Buf = MB.getBufferStart();
288 const char *End = MB.getBufferEnd();
Rui Ueyama411c63602015-05-28 19:09:30 +0000289 const auto *Hdr = reinterpret_cast<const coff_import_header *>(Buf);
290
291 // Check if the total size is valid.
Denis Protivensky68336902015-06-01 09:26:32 +0000292 if ((size_t)(End - Buf) != (sizeof(*Hdr) + Hdr->SizeOfData)) {
Rui Ueyama8fd9fb92015-06-01 02:58:15 +0000293 llvm::errs() << "broken import library\n";
294 return make_error_code(LLDError::BrokenFile);
295 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000296
297 // Read names and create an __imp_ symbol.
298 StringRef Name = StringAlloc.save(StringRef(Buf + sizeof(*Hdr)));
299 StringRef ImpName = StringAlloc.save(Twine("__imp_") + Name);
300 StringRef DLLName(Buf + sizeof(coff_import_header) + Name.size() + 1);
Rui Ueyama1c79ce92015-07-08 20:22:50 +0000301 StringRef ExtName;
302 switch (Hdr->getNameType()) {
303 case IMPORT_ORDINAL:
304 ExtName = "";
305 break;
306 case IMPORT_NAME:
307 ExtName = Name;
308 break;
309 case IMPORT_NAME_NOPREFIX:
Rui Ueyamaa841bb02015-07-09 20:22:41 +0000310 ExtName = ltrim1(Name, "?@_");
Rui Ueyama1c79ce92015-07-08 20:22:50 +0000311 break;
312 case IMPORT_NAME_UNDECORATE:
Rui Ueyamaa841bb02015-07-09 20:22:41 +0000313 ExtName = ltrim1(Name, "?@_");
Rui Ueyama1c79ce92015-07-08 20:22:50 +0000314 ExtName = ExtName.substr(0, ExtName.find('@'));
315 break;
316 }
317 auto *ImpSym = new (Alloc) DefinedImportData(DLLName, ImpName, ExtName, Hdr);
Rui Ueyama411c63602015-05-28 19:09:30 +0000318 SymbolBodies.push_back(ImpSym);
319
320 // If type is function, we need to create a thunk which jump to an
321 // address pointed by the __imp_ symbol. (This allows you to call
322 // DLL functions just like regular non-DLL functions.)
Rui Ueyama28df0422015-07-25 01:16:06 +0000323 if (Hdr->getType() == llvm::COFF::IMPORT_CODE) {
324 auto *B = new (Alloc) DefinedImportThunk(Name, ImpSym, Hdr->Machine);
325 SymbolBodies.push_back(B);
326 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000327 return std::error_code();
328}
329
Peter Collingbourne60c16162015-06-01 20:10:10 +0000330std::error_code BitcodeFile::parse() {
331 std::string Err;
Rui Ueyama81b030c2015-06-01 21:19:43 +0000332 M.reset(LTOModule::createFromBuffer(MB.getBufferStart(),
333 MB.getBufferSize(),
334 llvm::TargetOptions(), Err));
Peter Collingbourne60c16162015-06-01 20:10:10 +0000335 if (!Err.empty()) {
336 llvm::errs() << Err << '\n';
337 return make_error_code(LLDError::BrokenFile);
338 }
339
Rui Ueyama223fe1b2015-06-18 20:29:41 +0000340 llvm::BumpPtrStringSaver Saver(Alloc);
Peter Collingbourne60c16162015-06-01 20:10:10 +0000341 for (unsigned I = 0, E = M->getSymbolCount(); I != E; ++I) {
Peter Collingbournedf637ea2015-06-08 20:21:28 +0000342 lto_symbol_attributes Attrs = M->getSymbolAttributes(I);
343 if ((Attrs & LTO_SYMBOL_SCOPE_MASK) == LTO_SYMBOL_SCOPE_INTERNAL)
344 continue;
345
Rui Ueyama223fe1b2015-06-18 20:29:41 +0000346 StringRef SymName = Saver.save(M->getSymbolName(I));
Peter Collingbournedf637ea2015-06-08 20:21:28 +0000347 int SymbolDef = Attrs & LTO_SYMBOL_DEFINITION_MASK;
348 if (SymbolDef == LTO_SYMBOL_DEFINITION_UNDEFINED) {
Peter Collingbourne60c16162015-06-01 20:10:10 +0000349 SymbolBodies.push_back(new (Alloc) Undefined(SymName));
350 } else {
Peter Collingbourne2612a322015-07-04 05:28:41 +0000351 bool Replaceable =
352 (SymbolDef == LTO_SYMBOL_DEFINITION_TENTATIVE || // common
353 (Attrs & LTO_SYMBOL_COMDAT) || // comdat
354 (SymbolDef == LTO_SYMBOL_DEFINITION_WEAK && // weak external
355 (Attrs & LTO_SYMBOL_ALIAS)));
Peter Collingbournef7b27d12015-06-30 00:47:52 +0000356 SymbolBodies.push_back(new (Alloc) DefinedBitcode(this, SymName,
357 Replaceable));
Peter Collingbourne60c16162015-06-01 20:10:10 +0000358 }
359 }
Peter Collingbourneace2f092015-06-06 02:00:45 +0000360
Peter Collingbourne79cfd432015-06-29 23:26:28 +0000361 Directives = M->getLinkerOpts();
Peter Collingbourne60c16162015-06-01 20:10:10 +0000362 return std::error_code();
363}
Rui Ueyama81b030c2015-06-01 21:19:43 +0000364
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000365MachineTypes BitcodeFile::getMachineType() {
366 if (!M)
367 return IMAGE_FILE_MACHINE_UNKNOWN;
368 switch (Triple(M->getTargetTriple()).getArch()) {
369 case Triple::x86_64:
370 return IMAGE_FILE_MACHINE_AMD64;
371 case Triple::x86:
372 return IMAGE_FILE_MACHINE_I386;
373 case Triple::arm:
374 return IMAGE_FILE_MACHINE_ARMNT;
375 default:
376 return IMAGE_FILE_MACHINE_UNKNOWN;
377 }
378}
379
Rui Ueyama411c63602015-05-28 19:09:30 +0000380} // namespace coff
381} // namespace lld