blob: 696f7dfcbdc60b3da491c3bc216bcde76ac5a7e1 [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 }
Rui Ueyama95dd08e2015-07-06 18:22:16 +000076
77 // Seen is a map from member files to boolean values. Initially
78 // all members are mapped to false, which indicates all these files
79 // are not read yet.
80 for (const Archive::Child &Child : File->children())
81 Seen[Child.getBuffer().data()].clear();
Rui Ueyama411c63602015-05-28 19:09:30 +000082 return std::error_code();
83}
84
85// Returns a buffer pointing to a member file containing a given symbol.
Rui Ueyamaadcde532015-07-05 22:50:00 +000086// This function is thread-safe.
Rui Ueyama411c63602015-05-28 19:09:30 +000087ErrorOr<MemoryBufferRef> ArchiveFile::getMember(const Archive::Symbol *Sym) {
88 auto ItOrErr = Sym->getMember();
89 if (auto EC = ItOrErr.getError())
90 return EC;
91 Archive::child_iterator It = ItOrErr.get();
92
93 // Return an empty buffer if we have already returned the same buffer.
94 const char *StartAddr = It->getBuffer().data();
Rui Ueyama95dd08e2015-07-06 18:22:16 +000095 if (Seen[StartAddr].test_and_set())
Rui Ueyama411c63602015-05-28 19:09:30 +000096 return MemoryBufferRef();
97 return It->getMemoryBufferRef();
98}
99
100std::error_code ObjectFile::parse() {
Rui Ueyama411c63602015-05-28 19:09:30 +0000101 // Parse a memory buffer as a COFF file.
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000102 auto BinOrErr = createBinary(MB);
Rui Ueyama411c63602015-05-28 19:09:30 +0000103 if (auto EC = BinOrErr.getError())
104 return EC;
105 std::unique_ptr<Binary> Bin = std::move(BinOrErr.get());
106
107 if (auto *Obj = dyn_cast<COFFObjectFile>(Bin.get())) {
108 Bin.release();
109 COFFObj.reset(Obj);
110 } else {
Rui Ueyama8fd9fb92015-06-01 02:58:15 +0000111 llvm::errs() << getName() << " is not a COFF file.\n";
112 return make_error_code(LLDError::InvalidFile);
Rui Ueyama411c63602015-05-28 19:09:30 +0000113 }
114
115 // Read section and symbol tables.
116 if (auto EC = initializeChunks())
117 return EC;
118 return initializeSymbols();
119}
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 Ueyama411c63602015-05-28 19:09:30 +0000138 if (Name == ".drectve") {
139 ArrayRef<uint8_t> Data;
140 COFFObj->getSectionContents(Sec, Data);
Rui Ueyama0569ecf2015-07-04 03:27:46 +0000141 Directives = std::string((const char *)Data.data(), Data.size());
Rui Ueyama411c63602015-05-28 19:09:30 +0000142 continue;
143 }
144 if (Name.startswith(".debug"))
145 continue;
146 if (Sec->Characteristics & llvm::COFF::IMAGE_SCN_LNK_REMOVE)
147 continue;
Peter Collingbournebd3a29d2015-06-24 00:12:36 +0000148 auto *C = new (Alloc) SectionChunk(this, Sec);
Rui Ueyama411c63602015-05-28 19:09:30 +0000149 Chunks.push_back(C);
150 SparseChunks[I] = C;
151 }
152 return std::error_code();
153}
154
155std::error_code ObjectFile::initializeSymbols() {
156 uint32_t NumSymbols = COFFObj->getNumberOfSymbols();
157 SymbolBodies.reserve(NumSymbols);
158 SparseSymbolBodies.resize(NumSymbols);
159 int32_t LastSectionNumber = 0;
160 for (uint32_t I = 0; I < NumSymbols; ++I) {
161 // Get a COFFSymbolRef object.
162 auto SymOrErr = COFFObj->getSymbol(I);
Rui Ueyama8fd9fb92015-06-01 02:58:15 +0000163 if (auto EC = SymOrErr.getError()) {
164 llvm::errs() << "broken object file: " << getName() << ": "
165 << EC.message() << "\n";
166 return make_error_code(LLDError::BrokenFile);
167 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000168 COFFSymbolRef Sym = SymOrErr.get();
169
Rui Ueyama411c63602015-05-28 19:09:30 +0000170 const void *AuxP = nullptr;
171 if (Sym.getNumberOfAuxSymbols())
172 AuxP = COFFObj->getSymbol(I + 1)->getRawPtr();
173 bool IsFirst = (LastSectionNumber != Sym.getSectionNumber());
174
Rui Ueyamadae16612015-06-29 22:16:21 +0000175 SymbolBody *Body = nullptr;
176 if (Sym.isUndefined()) {
177 Body = createUndefined(Sym);
178 } else if (Sym.isWeakExternal()) {
179 Body = createWeakExternal(Sym, AuxP);
180 } else {
181 Body = createDefined(Sym, AuxP, IsFirst);
182 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000183 if (Body) {
184 SymbolBodies.push_back(Body);
185 SparseSymbolBodies[I] = Body;
186 }
187 I += Sym.getNumberOfAuxSymbols();
188 LastSectionNumber = Sym.getSectionNumber();
189 }
190 return std::error_code();
191}
192
Rui Ueyamadae16612015-06-29 22:16:21 +0000193Undefined *ObjectFile::createUndefined(COFFSymbolRef Sym) {
Rui Ueyama57fe78d2015-06-08 19:43:59 +0000194 StringRef Name;
Rui Ueyamadae16612015-06-29 22:16:21 +0000195 COFFObj->getSymbolName(Sym, Name);
196 return new (Alloc) Undefined(Name);
197}
198
199Undefined *ObjectFile::createWeakExternal(COFFSymbolRef Sym, const void *AuxP) {
200 StringRef Name;
201 COFFObj->getSymbolName(Sym, Name);
Rui Ueyama48975962015-07-01 22:32:23 +0000202 auto *U = new (Alloc) Undefined(Name);
Rui Ueyamadae16612015-06-29 22:16:21 +0000203 auto *Aux = (const coff_aux_weak_external *)AuxP;
Peter Collingbourneda2f0942015-07-03 22:03:36 +0000204 U->WeakAlias = SparseSymbolBodies[Aux->TagIndex];
Rui Ueyama48975962015-07-01 22:32:23 +0000205 return U;
Rui Ueyamadae16612015-06-29 22:16:21 +0000206}
207
208Defined *ObjectFile::createDefined(COFFSymbolRef Sym, const void *AuxP,
209 bool IsFirst) {
210 StringRef Name;
Rui Ueyama411c63602015-05-28 19:09:30 +0000211 if (Sym.isCommon()) {
Rui Ueyamafc510f42015-06-25 19:10:58 +0000212 auto *C = new (Alloc) CommonChunk(Sym);
Rui Ueyama411c63602015-05-28 19:09:30 +0000213 Chunks.push_back(C);
Rui Ueyama68633f12015-06-25 23:22:00 +0000214 return new (Alloc) DefinedCommon(this, Sym, C);
Rui Ueyama411c63602015-05-28 19:09:30 +0000215 }
Rui Ueyama57fe78d2015-06-08 19:43:59 +0000216 if (Sym.isAbsolute()) {
217 COFFObj->getSymbolName(Sym, Name);
218 // Skip special symbols.
219 if (Name == "@comp.id" || Name == "@feat.00")
220 return nullptr;
Rui Ueyamaccde19d2015-06-26 03:09:23 +0000221 return new (Alloc) DefinedAbsolute(Name, Sym);
Rui Ueyama57fe78d2015-06-08 19:43:59 +0000222 }
Peter Collingbournec7b685d2015-06-24 00:05:50 +0000223 if (Sym.getSectionNumber() == llvm::COFF::IMAGE_SYM_DEBUG)
224 return nullptr;
Chandler Carruthee5bf522015-06-29 21:32:37 +0000225
226 // Nothing else to do without a section chunk.
227 auto *SC = cast_or_null<SectionChunk>(SparseChunks[Sym.getSectionNumber()]);
228 if (!SC)
229 return nullptr;
230
Rui Ueyama80141a42015-06-08 05:00:42 +0000231 // Handle associative sections
Rui Ueyama411c63602015-05-28 19:09:30 +0000232 if (IsFirst && AuxP) {
Chandler Carruthee5bf522015-06-29 21:32:37 +0000233 auto *Aux = reinterpret_cast<const coff_aux_section_definition *>(AuxP);
234 if (Aux->Selection == IMAGE_COMDAT_SELECT_ASSOCIATIVE)
235 if (auto *ParentSC = cast_or_null<SectionChunk>(
236 SparseChunks[Aux->getNumber(Sym.isBigObj())]))
237 ParentSC->addAssociative(SC);
Rui Ueyama411c63602015-05-28 19:09:30 +0000238 }
Chandler Carruthee5bf522015-06-29 21:32:37 +0000239
240 auto *B = new (Alloc) DefinedRegular(this, Sym, SC);
241 if (SC->isCOMDAT() && Sym.getValue() == 0 && !AuxP)
242 SC->setSymbol(B);
243
244 return B;
Rui Ueyama411c63602015-05-28 19:09:30 +0000245}
246
247std::error_code ImportFile::parse() {
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000248 const char *Buf = MB.getBufferStart();
249 const char *End = MB.getBufferEnd();
Rui Ueyama411c63602015-05-28 19:09:30 +0000250 const auto *Hdr = reinterpret_cast<const coff_import_header *>(Buf);
251
252 // Check if the total size is valid.
Denis Protivensky68336902015-06-01 09:26:32 +0000253 if ((size_t)(End - Buf) != (sizeof(*Hdr) + Hdr->SizeOfData)) {
Rui Ueyama8fd9fb92015-06-01 02:58:15 +0000254 llvm::errs() << "broken import library\n";
255 return make_error_code(LLDError::BrokenFile);
256 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000257
258 // Read names and create an __imp_ symbol.
259 StringRef Name = StringAlloc.save(StringRef(Buf + sizeof(*Hdr)));
260 StringRef ImpName = StringAlloc.save(Twine("__imp_") + Name);
261 StringRef DLLName(Buf + sizeof(coff_import_header) + Name.size() + 1);
Rui Ueyamafd99e012015-06-01 21:05:27 +0000262 StringRef ExternalName = Name;
263 if (Hdr->getNameType() == llvm::COFF::IMPORT_ORDINAL)
264 ExternalName = "";
265 auto *ImpSym = new (Alloc) DefinedImportData(DLLName, ImpName, ExternalName,
266 Hdr);
Rui Ueyama411c63602015-05-28 19:09:30 +0000267 SymbolBodies.push_back(ImpSym);
268
269 // If type is function, we need to create a thunk which jump to an
270 // address pointed by the __imp_ symbol. (This allows you to call
271 // DLL functions just like regular non-DLL functions.)
272 if (Hdr->getType() == llvm::COFF::IMPORT_CODE)
273 SymbolBodies.push_back(new (Alloc) DefinedImportThunk(Name, ImpSym));
274 return std::error_code();
275}
276
Peter Collingbourne60c16162015-06-01 20:10:10 +0000277std::error_code BitcodeFile::parse() {
278 std::string Err;
Rui Ueyama81b030c2015-06-01 21:19:43 +0000279 M.reset(LTOModule::createFromBuffer(MB.getBufferStart(),
280 MB.getBufferSize(),
281 llvm::TargetOptions(), Err));
Peter Collingbourne60c16162015-06-01 20:10:10 +0000282 if (!Err.empty()) {
283 llvm::errs() << Err << '\n';
284 return make_error_code(LLDError::BrokenFile);
285 }
286
Rui Ueyama223fe1b2015-06-18 20:29:41 +0000287 llvm::BumpPtrStringSaver Saver(Alloc);
Peter Collingbourne60c16162015-06-01 20:10:10 +0000288 for (unsigned I = 0, E = M->getSymbolCount(); I != E; ++I) {
Peter Collingbournedf637ea2015-06-08 20:21:28 +0000289 lto_symbol_attributes Attrs = M->getSymbolAttributes(I);
290 if ((Attrs & LTO_SYMBOL_SCOPE_MASK) == LTO_SYMBOL_SCOPE_INTERNAL)
291 continue;
292
Rui Ueyama223fe1b2015-06-18 20:29:41 +0000293 StringRef SymName = Saver.save(M->getSymbolName(I));
Peter Collingbournedf637ea2015-06-08 20:21:28 +0000294 int SymbolDef = Attrs & LTO_SYMBOL_DEFINITION_MASK;
295 if (SymbolDef == LTO_SYMBOL_DEFINITION_UNDEFINED) {
Peter Collingbourne60c16162015-06-01 20:10:10 +0000296 SymbolBodies.push_back(new (Alloc) Undefined(SymName));
297 } else {
Peter Collingbourne2612a322015-07-04 05:28:41 +0000298 bool Replaceable =
299 (SymbolDef == LTO_SYMBOL_DEFINITION_TENTATIVE || // common
300 (Attrs & LTO_SYMBOL_COMDAT) || // comdat
301 (SymbolDef == LTO_SYMBOL_DEFINITION_WEAK && // weak external
302 (Attrs & LTO_SYMBOL_ALIAS)));
Peter Collingbournef7b27d12015-06-30 00:47:52 +0000303 SymbolBodies.push_back(new (Alloc) DefinedBitcode(this, SymName,
304 Replaceable));
Peter Collingbourne60c16162015-06-01 20:10:10 +0000305 }
306 }
Peter Collingbourneace2f092015-06-06 02:00:45 +0000307
Peter Collingbourne79cfd432015-06-29 23:26:28 +0000308 Directives = M->getLinkerOpts();
Peter Collingbourne60c16162015-06-01 20:10:10 +0000309 return std::error_code();
310}
Rui Ueyama81b030c2015-06-01 21:19:43 +0000311
Rui Ueyama411c63602015-05-28 19:09:30 +0000312} // namespace coff
313} // namespace lld