blob: cbc239388863c0f69f1a0d2ecdad298429fe97d9 [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 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 Ueyama95dd08e2015-07-06 18:22:16 +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())
79 Seen[Child.getBuffer().data()].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.
92 const char *StartAddr = It->getBuffer().data();
Rui Ueyama95dd08e2015-07-06 18:22:16 +000093 if (Seen[StartAddr].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;
116 return initializeSymbols();
117}
118
Rui Ueyama411c63602015-05-28 19:09:30 +0000119std::error_code ObjectFile::initializeChunks() {
120 uint32_t NumSections = COFFObj->getNumberOfSections();
121 Chunks.reserve(NumSections);
122 SparseChunks.resize(NumSections + 1);
123 for (uint32_t I = 1; I < NumSections + 1; ++I) {
124 const coff_section *Sec;
125 StringRef Name;
Rui Ueyama8fd9fb92015-06-01 02:58:15 +0000126 if (auto EC = COFFObj->getSection(I, Sec)) {
127 llvm::errs() << "getSection failed: " << Name << ": "
128 << EC.message() << "\n";
129 return make_error_code(LLDError::BrokenFile);
130 }
131 if (auto EC = COFFObj->getSectionName(Sec, Name)) {
132 llvm::errs() << "getSectionName failed: " << Name << ": "
133 << EC.message() << "\n";
134 return make_error_code(LLDError::BrokenFile);
135 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000136 if (Name == ".drectve") {
137 ArrayRef<uint8_t> Data;
138 COFFObj->getSectionContents(Sec, Data);
Rui Ueyama0569ecf2015-07-04 03:27:46 +0000139 Directives = std::string((const char *)Data.data(), Data.size());
Rui Ueyama411c63602015-05-28 19:09:30 +0000140 continue;
141 }
David Majnemer2c345a32015-07-08 16:37:50 +0000142 // We want to preserve DWARF debug sections only when /debug is on.
143 if (!Config->Debug && Name.startswith(".debug"))
Rui Ueyama411c63602015-05-28 19:09:30 +0000144 continue;
145 if (Sec->Characteristics & llvm::COFF::IMAGE_SCN_LNK_REMOVE)
146 continue;
Peter Collingbournebd3a29d2015-06-24 00:12:36 +0000147 auto *C = new (Alloc) SectionChunk(this, Sec);
Rui Ueyama411c63602015-05-28 19:09:30 +0000148 Chunks.push_back(C);
149 SparseChunks[I] = C;
150 }
151 return std::error_code();
152}
153
154std::error_code ObjectFile::initializeSymbols() {
155 uint32_t NumSymbols = COFFObj->getNumberOfSymbols();
156 SymbolBodies.reserve(NumSymbols);
157 SparseSymbolBodies.resize(NumSymbols);
158 int32_t LastSectionNumber = 0;
159 for (uint32_t I = 0; I < NumSymbols; ++I) {
160 // Get a COFFSymbolRef object.
161 auto SymOrErr = COFFObj->getSymbol(I);
Rui Ueyama8fd9fb92015-06-01 02:58:15 +0000162 if (auto EC = SymOrErr.getError()) {
163 llvm::errs() << "broken object file: " << getName() << ": "
164 << EC.message() << "\n";
165 return make_error_code(LLDError::BrokenFile);
166 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000167 COFFSymbolRef Sym = SymOrErr.get();
168
Rui Ueyama411c63602015-05-28 19:09:30 +0000169 const void *AuxP = nullptr;
170 if (Sym.getNumberOfAuxSymbols())
171 AuxP = COFFObj->getSymbol(I + 1)->getRawPtr();
172 bool IsFirst = (LastSectionNumber != Sym.getSectionNumber());
173
Rui Ueyamadae16612015-06-29 22:16:21 +0000174 SymbolBody *Body = nullptr;
175 if (Sym.isUndefined()) {
176 Body = createUndefined(Sym);
177 } else if (Sym.isWeakExternal()) {
178 Body = createWeakExternal(Sym, AuxP);
179 } else {
180 Body = createDefined(Sym, AuxP, IsFirst);
181 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000182 if (Body) {
183 SymbolBodies.push_back(Body);
184 SparseSymbolBodies[I] = Body;
185 }
186 I += Sym.getNumberOfAuxSymbols();
187 LastSectionNumber = Sym.getSectionNumber();
188 }
189 return std::error_code();
190}
191
Rui Ueyamadae16612015-06-29 22:16:21 +0000192Undefined *ObjectFile::createUndefined(COFFSymbolRef Sym) {
Rui Ueyama57fe78d2015-06-08 19:43:59 +0000193 StringRef Name;
Rui Ueyamadae16612015-06-29 22:16:21 +0000194 COFFObj->getSymbolName(Sym, Name);
195 return new (Alloc) Undefined(Name);
196}
197
198Undefined *ObjectFile::createWeakExternal(COFFSymbolRef Sym, const void *AuxP) {
199 StringRef Name;
200 COFFObj->getSymbolName(Sym, Name);
Rui Ueyama48975962015-07-01 22:32:23 +0000201 auto *U = new (Alloc) Undefined(Name);
Rui Ueyamadae16612015-06-29 22:16:21 +0000202 auto *Aux = (const coff_aux_weak_external *)AuxP;
Peter Collingbourneda2f0942015-07-03 22:03:36 +0000203 U->WeakAlias = SparseSymbolBodies[Aux->TagIndex];
Rui Ueyama48975962015-07-01 22:32:23 +0000204 return U;
Rui Ueyamadae16612015-06-29 22:16:21 +0000205}
206
207Defined *ObjectFile::createDefined(COFFSymbolRef Sym, const void *AuxP,
208 bool IsFirst) {
209 StringRef Name;
Rui Ueyama411c63602015-05-28 19:09:30 +0000210 if (Sym.isCommon()) {
Rui Ueyamafc510f42015-06-25 19:10:58 +0000211 auto *C = new (Alloc) CommonChunk(Sym);
Rui Ueyama411c63602015-05-28 19:09:30 +0000212 Chunks.push_back(C);
Rui Ueyama68633f12015-06-25 23:22:00 +0000213 return new (Alloc) DefinedCommon(this, Sym, C);
Rui Ueyama411c63602015-05-28 19:09:30 +0000214 }
Rui Ueyama57fe78d2015-06-08 19:43:59 +0000215 if (Sym.isAbsolute()) {
216 COFFObj->getSymbolName(Sym, Name);
217 // Skip special symbols.
218 if (Name == "@comp.id" || Name == "@feat.00")
219 return nullptr;
Rui Ueyamaccde19d2015-06-26 03:09:23 +0000220 return new (Alloc) DefinedAbsolute(Name, Sym);
Rui Ueyama57fe78d2015-06-08 19:43:59 +0000221 }
Peter Collingbournec7b685d2015-06-24 00:05:50 +0000222 if (Sym.getSectionNumber() == llvm::COFF::IMAGE_SYM_DEBUG)
223 return nullptr;
Chandler Carruthee5bf522015-06-29 21:32:37 +0000224
225 // Nothing else to do without a section chunk.
226 auto *SC = cast_or_null<SectionChunk>(SparseChunks[Sym.getSectionNumber()]);
227 if (!SC)
228 return nullptr;
229
Rui Ueyama80141a42015-06-08 05:00:42 +0000230 // Handle associative sections
Rui Ueyama411c63602015-05-28 19:09:30 +0000231 if (IsFirst && AuxP) {
Chandler Carruthee5bf522015-06-29 21:32:37 +0000232 auto *Aux = reinterpret_cast<const coff_aux_section_definition *>(AuxP);
233 if (Aux->Selection == IMAGE_COMDAT_SELECT_ASSOCIATIVE)
234 if (auto *ParentSC = cast_or_null<SectionChunk>(
235 SparseChunks[Aux->getNumber(Sym.isBigObj())]))
236 ParentSC->addAssociative(SC);
Rui Ueyama411c63602015-05-28 19:09:30 +0000237 }
Chandler Carruthee5bf522015-06-29 21:32:37 +0000238
239 auto *B = new (Alloc) DefinedRegular(this, Sym, SC);
240 if (SC->isCOMDAT() && Sym.getValue() == 0 && !AuxP)
241 SC->setSymbol(B);
242
243 return B;
Rui Ueyama411c63602015-05-28 19:09:30 +0000244}
245
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000246MachineTypes ObjectFile::getMachineType() {
247 if (COFFObj)
248 return static_cast<MachineTypes>(COFFObj->getMachine());
249 return IMAGE_FILE_MACHINE_UNKNOWN;
250}
251
Rui Ueyama411c63602015-05-28 19:09:30 +0000252std::error_code ImportFile::parse() {
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000253 const char *Buf = MB.getBufferStart();
254 const char *End = MB.getBufferEnd();
Rui Ueyama411c63602015-05-28 19:09:30 +0000255 const auto *Hdr = reinterpret_cast<const coff_import_header *>(Buf);
256
257 // Check if the total size is valid.
Denis Protivensky68336902015-06-01 09:26:32 +0000258 if ((size_t)(End - Buf) != (sizeof(*Hdr) + Hdr->SizeOfData)) {
Rui Ueyama8fd9fb92015-06-01 02:58:15 +0000259 llvm::errs() << "broken import library\n";
260 return make_error_code(LLDError::BrokenFile);
261 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000262
263 // Read names and create an __imp_ symbol.
264 StringRef Name = StringAlloc.save(StringRef(Buf + sizeof(*Hdr)));
265 StringRef ImpName = StringAlloc.save(Twine("__imp_") + Name);
266 StringRef DLLName(Buf + sizeof(coff_import_header) + Name.size() + 1);
Rui Ueyama1c79ce92015-07-08 20:22:50 +0000267 StringRef ExtName;
268 switch (Hdr->getNameType()) {
269 case IMPORT_ORDINAL:
270 ExtName = "";
271 break;
272 case IMPORT_NAME:
273 ExtName = Name;
274 break;
275 case IMPORT_NAME_NOPREFIX:
276 ExtName = Name.ltrim("?@_");
277 break;
278 case IMPORT_NAME_UNDECORATE:
279 ExtName = Name.ltrim("?@_");
280 ExtName = ExtName.substr(0, ExtName.find('@'));
281 break;
282 }
283 auto *ImpSym = new (Alloc) DefinedImportData(DLLName, ImpName, ExtName, Hdr);
Rui Ueyama411c63602015-05-28 19:09:30 +0000284 SymbolBodies.push_back(ImpSym);
285
286 // If type is function, we need to create a thunk which jump to an
287 // address pointed by the __imp_ symbol. (This allows you to call
288 // DLL functions just like regular non-DLL functions.)
289 if (Hdr->getType() == llvm::COFF::IMPORT_CODE)
290 SymbolBodies.push_back(new (Alloc) DefinedImportThunk(Name, ImpSym));
291 return std::error_code();
292}
293
Peter Collingbourne60c16162015-06-01 20:10:10 +0000294std::error_code BitcodeFile::parse() {
295 std::string Err;
Rui Ueyama81b030c2015-06-01 21:19:43 +0000296 M.reset(LTOModule::createFromBuffer(MB.getBufferStart(),
297 MB.getBufferSize(),
298 llvm::TargetOptions(), Err));
Peter Collingbourne60c16162015-06-01 20:10:10 +0000299 if (!Err.empty()) {
300 llvm::errs() << Err << '\n';
301 return make_error_code(LLDError::BrokenFile);
302 }
303
Rui Ueyama223fe1b2015-06-18 20:29:41 +0000304 llvm::BumpPtrStringSaver Saver(Alloc);
Peter Collingbourne60c16162015-06-01 20:10:10 +0000305 for (unsigned I = 0, E = M->getSymbolCount(); I != E; ++I) {
Peter Collingbournedf637ea2015-06-08 20:21:28 +0000306 lto_symbol_attributes Attrs = M->getSymbolAttributes(I);
307 if ((Attrs & LTO_SYMBOL_SCOPE_MASK) == LTO_SYMBOL_SCOPE_INTERNAL)
308 continue;
309
Rui Ueyama223fe1b2015-06-18 20:29:41 +0000310 StringRef SymName = Saver.save(M->getSymbolName(I));
Peter Collingbournedf637ea2015-06-08 20:21:28 +0000311 int SymbolDef = Attrs & LTO_SYMBOL_DEFINITION_MASK;
312 if (SymbolDef == LTO_SYMBOL_DEFINITION_UNDEFINED) {
Peter Collingbourne60c16162015-06-01 20:10:10 +0000313 SymbolBodies.push_back(new (Alloc) Undefined(SymName));
314 } else {
Peter Collingbourne2612a322015-07-04 05:28:41 +0000315 bool Replaceable =
316 (SymbolDef == LTO_SYMBOL_DEFINITION_TENTATIVE || // common
317 (Attrs & LTO_SYMBOL_COMDAT) || // comdat
318 (SymbolDef == LTO_SYMBOL_DEFINITION_WEAK && // weak external
319 (Attrs & LTO_SYMBOL_ALIAS)));
Peter Collingbournef7b27d12015-06-30 00:47:52 +0000320 SymbolBodies.push_back(new (Alloc) DefinedBitcode(this, SymName,
321 Replaceable));
Peter Collingbourne60c16162015-06-01 20:10:10 +0000322 }
323 }
Peter Collingbourneace2f092015-06-06 02:00:45 +0000324
Peter Collingbourne79cfd432015-06-29 23:26:28 +0000325 Directives = M->getLinkerOpts();
Peter Collingbourne60c16162015-06-01 20:10:10 +0000326 return std::error_code();
327}
Rui Ueyama81b030c2015-06-01 21:19:43 +0000328
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000329MachineTypes BitcodeFile::getMachineType() {
330 if (!M)
331 return IMAGE_FILE_MACHINE_UNKNOWN;
332 switch (Triple(M->getTargetTriple()).getArch()) {
333 case Triple::x86_64:
334 return IMAGE_FILE_MACHINE_AMD64;
335 case Triple::x86:
336 return IMAGE_FILE_MACHINE_I386;
337 case Triple::arm:
338 return IMAGE_FILE_MACHINE_ARMNT;
339 default:
340 return IMAGE_FILE_MACHINE_UNKNOWN;
341 }
342}
343
Rui Ueyama411c63602015-05-28 19:09:30 +0000344} // namespace coff
345} // namespace lld