blob: 9187504280cb31e5d90b29dce89475017e56d030 [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"
21
22using namespace llvm::object;
23using namespace llvm::support::endian;
24using llvm::COFF::ImportHeader;
Rui Ueyama80141a42015-06-08 05:00:42 +000025using llvm::COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
Rui Ueyamaa2994882015-06-26 00:42:21 +000026using llvm::COFF::IMAGE_FILE_MACHINE_AMD64;
27using llvm::COFF::IMAGE_FILE_MACHINE_UNKNOWN;
Rui Ueyama411c63602015-05-28 19:09:30 +000028using llvm::RoundUpToAlignment;
29using llvm::sys::fs::identify_magic;
30using llvm::sys::fs::file_magic;
31
32namespace lld {
33namespace coff {
34
35// 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 }
73 return std::error_code();
74}
75
76// Returns a buffer pointing to a member file containing a given symbol.
77ErrorOr<MemoryBufferRef> ArchiveFile::getMember(const Archive::Symbol *Sym) {
78 auto ItOrErr = Sym->getMember();
79 if (auto EC = ItOrErr.getError())
80 return EC;
81 Archive::child_iterator It = ItOrErr.get();
82
83 // Return an empty buffer if we have already returned the same buffer.
84 const char *StartAddr = It->getBuffer().data();
85 auto Pair = Seen.insert(StartAddr);
86 if (!Pair.second)
87 return MemoryBufferRef();
88 return It->getMemoryBufferRef();
89}
90
91std::error_code ObjectFile::parse() {
Rui Ueyama411c63602015-05-28 19:09:30 +000092 // Parse a memory buffer as a COFF file.
Rui Ueyamad7c2f582015-05-31 21:04:56 +000093 auto BinOrErr = createBinary(MB);
Rui Ueyama411c63602015-05-28 19:09:30 +000094 if (auto EC = BinOrErr.getError())
95 return EC;
96 std::unique_ptr<Binary> Bin = std::move(BinOrErr.get());
97
98 if (auto *Obj = dyn_cast<COFFObjectFile>(Bin.get())) {
99 Bin.release();
100 COFFObj.reset(Obj);
101 } else {
Rui Ueyama8fd9fb92015-06-01 02:58:15 +0000102 llvm::errs() << getName() << " is not a COFF file.\n";
103 return make_error_code(LLDError::InvalidFile);
Rui Ueyama411c63602015-05-28 19:09:30 +0000104 }
Rui Ueyamaa2994882015-06-26 00:42:21 +0000105 if (COFFObj->getMachine() != IMAGE_FILE_MACHINE_AMD64 &&
106 COFFObj->getMachine() != IMAGE_FILE_MACHINE_UNKNOWN) {
107 llvm::errs() << getName() << " is not an x64 object file.\n";
108 return make_error_code(LLDError::InvalidFile);
109 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000110
111 // Read section and symbol tables.
112 if (auto EC = initializeChunks())
113 return EC;
114 return initializeSymbols();
115}
116
Rui Ueyama411c63602015-05-28 19:09:30 +0000117std::error_code ObjectFile::initializeChunks() {
118 uint32_t NumSections = COFFObj->getNumberOfSections();
119 Chunks.reserve(NumSections);
120 SparseChunks.resize(NumSections + 1);
121 for (uint32_t I = 1; I < NumSections + 1; ++I) {
122 const coff_section *Sec;
123 StringRef Name;
Rui Ueyama8fd9fb92015-06-01 02:58:15 +0000124 if (auto EC = COFFObj->getSection(I, Sec)) {
125 llvm::errs() << "getSection failed: " << Name << ": "
126 << EC.message() << "\n";
127 return make_error_code(LLDError::BrokenFile);
128 }
129 if (auto EC = COFFObj->getSectionName(Sec, Name)) {
130 llvm::errs() << "getSectionName failed: " << Name << ": "
131 << EC.message() << "\n";
132 return make_error_code(LLDError::BrokenFile);
133 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000134 if (Name == ".drectve") {
135 ArrayRef<uint8_t> Data;
136 COFFObj->getSectionContents(Sec, Data);
Rui Ueyamae3a33502015-06-20 23:10:05 +0000137 Directives = std::string((const char *)Data.data(), Data.size());
Rui Ueyama411c63602015-05-28 19:09:30 +0000138 continue;
139 }
140 if (Name.startswith(".debug"))
141 continue;
142 if (Sec->Characteristics & llvm::COFF::IMAGE_SCN_LNK_REMOVE)
143 continue;
Peter Collingbournebd3a29d2015-06-24 00:12:36 +0000144 auto *C = new (Alloc) SectionChunk(this, Sec);
Rui Ueyama411c63602015-05-28 19:09:30 +0000145 Chunks.push_back(C);
146 SparseChunks[I] = C;
147 }
148 return std::error_code();
149}
150
151std::error_code ObjectFile::initializeSymbols() {
152 uint32_t NumSymbols = COFFObj->getNumberOfSymbols();
153 SymbolBodies.reserve(NumSymbols);
154 SparseSymbolBodies.resize(NumSymbols);
155 int32_t LastSectionNumber = 0;
156 for (uint32_t I = 0; I < NumSymbols; ++I) {
157 // Get a COFFSymbolRef object.
158 auto SymOrErr = COFFObj->getSymbol(I);
Rui Ueyama8fd9fb92015-06-01 02:58:15 +0000159 if (auto EC = SymOrErr.getError()) {
160 llvm::errs() << "broken object file: " << getName() << ": "
161 << EC.message() << "\n";
162 return make_error_code(LLDError::BrokenFile);
163 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000164 COFFSymbolRef Sym = SymOrErr.get();
165
Rui Ueyama411c63602015-05-28 19:09:30 +0000166 const void *AuxP = nullptr;
167 if (Sym.getNumberOfAuxSymbols())
168 AuxP = COFFObj->getSymbol(I + 1)->getRawPtr();
169 bool IsFirst = (LastSectionNumber != Sym.getSectionNumber());
170
Rui Ueyamadae16612015-06-29 22:16:21 +0000171 SymbolBody *Body = nullptr;
172 if (Sym.isUndefined()) {
173 Body = createUndefined(Sym);
174 } else if (Sym.isWeakExternal()) {
175 Body = createWeakExternal(Sym, AuxP);
176 } else {
177 Body = createDefined(Sym, AuxP, IsFirst);
178 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000179 if (Body) {
180 SymbolBodies.push_back(Body);
181 SparseSymbolBodies[I] = Body;
182 }
183 I += Sym.getNumberOfAuxSymbols();
184 LastSectionNumber = Sym.getSectionNumber();
185 }
186 return std::error_code();
187}
188
Rui Ueyamadae16612015-06-29 22:16:21 +0000189Undefined *ObjectFile::createUndefined(COFFSymbolRef Sym) {
Rui Ueyama57fe78d2015-06-08 19:43:59 +0000190 StringRef Name;
Rui Ueyamadae16612015-06-29 22:16:21 +0000191 COFFObj->getSymbolName(Sym, Name);
192 return new (Alloc) Undefined(Name);
193}
194
195Undefined *ObjectFile::createWeakExternal(COFFSymbolRef Sym, const void *AuxP) {
196 StringRef Name;
197 COFFObj->getSymbolName(Sym, Name);
198 auto *Aux = (const coff_aux_weak_external *)AuxP;
199 return new (Alloc) Undefined(Name, &SparseSymbolBodies[Aux->TagIndex]);
200}
201
202Defined *ObjectFile::createDefined(COFFSymbolRef Sym, const void *AuxP,
203 bool IsFirst) {
204 StringRef Name;
Rui Ueyama411c63602015-05-28 19:09:30 +0000205 if (Sym.isCommon()) {
Rui Ueyamafc510f42015-06-25 19:10:58 +0000206 auto *C = new (Alloc) CommonChunk(Sym);
Rui Ueyama411c63602015-05-28 19:09:30 +0000207 Chunks.push_back(C);
Rui Ueyama68633f12015-06-25 23:22:00 +0000208 return new (Alloc) DefinedCommon(this, Sym, C);
Rui Ueyama411c63602015-05-28 19:09:30 +0000209 }
Rui Ueyama57fe78d2015-06-08 19:43:59 +0000210 if (Sym.isAbsolute()) {
211 COFFObj->getSymbolName(Sym, Name);
212 // Skip special symbols.
213 if (Name == "@comp.id" || Name == "@feat.00")
214 return nullptr;
Rui Ueyamaccde19d2015-06-26 03:09:23 +0000215 return new (Alloc) DefinedAbsolute(Name, Sym);
Rui Ueyama57fe78d2015-06-08 19:43:59 +0000216 }
Peter Collingbournec7b685d2015-06-24 00:05:50 +0000217 if (Sym.getSectionNumber() == llvm::COFF::IMAGE_SYM_DEBUG)
218 return nullptr;
Chandler Carruthee5bf522015-06-29 21:32:37 +0000219
220 // Nothing else to do without a section chunk.
221 auto *SC = cast_or_null<SectionChunk>(SparseChunks[Sym.getSectionNumber()]);
222 if (!SC)
223 return nullptr;
224
Rui Ueyama80141a42015-06-08 05:00:42 +0000225 // Handle associative sections
Rui Ueyama411c63602015-05-28 19:09:30 +0000226 if (IsFirst && AuxP) {
Chandler Carruthee5bf522015-06-29 21:32:37 +0000227 auto *Aux = reinterpret_cast<const coff_aux_section_definition *>(AuxP);
228 if (Aux->Selection == IMAGE_COMDAT_SELECT_ASSOCIATIVE)
229 if (auto *ParentSC = cast_or_null<SectionChunk>(
230 SparseChunks[Aux->getNumber(Sym.isBigObj())]))
231 ParentSC->addAssociative(SC);
Rui Ueyama411c63602015-05-28 19:09:30 +0000232 }
Chandler Carruthee5bf522015-06-29 21:32:37 +0000233
234 auto *B = new (Alloc) DefinedRegular(this, Sym, SC);
235 if (SC->isCOMDAT() && Sym.getValue() == 0 && !AuxP)
236 SC->setSymbol(B);
237
238 return B;
Rui Ueyama411c63602015-05-28 19:09:30 +0000239}
240
241std::error_code ImportFile::parse() {
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000242 const char *Buf = MB.getBufferStart();
243 const char *End = MB.getBufferEnd();
Rui Ueyama411c63602015-05-28 19:09:30 +0000244 const auto *Hdr = reinterpret_cast<const coff_import_header *>(Buf);
245
246 // Check if the total size is valid.
Denis Protivensky68336902015-06-01 09:26:32 +0000247 if ((size_t)(End - Buf) != (sizeof(*Hdr) + Hdr->SizeOfData)) {
Rui Ueyama8fd9fb92015-06-01 02:58:15 +0000248 llvm::errs() << "broken import library\n";
249 return make_error_code(LLDError::BrokenFile);
250 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000251
252 // Read names and create an __imp_ symbol.
253 StringRef Name = StringAlloc.save(StringRef(Buf + sizeof(*Hdr)));
254 StringRef ImpName = StringAlloc.save(Twine("__imp_") + Name);
255 StringRef DLLName(Buf + sizeof(coff_import_header) + Name.size() + 1);
Rui Ueyamafd99e012015-06-01 21:05:27 +0000256 StringRef ExternalName = Name;
257 if (Hdr->getNameType() == llvm::COFF::IMPORT_ORDINAL)
258 ExternalName = "";
259 auto *ImpSym = new (Alloc) DefinedImportData(DLLName, ImpName, ExternalName,
260 Hdr);
Rui Ueyama411c63602015-05-28 19:09:30 +0000261 SymbolBodies.push_back(ImpSym);
262
263 // If type is function, we need to create a thunk which jump to an
264 // address pointed by the __imp_ symbol. (This allows you to call
265 // DLL functions just like regular non-DLL functions.)
266 if (Hdr->getType() == llvm::COFF::IMPORT_CODE)
267 SymbolBodies.push_back(new (Alloc) DefinedImportThunk(Name, ImpSym));
268 return std::error_code();
269}
270
Peter Collingbourne60c16162015-06-01 20:10:10 +0000271std::error_code BitcodeFile::parse() {
272 std::string Err;
Rui Ueyama81b030c2015-06-01 21:19:43 +0000273 M.reset(LTOModule::createFromBuffer(MB.getBufferStart(),
274 MB.getBufferSize(),
275 llvm::TargetOptions(), Err));
Peter Collingbourne60c16162015-06-01 20:10:10 +0000276 if (!Err.empty()) {
277 llvm::errs() << Err << '\n';
278 return make_error_code(LLDError::BrokenFile);
279 }
280
Rui Ueyama223fe1b2015-06-18 20:29:41 +0000281 llvm::BumpPtrStringSaver Saver(Alloc);
Peter Collingbourne60c16162015-06-01 20:10:10 +0000282 for (unsigned I = 0, E = M->getSymbolCount(); I != E; ++I) {
Peter Collingbournedf637ea2015-06-08 20:21:28 +0000283 lto_symbol_attributes Attrs = M->getSymbolAttributes(I);
284 if ((Attrs & LTO_SYMBOL_SCOPE_MASK) == LTO_SYMBOL_SCOPE_INTERNAL)
285 continue;
286
Rui Ueyama223fe1b2015-06-18 20:29:41 +0000287 StringRef SymName = Saver.save(M->getSymbolName(I));
Peter Collingbournedf637ea2015-06-08 20:21:28 +0000288 int SymbolDef = Attrs & LTO_SYMBOL_DEFINITION_MASK;
289 if (SymbolDef == LTO_SYMBOL_DEFINITION_UNDEFINED) {
Peter Collingbourne60c16162015-06-01 20:10:10 +0000290 SymbolBodies.push_back(new (Alloc) Undefined(SymName));
291 } else {
Peter Collingbourne1b6fd1f2015-06-11 21:49:54 +0000292 bool Replaceable = (SymbolDef == LTO_SYMBOL_DEFINITION_TENTATIVE ||
293 (Attrs & LTO_SYMBOL_COMDAT));
Peter Collingbournef7b27d12015-06-30 00:47:52 +0000294 SymbolBodies.push_back(new (Alloc) DefinedBitcode(this, SymName,
295 Replaceable));
Peter Collingbourne60c16162015-06-01 20:10:10 +0000296 }
297 }
Peter Collingbourneace2f092015-06-06 02:00:45 +0000298
Peter Collingbourne79cfd432015-06-29 23:26:28 +0000299 Directives = M->getLinkerOpts();
Peter Collingbourne60c16162015-06-01 20:10:10 +0000300 return std::error_code();
301}
Rui Ueyama81b030c2015-06-01 21:19:43 +0000302
Rui Ueyama411c63602015-05-28 19:09:30 +0000303} // namespace coff
304} // namespace lld