blob: 215271c0844249f0bb0101255993448052afa747 [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"
Rui Ueyama67fcd1a02015-08-05 19:51:28 +000013#include "Symbols.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"
21
Rui Ueyama1c79ce92015-07-08 20:22:50 +000022using namespace llvm::COFF;
Rui Ueyama411c63602015-05-28 19:09:30 +000023using namespace llvm::object;
24using namespace llvm::support::endian;
Rui Ueyama411c63602015-05-28 19:09:30 +000025using llvm::RoundUpToAlignment;
Rui Ueyamaea533cd2015-07-09 19:54:13 +000026using llvm::Triple;
Rui Ueyamacd3f99b2015-07-24 23:51:14 +000027using llvm::support::ulittle32_t;
Rui Ueyama411c63602015-05-28 19:09:30 +000028using llvm::sys::fs::file_magic;
Rui Ueyamaea533cd2015-07-09 19:54:13 +000029using llvm::sys::fs::identify_magic;
Rui Ueyama411c63602015-05-28 19:09:30 +000030
31namespace lld {
32namespace coff {
33
Rui Ueyama65813ed2015-07-02 20:33:48 +000034int InputFile::NextIndex = 0;
35
Rui Ueyama411c63602015-05-28 19:09:30 +000036// Returns the last element of a path, which is supposed to be a filename.
37static StringRef getBasename(StringRef Path) {
Rui Ueyamaea63a282015-06-18 20:16:26 +000038 size_t Pos = Path.find_last_of("\\/");
Rui Ueyama411c63602015-05-28 19:09:30 +000039 if (Pos == StringRef::npos)
40 return Path;
41 return Path.substr(Pos + 1);
42}
43
44// Returns a string in the format of "foo.obj" or "foo.obj(bar.lib)".
45std::string InputFile::getShortName() {
46 if (ParentName == "")
47 return getName().lower();
48 std::string Res = (getBasename(ParentName) + "(" +
49 getBasename(getName()) + ")").str();
50 return StringRef(Res).lower();
51}
52
53std::error_code ArchiveFile::parse() {
Rui Ueyamad7c2f582015-05-31 21:04:56 +000054 // Parse a MemoryBufferRef as an archive file.
55 auto ArchiveOrErr = Archive::create(MB);
Rui Ueyama411c63602015-05-28 19:09:30 +000056 if (auto EC = ArchiveOrErr.getError())
57 return EC;
58 File = std::move(ArchiveOrErr.get());
59
60 // Allocate a buffer for Lazy objects.
Rui Ueyama605e1f62015-06-26 23:51:45 +000061 size_t NumSyms = File->getNumberOfSymbols();
62 size_t BufSize = NumSyms * sizeof(Lazy);
Rui Ueyama411c63602015-05-28 19:09:30 +000063 Lazy *Buf = (Lazy *)Alloc.Allocate(BufSize, llvm::alignOf<Lazy>());
Rui Ueyama8d3010a2015-06-30 19:35:21 +000064 LazySymbols.reserve(NumSyms);
Rui Ueyama411c63602015-05-28 19:09:30 +000065
66 // Read the symbol table to construct Lazy objects.
67 uint32_t I = 0;
68 for (const Archive::Symbol &Sym : File->symbols()) {
Rui Ueyama29792a82015-06-19 21:25:44 +000069 auto *B = new (&Buf[I++]) Lazy(this, Sym);
Rui Ueyama411c63602015-05-28 19:09:30 +000070 // Skip special symbol exists in import library files.
Rui Ueyama29792a82015-06-19 21:25:44 +000071 if (B->getName() != "__NULL_IMPORT_DESCRIPTOR")
Rui Ueyama8d3010a2015-06-30 19:35:21 +000072 LazySymbols.push_back(B);
Rui Ueyama411c63602015-05-28 19:09:30 +000073 }
Rui Ueyama159fb4cd2015-07-14 03:09:59 +000074
75 // Seen is a map from member files to boolean values. Initially
76 // all members are mapped to false, which indicates all these files
77 // are not read yet.
78 for (const Archive::Child &Child : File->children())
Rafael Espindola9f141ef2015-07-14 21:28:07 +000079 Seen[Child.getChildOffset()].clear();
Rui Ueyama411c63602015-05-28 19:09:30 +000080 return std::error_code();
81}
82
83// Returns a buffer pointing to a member file containing a given symbol.
Rui Ueyamaadcde532015-07-05 22:50:00 +000084// This function is thread-safe.
Rui Ueyama411c63602015-05-28 19:09:30 +000085ErrorOr<MemoryBufferRef> ArchiveFile::getMember(const Archive::Symbol *Sym) {
86 auto ItOrErr = Sym->getMember();
87 if (auto EC = ItOrErr.getError())
88 return EC;
89 Archive::child_iterator It = ItOrErr.get();
90
91 // Return an empty buffer if we have already returned the same buffer.
Rafael Espindola9f141ef2015-07-14 21:28:07 +000092 if (Seen[It->getChildOffset()].test_and_set())
Rui Ueyama411c63602015-05-28 19:09:30 +000093 return MemoryBufferRef();
94 return It->getMemoryBufferRef();
95}
96
97std::error_code ObjectFile::parse() {
Rui Ueyama411c63602015-05-28 19:09:30 +000098 // Parse a memory buffer as a COFF file.
Rui Ueyamad7c2f582015-05-31 21:04:56 +000099 auto BinOrErr = createBinary(MB);
Rui Ueyama411c63602015-05-28 19:09:30 +0000100 if (auto EC = BinOrErr.getError())
101 return EC;
102 std::unique_ptr<Binary> Bin = std::move(BinOrErr.get());
103
104 if (auto *Obj = dyn_cast<COFFObjectFile>(Bin.get())) {
105 Bin.release();
106 COFFObj.reset(Obj);
107 } else {
Rui Ueyama8fd9fb92015-06-01 02:58:15 +0000108 llvm::errs() << getName() << " is not a COFF file.\n";
109 return make_error_code(LLDError::InvalidFile);
Rui Ueyama411c63602015-05-28 19:09:30 +0000110 }
111
112 // Read section and symbol tables.
113 if (auto EC = initializeChunks())
114 return EC;
Rui Ueyamacd3f99b2015-07-24 23:51:14 +0000115 if (auto EC = initializeSymbols())
116 return EC;
117 return initializeSEH();
Rui Ueyama411c63602015-05-28 19:09:30 +0000118}
119
Rui Ueyama411c63602015-05-28 19:09:30 +0000120std::error_code ObjectFile::initializeChunks() {
121 uint32_t NumSections = COFFObj->getNumberOfSections();
122 Chunks.reserve(NumSections);
123 SparseChunks.resize(NumSections + 1);
124 for (uint32_t I = 1; I < NumSections + 1; ++I) {
125 const coff_section *Sec;
126 StringRef Name;
Rui Ueyama8fd9fb92015-06-01 02:58:15 +0000127 if (auto EC = COFFObj->getSection(I, Sec)) {
128 llvm::errs() << "getSection failed: " << Name << ": "
129 << EC.message() << "\n";
130 return make_error_code(LLDError::BrokenFile);
131 }
132 if (auto EC = COFFObj->getSectionName(Sec, Name)) {
133 llvm::errs() << "getSectionName failed: " << Name << ": "
134 << EC.message() << "\n";
135 return make_error_code(LLDError::BrokenFile);
136 }
Rui Ueyamacd3f99b2015-07-24 23:51:14 +0000137 if (Name == ".sxdata") {
138 SXData = Sec;
139 continue;
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 }
Rui Ueyama2832ce92015-07-28 01:06:58 +0000147 // Skip non-DWARF debug info. MSVC linker converts the sections into
148 // a PDB file, but we don't support that.
149 if (Name == ".debug" || Name.startswith(".debug$"))
150 continue;
David Majnemer2c345a32015-07-08 16:37:50 +0000151 // We want to preserve DWARF debug sections only when /debug is on.
152 if (!Config->Debug && Name.startswith(".debug"))
Rui Ueyama411c63602015-05-28 19:09:30 +0000153 continue;
154 if (Sec->Characteristics & llvm::COFF::IMAGE_SCN_LNK_REMOVE)
155 continue;
Peter Collingbournebd3a29d2015-06-24 00:12:36 +0000156 auto *C = new (Alloc) SectionChunk(this, Sec);
Rui Ueyama411c63602015-05-28 19:09:30 +0000157 Chunks.push_back(C);
158 SparseChunks[I] = C;
159 }
160 return std::error_code();
161}
162
163std::error_code ObjectFile::initializeSymbols() {
164 uint32_t NumSymbols = COFFObj->getNumberOfSymbols();
165 SymbolBodies.reserve(NumSymbols);
166 SparseSymbolBodies.resize(NumSymbols);
167 int32_t LastSectionNumber = 0;
168 for (uint32_t I = 0; I < NumSymbols; ++I) {
169 // Get a COFFSymbolRef object.
170 auto SymOrErr = COFFObj->getSymbol(I);
Rui Ueyama8fd9fb92015-06-01 02:58:15 +0000171 if (auto EC = SymOrErr.getError()) {
172 llvm::errs() << "broken object file: " << getName() << ": "
173 << EC.message() << "\n";
174 return make_error_code(LLDError::BrokenFile);
175 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000176 COFFSymbolRef Sym = SymOrErr.get();
177
Rui Ueyama411c63602015-05-28 19:09:30 +0000178 const void *AuxP = nullptr;
179 if (Sym.getNumberOfAuxSymbols())
180 AuxP = COFFObj->getSymbol(I + 1)->getRawPtr();
181 bool IsFirst = (LastSectionNumber != Sym.getSectionNumber());
182
Rui Ueyamadae16612015-06-29 22:16:21 +0000183 SymbolBody *Body = nullptr;
184 if (Sym.isUndefined()) {
185 Body = createUndefined(Sym);
186 } else if (Sym.isWeakExternal()) {
187 Body = createWeakExternal(Sym, AuxP);
188 } else {
189 Body = createDefined(Sym, AuxP, IsFirst);
190 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000191 if (Body) {
192 SymbolBodies.push_back(Body);
193 SparseSymbolBodies[I] = Body;
194 }
195 I += Sym.getNumberOfAuxSymbols();
196 LastSectionNumber = Sym.getSectionNumber();
197 }
198 return std::error_code();
199}
200
Rui Ueyamadae16612015-06-29 22:16:21 +0000201Undefined *ObjectFile::createUndefined(COFFSymbolRef Sym) {
Rui Ueyama57fe78d2015-06-08 19:43:59 +0000202 StringRef Name;
Rui Ueyamadae16612015-06-29 22:16:21 +0000203 COFFObj->getSymbolName(Sym, Name);
204 return new (Alloc) Undefined(Name);
205}
206
207Undefined *ObjectFile::createWeakExternal(COFFSymbolRef Sym, const void *AuxP) {
208 StringRef Name;
209 COFFObj->getSymbolName(Sym, Name);
Rui Ueyama48975962015-07-01 22:32:23 +0000210 auto *U = new (Alloc) Undefined(Name);
Rui Ueyamadae16612015-06-29 22:16:21 +0000211 auto *Aux = (const coff_aux_weak_external *)AuxP;
Peter Collingbourneda2f0942015-07-03 22:03:36 +0000212 U->WeakAlias = SparseSymbolBodies[Aux->TagIndex];
Rui Ueyama48975962015-07-01 22:32:23 +0000213 return U;
Rui Ueyamadae16612015-06-29 22:16:21 +0000214}
215
216Defined *ObjectFile::createDefined(COFFSymbolRef Sym, const void *AuxP,
217 bool IsFirst) {
218 StringRef Name;
Rui Ueyama411c63602015-05-28 19:09:30 +0000219 if (Sym.isCommon()) {
Rui Ueyamafc510f42015-06-25 19:10:58 +0000220 auto *C = new (Alloc) CommonChunk(Sym);
Rui Ueyama411c63602015-05-28 19:09:30 +0000221 Chunks.push_back(C);
Rui Ueyama68633f12015-06-25 23:22:00 +0000222 return new (Alloc) DefinedCommon(this, Sym, C);
Rui Ueyama411c63602015-05-28 19:09:30 +0000223 }
Rui Ueyama57fe78d2015-06-08 19:43:59 +0000224 if (Sym.isAbsolute()) {
225 COFFObj->getSymbolName(Sym, Name);
226 // Skip special symbols.
Rui Ueyamacd3f99b2015-07-24 23:51:14 +0000227 if (Name == "@comp.id")
Rui Ueyama57fe78d2015-06-08 19:43:59 +0000228 return nullptr;
Rui Ueyamacd3f99b2015-07-24 23:51:14 +0000229 // COFF spec 5.10.1. The .sxdata section.
230 if (Name == "@feat.00") {
231 if (Sym.getValue() & 1)
232 SEHCompat = true;
233 return nullptr;
234 }
Rui Ueyamaccde19d2015-06-26 03:09:23 +0000235 return new (Alloc) DefinedAbsolute(Name, Sym);
Rui Ueyama57fe78d2015-06-08 19:43:59 +0000236 }
Peter Collingbournec7b685d2015-06-24 00:05:50 +0000237 if (Sym.getSectionNumber() == llvm::COFF::IMAGE_SYM_DEBUG)
238 return nullptr;
Chandler Carruthee5bf522015-06-29 21:32:37 +0000239
240 // Nothing else to do without a section chunk.
241 auto *SC = cast_or_null<SectionChunk>(SparseChunks[Sym.getSectionNumber()]);
242 if (!SC)
243 return nullptr;
244
Rui Ueyama80141a42015-06-08 05:00:42 +0000245 // Handle associative sections
Rui Ueyama411c63602015-05-28 19:09:30 +0000246 if (IsFirst && AuxP) {
Chandler Carruthee5bf522015-06-29 21:32:37 +0000247 auto *Aux = reinterpret_cast<const coff_aux_section_definition *>(AuxP);
248 if (Aux->Selection == IMAGE_COMDAT_SELECT_ASSOCIATIVE)
249 if (auto *ParentSC = cast_or_null<SectionChunk>(
250 SparseChunks[Aux->getNumber(Sym.isBigObj())]))
251 ParentSC->addAssociative(SC);
Rui Ueyama411c63602015-05-28 19:09:30 +0000252 }
Chandler Carruthee5bf522015-06-29 21:32:37 +0000253
254 auto *B = new (Alloc) DefinedRegular(this, Sym, SC);
255 if (SC->isCOMDAT() && Sym.getValue() == 0 && !AuxP)
256 SC->setSymbol(B);
257
258 return B;
Rui Ueyama411c63602015-05-28 19:09:30 +0000259}
260
Rui Ueyamacd3f99b2015-07-24 23:51:14 +0000261std::error_code ObjectFile::initializeSEH() {
262 if (!SEHCompat || !SXData)
263 return std::error_code();
264 ArrayRef<uint8_t> A;
265 COFFObj->getSectionContents(SXData, A);
266 if (A.size() % 4 != 0) {
267 llvm::errs() << ".sxdata must be an array of symbol table indices\n";
268 return make_error_code(LLDError::BrokenFile);
269 }
270 auto *I = reinterpret_cast<const ulittle32_t *>(A.data());
271 auto *E = reinterpret_cast<const ulittle32_t *>(A.data() + A.size());
272 for (; I != E; ++I)
273 SEHandlers.insert(SparseSymbolBodies[*I]);
274 return std::error_code();
275}
276
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000277MachineTypes ObjectFile::getMachineType() {
278 if (COFFObj)
279 return static_cast<MachineTypes>(COFFObj->getMachine());
280 return IMAGE_FILE_MACHINE_UNKNOWN;
281}
282
Rui Ueyamaa841bb02015-07-09 20:22:41 +0000283StringRef ltrim1(StringRef S, const char *Chars) {
284 if (!S.empty() && strchr(Chars, S[0]))
285 return S.substr(1);
286 return S;
287}
288
Rui Ueyama411c63602015-05-28 19:09:30 +0000289std::error_code ImportFile::parse() {
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000290 const char *Buf = MB.getBufferStart();
291 const char *End = MB.getBufferEnd();
Rui Ueyama411c63602015-05-28 19:09:30 +0000292 const auto *Hdr = reinterpret_cast<const coff_import_header *>(Buf);
293
294 // Check if the total size is valid.
Denis Protivensky68336902015-06-01 09:26:32 +0000295 if ((size_t)(End - Buf) != (sizeof(*Hdr) + Hdr->SizeOfData)) {
Rui Ueyama8fd9fb92015-06-01 02:58:15 +0000296 llvm::errs() << "broken import library\n";
297 return make_error_code(LLDError::BrokenFile);
298 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000299
300 // Read names and create an __imp_ symbol.
301 StringRef Name = StringAlloc.save(StringRef(Buf + sizeof(*Hdr)));
302 StringRef ImpName = StringAlloc.save(Twine("__imp_") + Name);
303 StringRef DLLName(Buf + sizeof(coff_import_header) + Name.size() + 1);
Rui Ueyama1c79ce92015-07-08 20:22:50 +0000304 StringRef ExtName;
305 switch (Hdr->getNameType()) {
306 case IMPORT_ORDINAL:
307 ExtName = "";
308 break;
309 case IMPORT_NAME:
310 ExtName = Name;
311 break;
312 case IMPORT_NAME_NOPREFIX:
Rui Ueyamaa841bb02015-07-09 20:22:41 +0000313 ExtName = ltrim1(Name, "?@_");
Rui Ueyama1c79ce92015-07-08 20:22:50 +0000314 break;
315 case IMPORT_NAME_UNDECORATE:
Rui Ueyamaa841bb02015-07-09 20:22:41 +0000316 ExtName = ltrim1(Name, "?@_");
Rui Ueyama1c79ce92015-07-08 20:22:50 +0000317 ExtName = ExtName.substr(0, ExtName.find('@'));
318 break;
319 }
320 auto *ImpSym = new (Alloc) DefinedImportData(DLLName, ImpName, ExtName, Hdr);
Rui Ueyama411c63602015-05-28 19:09:30 +0000321 SymbolBodies.push_back(ImpSym);
322
323 // If type is function, we need to create a thunk which jump to an
324 // address pointed by the __imp_ symbol. (This allows you to call
325 // DLL functions just like regular non-DLL functions.)
Rui Ueyama28df0422015-07-25 01:16:06 +0000326 if (Hdr->getType() == llvm::COFF::IMPORT_CODE) {
327 auto *B = new (Alloc) DefinedImportThunk(Name, ImpSym, Hdr->Machine);
328 SymbolBodies.push_back(B);
329 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000330 return std::error_code();
331}
332
Peter Collingbourne60c16162015-06-01 20:10:10 +0000333std::error_code BitcodeFile::parse() {
334 std::string Err;
Rui Ueyama81b030c2015-06-01 21:19:43 +0000335 M.reset(LTOModule::createFromBuffer(MB.getBufferStart(),
336 MB.getBufferSize(),
337 llvm::TargetOptions(), Err));
Peter Collingbourne60c16162015-06-01 20:10:10 +0000338 if (!Err.empty()) {
339 llvm::errs() << Err << '\n';
340 return make_error_code(LLDError::BrokenFile);
341 }
342
Rui Ueyama223fe1b2015-06-18 20:29:41 +0000343 llvm::BumpPtrStringSaver Saver(Alloc);
Peter Collingbourne60c16162015-06-01 20:10:10 +0000344 for (unsigned I = 0, E = M->getSymbolCount(); I != E; ++I) {
Peter Collingbournedf637ea2015-06-08 20:21:28 +0000345 lto_symbol_attributes Attrs = M->getSymbolAttributes(I);
346 if ((Attrs & LTO_SYMBOL_SCOPE_MASK) == LTO_SYMBOL_SCOPE_INTERNAL)
347 continue;
348
Rui Ueyama223fe1b2015-06-18 20:29:41 +0000349 StringRef SymName = Saver.save(M->getSymbolName(I));
Peter Collingbournedf637ea2015-06-08 20:21:28 +0000350 int SymbolDef = Attrs & LTO_SYMBOL_DEFINITION_MASK;
351 if (SymbolDef == LTO_SYMBOL_DEFINITION_UNDEFINED) {
Peter Collingbourne60c16162015-06-01 20:10:10 +0000352 SymbolBodies.push_back(new (Alloc) Undefined(SymName));
353 } else {
Peter Collingbourne2612a322015-07-04 05:28:41 +0000354 bool Replaceable =
355 (SymbolDef == LTO_SYMBOL_DEFINITION_TENTATIVE || // common
356 (Attrs & LTO_SYMBOL_COMDAT) || // comdat
357 (SymbolDef == LTO_SYMBOL_DEFINITION_WEAK && // weak external
358 (Attrs & LTO_SYMBOL_ALIAS)));
Peter Collingbournef7b27d12015-06-30 00:47:52 +0000359 SymbolBodies.push_back(new (Alloc) DefinedBitcode(this, SymName,
360 Replaceable));
Peter Collingbourne60c16162015-06-01 20:10:10 +0000361 }
362 }
Peter Collingbourneace2f092015-06-06 02:00:45 +0000363
Peter Collingbourne79cfd432015-06-29 23:26:28 +0000364 Directives = M->getLinkerOpts();
Peter Collingbourne60c16162015-06-01 20:10:10 +0000365 return std::error_code();
366}
Rui Ueyama81b030c2015-06-01 21:19:43 +0000367
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000368MachineTypes BitcodeFile::getMachineType() {
369 if (!M)
370 return IMAGE_FILE_MACHINE_UNKNOWN;
371 switch (Triple(M->getTargetTriple()).getArch()) {
372 case Triple::x86_64:
Rui Ueyama5e706b32015-07-25 21:54:50 +0000373 return AMD64;
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000374 case Triple::x86:
Rui Ueyama5e706b32015-07-25 21:54:50 +0000375 return I386;
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000376 case Triple::arm:
Rui Ueyama5e706b32015-07-25 21:54:50 +0000377 return ARMNT;
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000378 default:
379 return IMAGE_FILE_MACHINE_UNKNOWN;
380 }
381}
382
Rui Ueyama411c63602015-05-28 19:09:30 +0000383} // namespace coff
384} // namespace lld