blob: be5c0ed721c92447fef8b260b08c09056469f814 [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 }
74 return std::error_code();
75}
76
77// Returns a buffer pointing to a member file containing a given symbol.
Rui Ueyamaadcde532015-07-05 22:50:00 +000078// This function is thread-safe.
Rui Ueyama411c63602015-05-28 19:09:30 +000079ErrorOr<MemoryBufferRef> ArchiveFile::getMember(const Archive::Symbol *Sym) {
80 auto ItOrErr = Sym->getMember();
81 if (auto EC = ItOrErr.getError())
82 return EC;
83 Archive::child_iterator It = ItOrErr.get();
84
85 // Return an empty buffer if we have already returned the same buffer.
86 const char *StartAddr = It->getBuffer().data();
Nico Weber9262da22015-07-13 00:55:26 +000087 auto Pair = Seen.insert(StartAddr);
88 if (!Pair.second)
Rui Ueyama411c63602015-05-28 19:09:30 +000089 return MemoryBufferRef();
90 return It->getMemoryBufferRef();
91}
92
93std::error_code ObjectFile::parse() {
Rui Ueyama411c63602015-05-28 19:09:30 +000094 // Parse a memory buffer as a COFF file.
Rui Ueyamad7c2f582015-05-31 21:04:56 +000095 auto BinOrErr = createBinary(MB);
Rui Ueyama411c63602015-05-28 19:09:30 +000096 if (auto EC = BinOrErr.getError())
97 return EC;
98 std::unique_ptr<Binary> Bin = std::move(BinOrErr.get());
99
100 if (auto *Obj = dyn_cast<COFFObjectFile>(Bin.get())) {
101 Bin.release();
102 COFFObj.reset(Obj);
103 } else {
Rui Ueyama8fd9fb92015-06-01 02:58:15 +0000104 llvm::errs() << getName() << " is not a COFF file.\n";
105 return make_error_code(LLDError::InvalidFile);
Rui Ueyama411c63602015-05-28 19:09:30 +0000106 }
107
108 // Read section and symbol tables.
109 if (auto EC = initializeChunks())
110 return EC;
111 return initializeSymbols();
112}
113
Rui Ueyama411c63602015-05-28 19:09:30 +0000114std::error_code ObjectFile::initializeChunks() {
115 uint32_t NumSections = COFFObj->getNumberOfSections();
116 Chunks.reserve(NumSections);
117 SparseChunks.resize(NumSections + 1);
118 for (uint32_t I = 1; I < NumSections + 1; ++I) {
119 const coff_section *Sec;
120 StringRef Name;
Rui Ueyama8fd9fb92015-06-01 02:58:15 +0000121 if (auto EC = COFFObj->getSection(I, Sec)) {
122 llvm::errs() << "getSection failed: " << Name << ": "
123 << EC.message() << "\n";
124 return make_error_code(LLDError::BrokenFile);
125 }
126 if (auto EC = COFFObj->getSectionName(Sec, Name)) {
127 llvm::errs() << "getSectionName failed: " << Name << ": "
128 << EC.message() << "\n";
129 return make_error_code(LLDError::BrokenFile);
130 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000131 if (Name == ".drectve") {
132 ArrayRef<uint8_t> Data;
133 COFFObj->getSectionContents(Sec, Data);
Rui Ueyama0569ecf2015-07-04 03:27:46 +0000134 Directives = std::string((const char *)Data.data(), Data.size());
Rui Ueyama411c63602015-05-28 19:09:30 +0000135 continue;
136 }
David Majnemer2c345a32015-07-08 16:37:50 +0000137 // We want to preserve DWARF debug sections only when /debug is on.
138 if (!Config->Debug && Name.startswith(".debug"))
Rui Ueyama411c63602015-05-28 19:09:30 +0000139 continue;
140 if (Sec->Characteristics & llvm::COFF::IMAGE_SCN_LNK_REMOVE)
141 continue;
Peter Collingbournebd3a29d2015-06-24 00:12:36 +0000142 auto *C = new (Alloc) SectionChunk(this, Sec);
Rui Ueyama411c63602015-05-28 19:09:30 +0000143 Chunks.push_back(C);
144 SparseChunks[I] = C;
145 }
146 return std::error_code();
147}
148
149std::error_code ObjectFile::initializeSymbols() {
150 uint32_t NumSymbols = COFFObj->getNumberOfSymbols();
151 SymbolBodies.reserve(NumSymbols);
152 SparseSymbolBodies.resize(NumSymbols);
153 int32_t LastSectionNumber = 0;
154 for (uint32_t I = 0; I < NumSymbols; ++I) {
155 // Get a COFFSymbolRef object.
156 auto SymOrErr = COFFObj->getSymbol(I);
Rui Ueyama8fd9fb92015-06-01 02:58:15 +0000157 if (auto EC = SymOrErr.getError()) {
158 llvm::errs() << "broken object file: " << getName() << ": "
159 << EC.message() << "\n";
160 return make_error_code(LLDError::BrokenFile);
161 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000162 COFFSymbolRef Sym = SymOrErr.get();
163
Rui Ueyama411c63602015-05-28 19:09:30 +0000164 const void *AuxP = nullptr;
165 if (Sym.getNumberOfAuxSymbols())
166 AuxP = COFFObj->getSymbol(I + 1)->getRawPtr();
167 bool IsFirst = (LastSectionNumber != Sym.getSectionNumber());
168
Rui Ueyamadae16612015-06-29 22:16:21 +0000169 SymbolBody *Body = nullptr;
170 if (Sym.isUndefined()) {
171 Body = createUndefined(Sym);
172 } else if (Sym.isWeakExternal()) {
173 Body = createWeakExternal(Sym, AuxP);
174 } else {
175 Body = createDefined(Sym, AuxP, IsFirst);
176 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000177 if (Body) {
178 SymbolBodies.push_back(Body);
179 SparseSymbolBodies[I] = Body;
180 }
181 I += Sym.getNumberOfAuxSymbols();
182 LastSectionNumber = Sym.getSectionNumber();
183 }
184 return std::error_code();
185}
186
Rui Ueyamadae16612015-06-29 22:16:21 +0000187Undefined *ObjectFile::createUndefined(COFFSymbolRef Sym) {
Rui Ueyama57fe78d2015-06-08 19:43:59 +0000188 StringRef Name;
Rui Ueyamadae16612015-06-29 22:16:21 +0000189 COFFObj->getSymbolName(Sym, Name);
190 return new (Alloc) Undefined(Name);
191}
192
193Undefined *ObjectFile::createWeakExternal(COFFSymbolRef Sym, const void *AuxP) {
194 StringRef Name;
195 COFFObj->getSymbolName(Sym, Name);
Rui Ueyama48975962015-07-01 22:32:23 +0000196 auto *U = new (Alloc) Undefined(Name);
Rui Ueyamadae16612015-06-29 22:16:21 +0000197 auto *Aux = (const coff_aux_weak_external *)AuxP;
Peter Collingbourneda2f0942015-07-03 22:03:36 +0000198 U->WeakAlias = SparseSymbolBodies[Aux->TagIndex];
Rui Ueyama48975962015-07-01 22:32:23 +0000199 return U;
Rui Ueyamadae16612015-06-29 22:16:21 +0000200}
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
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000241MachineTypes ObjectFile::getMachineType() {
242 if (COFFObj)
243 return static_cast<MachineTypes>(COFFObj->getMachine());
244 return IMAGE_FILE_MACHINE_UNKNOWN;
245}
246
Rui Ueyamaa841bb02015-07-09 20:22:41 +0000247StringRef ltrim1(StringRef S, const char *Chars) {
248 if (!S.empty() && strchr(Chars, S[0]))
249 return S.substr(1);
250 return S;
251}
252
Rui Ueyama411c63602015-05-28 19:09:30 +0000253std::error_code ImportFile::parse() {
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000254 const char *Buf = MB.getBufferStart();
255 const char *End = MB.getBufferEnd();
Rui Ueyama411c63602015-05-28 19:09:30 +0000256 const auto *Hdr = reinterpret_cast<const coff_import_header *>(Buf);
257
258 // Check if the total size is valid.
Denis Protivensky68336902015-06-01 09:26:32 +0000259 if ((size_t)(End - Buf) != (sizeof(*Hdr) + Hdr->SizeOfData)) {
Rui Ueyama8fd9fb92015-06-01 02:58:15 +0000260 llvm::errs() << "broken import library\n";
261 return make_error_code(LLDError::BrokenFile);
262 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000263
264 // Read names and create an __imp_ symbol.
265 StringRef Name = StringAlloc.save(StringRef(Buf + sizeof(*Hdr)));
266 StringRef ImpName = StringAlloc.save(Twine("__imp_") + Name);
267 StringRef DLLName(Buf + sizeof(coff_import_header) + Name.size() + 1);
Rui Ueyama1c79ce92015-07-08 20:22:50 +0000268 StringRef ExtName;
269 switch (Hdr->getNameType()) {
270 case IMPORT_ORDINAL:
271 ExtName = "";
272 break;
273 case IMPORT_NAME:
274 ExtName = Name;
275 break;
276 case IMPORT_NAME_NOPREFIX:
Rui Ueyamaa841bb02015-07-09 20:22:41 +0000277 ExtName = ltrim1(Name, "?@_");
Rui Ueyama1c79ce92015-07-08 20:22:50 +0000278 break;
279 case IMPORT_NAME_UNDECORATE:
Rui Ueyamaa841bb02015-07-09 20:22:41 +0000280 ExtName = ltrim1(Name, "?@_");
Rui Ueyama1c79ce92015-07-08 20:22:50 +0000281 ExtName = ExtName.substr(0, ExtName.find('@'));
282 break;
283 }
284 auto *ImpSym = new (Alloc) DefinedImportData(DLLName, ImpName, ExtName, Hdr);
Rui Ueyama411c63602015-05-28 19:09:30 +0000285 SymbolBodies.push_back(ImpSym);
286
287 // If type is function, we need to create a thunk which jump to an
288 // address pointed by the __imp_ symbol. (This allows you to call
289 // DLL functions just like regular non-DLL functions.)
290 if (Hdr->getType() == llvm::COFF::IMPORT_CODE)
291 SymbolBodies.push_back(new (Alloc) DefinedImportThunk(Name, ImpSym));
292 return std::error_code();
293}
294
Peter Collingbourne60c16162015-06-01 20:10:10 +0000295std::error_code BitcodeFile::parse() {
296 std::string Err;
Rui Ueyama81b030c2015-06-01 21:19:43 +0000297 M.reset(LTOModule::createFromBuffer(MB.getBufferStart(),
298 MB.getBufferSize(),
299 llvm::TargetOptions(), Err));
Peter Collingbourne60c16162015-06-01 20:10:10 +0000300 if (!Err.empty()) {
301 llvm::errs() << Err << '\n';
302 return make_error_code(LLDError::BrokenFile);
303 }
304
Rui Ueyama223fe1b2015-06-18 20:29:41 +0000305 llvm::BumpPtrStringSaver Saver(Alloc);
Peter Collingbourne60c16162015-06-01 20:10:10 +0000306 for (unsigned I = 0, E = M->getSymbolCount(); I != E; ++I) {
Peter Collingbournedf637ea2015-06-08 20:21:28 +0000307 lto_symbol_attributes Attrs = M->getSymbolAttributes(I);
308 if ((Attrs & LTO_SYMBOL_SCOPE_MASK) == LTO_SYMBOL_SCOPE_INTERNAL)
309 continue;
310
Rui Ueyama223fe1b2015-06-18 20:29:41 +0000311 StringRef SymName = Saver.save(M->getSymbolName(I));
Peter Collingbournedf637ea2015-06-08 20:21:28 +0000312 int SymbolDef = Attrs & LTO_SYMBOL_DEFINITION_MASK;
313 if (SymbolDef == LTO_SYMBOL_DEFINITION_UNDEFINED) {
Peter Collingbourne60c16162015-06-01 20:10:10 +0000314 SymbolBodies.push_back(new (Alloc) Undefined(SymName));
315 } else {
Peter Collingbourne2612a322015-07-04 05:28:41 +0000316 bool Replaceable =
317 (SymbolDef == LTO_SYMBOL_DEFINITION_TENTATIVE || // common
318 (Attrs & LTO_SYMBOL_COMDAT) || // comdat
319 (SymbolDef == LTO_SYMBOL_DEFINITION_WEAK && // weak external
320 (Attrs & LTO_SYMBOL_ALIAS)));
Peter Collingbournef7b27d12015-06-30 00:47:52 +0000321 SymbolBodies.push_back(new (Alloc) DefinedBitcode(this, SymName,
322 Replaceable));
Peter Collingbourne60c16162015-06-01 20:10:10 +0000323 }
324 }
Peter Collingbourneace2f092015-06-06 02:00:45 +0000325
Peter Collingbourne79cfd432015-06-29 23:26:28 +0000326 Directives = M->getLinkerOpts();
Peter Collingbourne60c16162015-06-01 20:10:10 +0000327 return std::error_code();
328}
Rui Ueyama81b030c2015-06-01 21:19:43 +0000329
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000330MachineTypes BitcodeFile::getMachineType() {
331 if (!M)
332 return IMAGE_FILE_MACHINE_UNKNOWN;
333 switch (Triple(M->getTargetTriple()).getArch()) {
334 case Triple::x86_64:
335 return IMAGE_FILE_MACHINE_AMD64;
336 case Triple::x86:
337 return IMAGE_FILE_MACHINE_I386;
338 case Triple::arm:
339 return IMAGE_FILE_MACHINE_ARMNT;
340 default:
341 return IMAGE_FILE_MACHINE_UNKNOWN;
342 }
343}
344
Rui Ueyama411c63602015-05-28 19:09:30 +0000345} // namespace coff
346} // namespace lld