blob: a0211623f62d19cf5ed4fd2c795a185d71129919 [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;
27using llvm::sys::fs::identify_magic;
28using llvm::sys::fs::file_magic;
29
30namespace lld {
31namespace coff {
32
Rui Ueyama65813ed2015-07-02 20:33:48 +000033int InputFile::NextIndex = 0;
34
Rui Ueyama411c63602015-05-28 19:09:30 +000035// Returns the last element of a path, which is supposed to be a filename.
36static StringRef getBasename(StringRef Path) {
Rui Ueyamaea63a282015-06-18 20:16:26 +000037 size_t Pos = Path.find_last_of("\\/");
Rui Ueyama411c63602015-05-28 19:09:30 +000038 if (Pos == StringRef::npos)
39 return Path;
40 return Path.substr(Pos + 1);
41}
42
43// Returns a string in the format of "foo.obj" or "foo.obj(bar.lib)".
44std::string InputFile::getShortName() {
45 if (ParentName == "")
46 return getName().lower();
47 std::string Res = (getBasename(ParentName) + "(" +
48 getBasename(getName()) + ")").str();
49 return StringRef(Res).lower();
50}
51
52std::error_code ArchiveFile::parse() {
Rui Ueyamad7c2f582015-05-31 21:04:56 +000053 // Parse a MemoryBufferRef as an archive file.
54 auto ArchiveOrErr = Archive::create(MB);
Rui Ueyama411c63602015-05-28 19:09:30 +000055 if (auto EC = ArchiveOrErr.getError())
56 return EC;
57 File = std::move(ArchiveOrErr.get());
58
59 // Allocate a buffer for Lazy objects.
Rui Ueyama605e1f62015-06-26 23:51:45 +000060 size_t NumSyms = File->getNumberOfSymbols();
61 size_t BufSize = NumSyms * sizeof(Lazy);
Rui Ueyama411c63602015-05-28 19:09:30 +000062 Lazy *Buf = (Lazy *)Alloc.Allocate(BufSize, llvm::alignOf<Lazy>());
Rui Ueyama8d3010a2015-06-30 19:35:21 +000063 LazySymbols.reserve(NumSyms);
Rui Ueyama411c63602015-05-28 19:09:30 +000064
65 // Read the symbol table to construct Lazy objects.
66 uint32_t I = 0;
67 for (const Archive::Symbol &Sym : File->symbols()) {
Rui Ueyama29792a82015-06-19 21:25:44 +000068 auto *B = new (&Buf[I++]) Lazy(this, Sym);
Rui Ueyama411c63602015-05-28 19:09:30 +000069 // Skip special symbol exists in import library files.
Rui Ueyama29792a82015-06-19 21:25:44 +000070 if (B->getName() != "__NULL_IMPORT_DESCRIPTOR")
Rui Ueyama8d3010a2015-06-30 19:35:21 +000071 LazySymbols.push_back(B);
Rui Ueyama411c63602015-05-28 19:09:30 +000072 }
Rui Ueyama95dd08e2015-07-06 18:22:16 +000073
74 // Seen is a map from member files to boolean values. Initially
75 // all members are mapped to false, which indicates all these files
76 // are not read yet.
77 for (const Archive::Child &Child : File->children())
78 Seen[Child.getBuffer().data()].clear();
Rui Ueyama411c63602015-05-28 19:09:30 +000079 return std::error_code();
80}
81
82// Returns a buffer pointing to a member file containing a given symbol.
Rui Ueyamaadcde532015-07-05 22:50:00 +000083// This function is thread-safe.
Rui Ueyama411c63602015-05-28 19:09:30 +000084ErrorOr<MemoryBufferRef> ArchiveFile::getMember(const Archive::Symbol *Sym) {
85 auto ItOrErr = Sym->getMember();
86 if (auto EC = ItOrErr.getError())
87 return EC;
88 Archive::child_iterator It = ItOrErr.get();
89
90 // Return an empty buffer if we have already returned the same buffer.
91 const char *StartAddr = It->getBuffer().data();
Rui Ueyama95dd08e2015-07-06 18:22:16 +000092 if (Seen[StartAddr].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;
115 return initializeSymbols();
116}
117
Rui Ueyama411c63602015-05-28 19:09:30 +0000118std::error_code ObjectFile::initializeChunks() {
119 uint32_t NumSections = COFFObj->getNumberOfSections();
120 Chunks.reserve(NumSections);
121 SparseChunks.resize(NumSections + 1);
122 for (uint32_t I = 1; I < NumSections + 1; ++I) {
123 const coff_section *Sec;
124 StringRef Name;
Rui Ueyama8fd9fb92015-06-01 02:58:15 +0000125 if (auto EC = COFFObj->getSection(I, Sec)) {
126 llvm::errs() << "getSection failed: " << Name << ": "
127 << EC.message() << "\n";
128 return make_error_code(LLDError::BrokenFile);
129 }
130 if (auto EC = COFFObj->getSectionName(Sec, Name)) {
131 llvm::errs() << "getSectionName failed: " << Name << ": "
132 << EC.message() << "\n";
133 return make_error_code(LLDError::BrokenFile);
134 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000135 if (Name == ".drectve") {
136 ArrayRef<uint8_t> Data;
137 COFFObj->getSectionContents(Sec, Data);
Rui Ueyama0569ecf2015-07-04 03:27:46 +0000138 Directives = std::string((const char *)Data.data(), Data.size());
Rui Ueyama411c63602015-05-28 19:09:30 +0000139 continue;
140 }
David Majnemer2c345a32015-07-08 16:37:50 +0000141 // We want to preserve DWARF debug sections only when /debug is on.
142 if (!Config->Debug && Name.startswith(".debug"))
Rui Ueyama411c63602015-05-28 19:09:30 +0000143 continue;
144 if (Sec->Characteristics & llvm::COFF::IMAGE_SCN_LNK_REMOVE)
145 continue;
Peter Collingbournebd3a29d2015-06-24 00:12:36 +0000146 auto *C = new (Alloc) SectionChunk(this, Sec);
Rui Ueyama411c63602015-05-28 19:09:30 +0000147 Chunks.push_back(C);
148 SparseChunks[I] = C;
149 }
150 return std::error_code();
151}
152
153std::error_code ObjectFile::initializeSymbols() {
154 uint32_t NumSymbols = COFFObj->getNumberOfSymbols();
155 SymbolBodies.reserve(NumSymbols);
156 SparseSymbolBodies.resize(NumSymbols);
157 int32_t LastSectionNumber = 0;
158 for (uint32_t I = 0; I < NumSymbols; ++I) {
159 // Get a COFFSymbolRef object.
160 auto SymOrErr = COFFObj->getSymbol(I);
Rui Ueyama8fd9fb92015-06-01 02:58:15 +0000161 if (auto EC = SymOrErr.getError()) {
162 llvm::errs() << "broken object file: " << getName() << ": "
163 << EC.message() << "\n";
164 return make_error_code(LLDError::BrokenFile);
165 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000166 COFFSymbolRef Sym = SymOrErr.get();
167
Rui Ueyama411c63602015-05-28 19:09:30 +0000168 const void *AuxP = nullptr;
169 if (Sym.getNumberOfAuxSymbols())
170 AuxP = COFFObj->getSymbol(I + 1)->getRawPtr();
171 bool IsFirst = (LastSectionNumber != Sym.getSectionNumber());
172
Rui Ueyamadae16612015-06-29 22:16:21 +0000173 SymbolBody *Body = nullptr;
174 if (Sym.isUndefined()) {
175 Body = createUndefined(Sym);
176 } else if (Sym.isWeakExternal()) {
177 Body = createWeakExternal(Sym, AuxP);
178 } else {
179 Body = createDefined(Sym, AuxP, IsFirst);
180 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000181 if (Body) {
182 SymbolBodies.push_back(Body);
183 SparseSymbolBodies[I] = Body;
184 }
185 I += Sym.getNumberOfAuxSymbols();
186 LastSectionNumber = Sym.getSectionNumber();
187 }
188 return std::error_code();
189}
190
Rui Ueyamadae16612015-06-29 22:16:21 +0000191Undefined *ObjectFile::createUndefined(COFFSymbolRef Sym) {
Rui Ueyama57fe78d2015-06-08 19:43:59 +0000192 StringRef Name;
Rui Ueyamadae16612015-06-29 22:16:21 +0000193 COFFObj->getSymbolName(Sym, Name);
194 return new (Alloc) Undefined(Name);
195}
196
197Undefined *ObjectFile::createWeakExternal(COFFSymbolRef Sym, const void *AuxP) {
198 StringRef Name;
199 COFFObj->getSymbolName(Sym, Name);
Rui Ueyama48975962015-07-01 22:32:23 +0000200 auto *U = new (Alloc) Undefined(Name);
Rui Ueyamadae16612015-06-29 22:16:21 +0000201 auto *Aux = (const coff_aux_weak_external *)AuxP;
Peter Collingbourneda2f0942015-07-03 22:03:36 +0000202 U->WeakAlias = SparseSymbolBodies[Aux->TagIndex];
Rui Ueyama48975962015-07-01 22:32:23 +0000203 return U;
Rui Ueyamadae16612015-06-29 22:16:21 +0000204}
205
206Defined *ObjectFile::createDefined(COFFSymbolRef Sym, const void *AuxP,
207 bool IsFirst) {
208 StringRef Name;
Rui Ueyama411c63602015-05-28 19:09:30 +0000209 if (Sym.isCommon()) {
Rui Ueyamafc510f42015-06-25 19:10:58 +0000210 auto *C = new (Alloc) CommonChunk(Sym);
Rui Ueyama411c63602015-05-28 19:09:30 +0000211 Chunks.push_back(C);
Rui Ueyama68633f12015-06-25 23:22:00 +0000212 return new (Alloc) DefinedCommon(this, Sym, C);
Rui Ueyama411c63602015-05-28 19:09:30 +0000213 }
Rui Ueyama57fe78d2015-06-08 19:43:59 +0000214 if (Sym.isAbsolute()) {
215 COFFObj->getSymbolName(Sym, Name);
216 // Skip special symbols.
217 if (Name == "@comp.id" || Name == "@feat.00")
218 return nullptr;
Rui Ueyamaccde19d2015-06-26 03:09:23 +0000219 return new (Alloc) DefinedAbsolute(Name, Sym);
Rui Ueyama57fe78d2015-06-08 19:43:59 +0000220 }
Peter Collingbournec7b685d2015-06-24 00:05:50 +0000221 if (Sym.getSectionNumber() == llvm::COFF::IMAGE_SYM_DEBUG)
222 return nullptr;
Chandler Carruthee5bf522015-06-29 21:32:37 +0000223
224 // Nothing else to do without a section chunk.
225 auto *SC = cast_or_null<SectionChunk>(SparseChunks[Sym.getSectionNumber()]);
226 if (!SC)
227 return nullptr;
228
Rui Ueyama80141a42015-06-08 05:00:42 +0000229 // Handle associative sections
Rui Ueyama411c63602015-05-28 19:09:30 +0000230 if (IsFirst && AuxP) {
Chandler Carruthee5bf522015-06-29 21:32:37 +0000231 auto *Aux = reinterpret_cast<const coff_aux_section_definition *>(AuxP);
232 if (Aux->Selection == IMAGE_COMDAT_SELECT_ASSOCIATIVE)
233 if (auto *ParentSC = cast_or_null<SectionChunk>(
234 SparseChunks[Aux->getNumber(Sym.isBigObj())]))
235 ParentSC->addAssociative(SC);
Rui Ueyama411c63602015-05-28 19:09:30 +0000236 }
Chandler Carruthee5bf522015-06-29 21:32:37 +0000237
238 auto *B = new (Alloc) DefinedRegular(this, Sym, SC);
239 if (SC->isCOMDAT() && Sym.getValue() == 0 && !AuxP)
240 SC->setSymbol(B);
241
242 return B;
Rui Ueyama411c63602015-05-28 19:09:30 +0000243}
244
245std::error_code ImportFile::parse() {
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000246 const char *Buf = MB.getBufferStart();
247 const char *End = MB.getBufferEnd();
Rui Ueyama411c63602015-05-28 19:09:30 +0000248 const auto *Hdr = reinterpret_cast<const coff_import_header *>(Buf);
249
250 // Check if the total size is valid.
Denis Protivensky68336902015-06-01 09:26:32 +0000251 if ((size_t)(End - Buf) != (sizeof(*Hdr) + Hdr->SizeOfData)) {
Rui Ueyama8fd9fb92015-06-01 02:58:15 +0000252 llvm::errs() << "broken import library\n";
253 return make_error_code(LLDError::BrokenFile);
254 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000255
256 // Read names and create an __imp_ symbol.
257 StringRef Name = StringAlloc.save(StringRef(Buf + sizeof(*Hdr)));
258 StringRef ImpName = StringAlloc.save(Twine("__imp_") + Name);
259 StringRef DLLName(Buf + sizeof(coff_import_header) + Name.size() + 1);
Rui Ueyama1c79ce92015-07-08 20:22:50 +0000260 StringRef ExtName;
261 switch (Hdr->getNameType()) {
262 case IMPORT_ORDINAL:
263 ExtName = "";
264 break;
265 case IMPORT_NAME:
266 ExtName = Name;
267 break;
268 case IMPORT_NAME_NOPREFIX:
269 ExtName = Name.ltrim("?@_");
270 break;
271 case IMPORT_NAME_UNDECORATE:
272 ExtName = Name.ltrim("?@_");
273 ExtName = ExtName.substr(0, ExtName.find('@'));
274 break;
275 }
276 auto *ImpSym = new (Alloc) DefinedImportData(DLLName, ImpName, ExtName, Hdr);
Rui Ueyama411c63602015-05-28 19:09:30 +0000277 SymbolBodies.push_back(ImpSym);
278
279 // If type is function, we need to create a thunk which jump to an
280 // address pointed by the __imp_ symbol. (This allows you to call
281 // DLL functions just like regular non-DLL functions.)
282 if (Hdr->getType() == llvm::COFF::IMPORT_CODE)
283 SymbolBodies.push_back(new (Alloc) DefinedImportThunk(Name, ImpSym));
284 return std::error_code();
285}
286
Peter Collingbourne60c16162015-06-01 20:10:10 +0000287std::error_code BitcodeFile::parse() {
288 std::string Err;
Rui Ueyama81b030c2015-06-01 21:19:43 +0000289 M.reset(LTOModule::createFromBuffer(MB.getBufferStart(),
290 MB.getBufferSize(),
291 llvm::TargetOptions(), Err));
Peter Collingbourne60c16162015-06-01 20:10:10 +0000292 if (!Err.empty()) {
293 llvm::errs() << Err << '\n';
294 return make_error_code(LLDError::BrokenFile);
295 }
296
Rui Ueyama223fe1b2015-06-18 20:29:41 +0000297 llvm::BumpPtrStringSaver Saver(Alloc);
Peter Collingbourne60c16162015-06-01 20:10:10 +0000298 for (unsigned I = 0, E = M->getSymbolCount(); I != E; ++I) {
Peter Collingbournedf637ea2015-06-08 20:21:28 +0000299 lto_symbol_attributes Attrs = M->getSymbolAttributes(I);
300 if ((Attrs & LTO_SYMBOL_SCOPE_MASK) == LTO_SYMBOL_SCOPE_INTERNAL)
301 continue;
302
Rui Ueyama223fe1b2015-06-18 20:29:41 +0000303 StringRef SymName = Saver.save(M->getSymbolName(I));
Peter Collingbournedf637ea2015-06-08 20:21:28 +0000304 int SymbolDef = Attrs & LTO_SYMBOL_DEFINITION_MASK;
305 if (SymbolDef == LTO_SYMBOL_DEFINITION_UNDEFINED) {
Peter Collingbourne60c16162015-06-01 20:10:10 +0000306 SymbolBodies.push_back(new (Alloc) Undefined(SymName));
307 } else {
Peter Collingbourne2612a322015-07-04 05:28:41 +0000308 bool Replaceable =
309 (SymbolDef == LTO_SYMBOL_DEFINITION_TENTATIVE || // common
310 (Attrs & LTO_SYMBOL_COMDAT) || // comdat
311 (SymbolDef == LTO_SYMBOL_DEFINITION_WEAK && // weak external
312 (Attrs & LTO_SYMBOL_ALIAS)));
Peter Collingbournef7b27d12015-06-30 00:47:52 +0000313 SymbolBodies.push_back(new (Alloc) DefinedBitcode(this, SymName,
314 Replaceable));
Peter Collingbourne60c16162015-06-01 20:10:10 +0000315 }
316 }
Peter Collingbourneace2f092015-06-06 02:00:45 +0000317
Peter Collingbourne79cfd432015-06-29 23:26:28 +0000318 Directives = M->getLinkerOpts();
Peter Collingbourne60c16162015-06-01 20:10:10 +0000319 return std::error_code();
320}
Rui Ueyama81b030c2015-06-01 21:19:43 +0000321
Rui Ueyama411c63602015-05-28 19:09:30 +0000322} // namespace coff
323} // namespace lld