blob: 20cc25f6692234cda925e35d974d13bbcd677871 [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);
Rui Ueyama48975962015-07-01 22:32:23 +0000198 auto *U = new (Alloc) Undefined(Name);
Rui Ueyamadae16612015-06-29 22:16:21 +0000199 auto *Aux = (const coff_aux_weak_external *)AuxP;
Rui Ueyama3d4c69c2015-07-02 02:38:59 +0000200 U->WeakAlias = cast<Undefined>(SparseSymbolBodies[Aux->TagIndex]);
Rui Ueyama48975962015-07-01 22:32:23 +0000201 return U;
Rui Ueyamadae16612015-06-29 22:16:21 +0000202}
203
204Defined *ObjectFile::createDefined(COFFSymbolRef Sym, const void *AuxP,
205 bool IsFirst) {
206 StringRef Name;
Rui Ueyama411c63602015-05-28 19:09:30 +0000207 if (Sym.isCommon()) {
Rui Ueyamafc510f42015-06-25 19:10:58 +0000208 auto *C = new (Alloc) CommonChunk(Sym);
Rui Ueyama411c63602015-05-28 19:09:30 +0000209 Chunks.push_back(C);
Rui Ueyama68633f12015-06-25 23:22:00 +0000210 return new (Alloc) DefinedCommon(this, Sym, C);
Rui Ueyama411c63602015-05-28 19:09:30 +0000211 }
Rui Ueyama57fe78d2015-06-08 19:43:59 +0000212 if (Sym.isAbsolute()) {
213 COFFObj->getSymbolName(Sym, Name);
214 // Skip special symbols.
215 if (Name == "@comp.id" || Name == "@feat.00")
216 return nullptr;
Rui Ueyamaccde19d2015-06-26 03:09:23 +0000217 return new (Alloc) DefinedAbsolute(Name, Sym);
Rui Ueyama57fe78d2015-06-08 19:43:59 +0000218 }
Peter Collingbournec7b685d2015-06-24 00:05:50 +0000219 if (Sym.getSectionNumber() == llvm::COFF::IMAGE_SYM_DEBUG)
220 return nullptr;
Chandler Carruthee5bf522015-06-29 21:32:37 +0000221
222 // Nothing else to do without a section chunk.
223 auto *SC = cast_or_null<SectionChunk>(SparseChunks[Sym.getSectionNumber()]);
224 if (!SC)
225 return nullptr;
226
Rui Ueyama80141a42015-06-08 05:00:42 +0000227 // Handle associative sections
Rui Ueyama411c63602015-05-28 19:09:30 +0000228 if (IsFirst && AuxP) {
Chandler Carruthee5bf522015-06-29 21:32:37 +0000229 auto *Aux = reinterpret_cast<const coff_aux_section_definition *>(AuxP);
230 if (Aux->Selection == IMAGE_COMDAT_SELECT_ASSOCIATIVE)
231 if (auto *ParentSC = cast_or_null<SectionChunk>(
232 SparseChunks[Aux->getNumber(Sym.isBigObj())]))
233 ParentSC->addAssociative(SC);
Rui Ueyama411c63602015-05-28 19:09:30 +0000234 }
Chandler Carruthee5bf522015-06-29 21:32:37 +0000235
236 auto *B = new (Alloc) DefinedRegular(this, Sym, SC);
237 if (SC->isCOMDAT() && Sym.getValue() == 0 && !AuxP)
238 SC->setSymbol(B);
239
240 return B;
Rui Ueyama411c63602015-05-28 19:09:30 +0000241}
242
243std::error_code ImportFile::parse() {
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000244 const char *Buf = MB.getBufferStart();
245 const char *End = MB.getBufferEnd();
Rui Ueyama411c63602015-05-28 19:09:30 +0000246 const auto *Hdr = reinterpret_cast<const coff_import_header *>(Buf);
247
248 // Check if the total size is valid.
Denis Protivensky68336902015-06-01 09:26:32 +0000249 if ((size_t)(End - Buf) != (sizeof(*Hdr) + Hdr->SizeOfData)) {
Rui Ueyama8fd9fb92015-06-01 02:58:15 +0000250 llvm::errs() << "broken import library\n";
251 return make_error_code(LLDError::BrokenFile);
252 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000253
254 // Read names and create an __imp_ symbol.
255 StringRef Name = StringAlloc.save(StringRef(Buf + sizeof(*Hdr)));
256 StringRef ImpName = StringAlloc.save(Twine("__imp_") + Name);
257 StringRef DLLName(Buf + sizeof(coff_import_header) + Name.size() + 1);
Rui Ueyamafd99e012015-06-01 21:05:27 +0000258 StringRef ExternalName = Name;
259 if (Hdr->getNameType() == llvm::COFF::IMPORT_ORDINAL)
260 ExternalName = "";
261 auto *ImpSym = new (Alloc) DefinedImportData(DLLName, ImpName, ExternalName,
262 Hdr);
Rui Ueyama411c63602015-05-28 19:09:30 +0000263 SymbolBodies.push_back(ImpSym);
264
265 // If type is function, we need to create a thunk which jump to an
266 // address pointed by the __imp_ symbol. (This allows you to call
267 // DLL functions just like regular non-DLL functions.)
268 if (Hdr->getType() == llvm::COFF::IMPORT_CODE)
269 SymbolBodies.push_back(new (Alloc) DefinedImportThunk(Name, ImpSym));
270 return std::error_code();
271}
272
Peter Collingbourne60c16162015-06-01 20:10:10 +0000273std::error_code BitcodeFile::parse() {
274 std::string Err;
Rui Ueyama81b030c2015-06-01 21:19:43 +0000275 M.reset(LTOModule::createFromBuffer(MB.getBufferStart(),
276 MB.getBufferSize(),
277 llvm::TargetOptions(), Err));
Peter Collingbourne60c16162015-06-01 20:10:10 +0000278 if (!Err.empty()) {
279 llvm::errs() << Err << '\n';
280 return make_error_code(LLDError::BrokenFile);
281 }
282
Rui Ueyama223fe1b2015-06-18 20:29:41 +0000283 llvm::BumpPtrStringSaver Saver(Alloc);
Peter Collingbourne60c16162015-06-01 20:10:10 +0000284 for (unsigned I = 0, E = M->getSymbolCount(); I != E; ++I) {
Peter Collingbournedf637ea2015-06-08 20:21:28 +0000285 lto_symbol_attributes Attrs = M->getSymbolAttributes(I);
286 if ((Attrs & LTO_SYMBOL_SCOPE_MASK) == LTO_SYMBOL_SCOPE_INTERNAL)
287 continue;
288
Rui Ueyama223fe1b2015-06-18 20:29:41 +0000289 StringRef SymName = Saver.save(M->getSymbolName(I));
Peter Collingbournedf637ea2015-06-08 20:21:28 +0000290 int SymbolDef = Attrs & LTO_SYMBOL_DEFINITION_MASK;
291 if (SymbolDef == LTO_SYMBOL_DEFINITION_UNDEFINED) {
Peter Collingbourne60c16162015-06-01 20:10:10 +0000292 SymbolBodies.push_back(new (Alloc) Undefined(SymName));
293 } else {
Peter Collingbourne1b6fd1f2015-06-11 21:49:54 +0000294 bool Replaceable = (SymbolDef == LTO_SYMBOL_DEFINITION_TENTATIVE ||
295 (Attrs & LTO_SYMBOL_COMDAT));
Peter Collingbournef7b27d12015-06-30 00:47:52 +0000296 SymbolBodies.push_back(new (Alloc) DefinedBitcode(this, SymName,
297 Replaceable));
Peter Collingbourne60c16162015-06-01 20:10:10 +0000298 }
299 }
Peter Collingbourneace2f092015-06-06 02:00:45 +0000300
Peter Collingbourne79cfd432015-06-29 23:26:28 +0000301 Directives = M->getLinkerOpts();
Peter Collingbourne60c16162015-06-01 20:10:10 +0000302 return std::error_code();
303}
Rui Ueyama81b030c2015-06-01 21:19:43 +0000304
Rui Ueyama411c63602015-05-28 19:09:30 +0000305} // namespace coff
306} // namespace lld