blob: 1d4db89653e185c2a8a067caa02ac6c94a58ef59 [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 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
33// Returns the last element of a path, which is supposed to be a filename.
34static StringRef getBasename(StringRef Path) {
Rui Ueyamaea63a282015-06-18 20:16:26 +000035 size_t Pos = Path.find_last_of("\\/");
Rui Ueyama411c63602015-05-28 19:09:30 +000036 if (Pos == StringRef::npos)
37 return Path;
38 return Path.substr(Pos + 1);
39}
40
41// Returns a string in the format of "foo.obj" or "foo.obj(bar.lib)".
42std::string InputFile::getShortName() {
43 if (ParentName == "")
44 return getName().lower();
45 std::string Res = (getBasename(ParentName) + "(" +
46 getBasename(getName()) + ")").str();
47 return StringRef(Res).lower();
48}
49
50std::error_code ArchiveFile::parse() {
Rui Ueyamad7c2f582015-05-31 21:04:56 +000051 // Parse a MemoryBufferRef as an archive file.
52 auto ArchiveOrErr = Archive::create(MB);
Rui Ueyama411c63602015-05-28 19:09:30 +000053 if (auto EC = ArchiveOrErr.getError())
54 return EC;
55 File = std::move(ArchiveOrErr.get());
56
57 // Allocate a buffer for Lazy objects.
58 size_t BufSize = File->getNumberOfSymbols() * sizeof(Lazy);
59 Lazy *Buf = (Lazy *)Alloc.Allocate(BufSize, llvm::alignOf<Lazy>());
60
61 // Read the symbol table to construct Lazy objects.
62 uint32_t I = 0;
63 for (const Archive::Symbol &Sym : File->symbols()) {
64 // Skip special symbol exists in import library files.
65 if (Sym.getName() == "__NULL_IMPORT_DESCRIPTOR")
66 continue;
67 SymbolBodies.push_back(new (&Buf[I++]) Lazy(this, Sym));
68 }
69 return std::error_code();
70}
71
72// Returns a buffer pointing to a member file containing a given symbol.
73ErrorOr<MemoryBufferRef> ArchiveFile::getMember(const Archive::Symbol *Sym) {
74 auto ItOrErr = Sym->getMember();
75 if (auto EC = ItOrErr.getError())
76 return EC;
77 Archive::child_iterator It = ItOrErr.get();
78
79 // Return an empty buffer if we have already returned the same buffer.
80 const char *StartAddr = It->getBuffer().data();
81 auto Pair = Seen.insert(StartAddr);
82 if (!Pair.second)
83 return MemoryBufferRef();
84 return It->getMemoryBufferRef();
85}
86
87std::error_code ObjectFile::parse() {
Rui Ueyama411c63602015-05-28 19:09:30 +000088 // Parse a memory buffer as a COFF file.
Rui Ueyamad7c2f582015-05-31 21:04:56 +000089 auto BinOrErr = createBinary(MB);
Rui Ueyama411c63602015-05-28 19:09:30 +000090 if (auto EC = BinOrErr.getError())
91 return EC;
92 std::unique_ptr<Binary> Bin = std::move(BinOrErr.get());
93
94 if (auto *Obj = dyn_cast<COFFObjectFile>(Bin.get())) {
95 Bin.release();
96 COFFObj.reset(Obj);
97 } else {
Rui Ueyama8fd9fb92015-06-01 02:58:15 +000098 llvm::errs() << getName() << " is not a COFF file.\n";
99 return make_error_code(LLDError::InvalidFile);
Rui Ueyama411c63602015-05-28 19:09:30 +0000100 }
101
102 // Read section and symbol tables.
103 if (auto EC = initializeChunks())
104 return EC;
105 return initializeSymbols();
106}
107
108SymbolBody *ObjectFile::getSymbolBody(uint32_t SymbolIndex) {
109 return SparseSymbolBodies[SymbolIndex]->getReplacement();
110}
111
112std::error_code ObjectFile::initializeChunks() {
113 uint32_t NumSections = COFFObj->getNumberOfSections();
114 Chunks.reserve(NumSections);
115 SparseChunks.resize(NumSections + 1);
116 for (uint32_t I = 1; I < NumSections + 1; ++I) {
117 const coff_section *Sec;
118 StringRef Name;
Rui Ueyama8fd9fb92015-06-01 02:58:15 +0000119 if (auto EC = COFFObj->getSection(I, Sec)) {
120 llvm::errs() << "getSection failed: " << Name << ": "
121 << EC.message() << "\n";
122 return make_error_code(LLDError::BrokenFile);
123 }
124 if (auto EC = COFFObj->getSectionName(Sec, Name)) {
125 llvm::errs() << "getSectionName failed: " << Name << ": "
126 << EC.message() << "\n";
127 return make_error_code(LLDError::BrokenFile);
128 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000129 if (Name == ".drectve") {
130 ArrayRef<uint8_t> Data;
131 COFFObj->getSectionContents(Sec, Data);
Denis Protivensky68336902015-06-01 09:26:32 +0000132 Directives = StringRef((const char *)Data.data(), Data.size()).trim();
Rui Ueyama411c63602015-05-28 19:09:30 +0000133 continue;
134 }
135 if (Name.startswith(".debug"))
136 continue;
137 if (Sec->Characteristics & llvm::COFF::IMAGE_SCN_LNK_REMOVE)
138 continue;
139 auto *C = new (Alloc) SectionChunk(this, Sec, I);
140 Chunks.push_back(C);
141 SparseChunks[I] = C;
142 }
143 return std::error_code();
144}
145
146std::error_code ObjectFile::initializeSymbols() {
147 uint32_t NumSymbols = COFFObj->getNumberOfSymbols();
148 SymbolBodies.reserve(NumSymbols);
149 SparseSymbolBodies.resize(NumSymbols);
150 int32_t LastSectionNumber = 0;
151 for (uint32_t I = 0; I < NumSymbols; ++I) {
152 // Get a COFFSymbolRef object.
153 auto SymOrErr = COFFObj->getSymbol(I);
Rui Ueyama8fd9fb92015-06-01 02:58:15 +0000154 if (auto EC = SymOrErr.getError()) {
155 llvm::errs() << "broken object file: " << getName() << ": "
156 << EC.message() << "\n";
157 return make_error_code(LLDError::BrokenFile);
158 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000159 COFFSymbolRef Sym = SymOrErr.get();
160
Rui Ueyama411c63602015-05-28 19:09:30 +0000161 const void *AuxP = nullptr;
162 if (Sym.getNumberOfAuxSymbols())
163 AuxP = COFFObj->getSymbol(I + 1)->getRawPtr();
164 bool IsFirst = (LastSectionNumber != Sym.getSectionNumber());
165
Rui Ueyama57fe78d2015-06-08 19:43:59 +0000166 SymbolBody *Body = createSymbolBody(Sym, AuxP, IsFirst);
Rui Ueyama411c63602015-05-28 19:09:30 +0000167 if (Body) {
168 SymbolBodies.push_back(Body);
169 SparseSymbolBodies[I] = Body;
170 }
171 I += Sym.getNumberOfAuxSymbols();
172 LastSectionNumber = Sym.getSectionNumber();
173 }
174 return std::error_code();
175}
176
Rui Ueyama57fe78d2015-06-08 19:43:59 +0000177SymbolBody *ObjectFile::createSymbolBody(COFFSymbolRef Sym, const void *AuxP,
178 bool IsFirst) {
179 StringRef Name;
180 if (Sym.isUndefined()) {
181 COFFObj->getSymbolName(Sym, Name);
Rui Ueyamab4f791b2015-06-08 00:09:25 +0000182 return new (Alloc) Undefined(Name);
Rui Ueyama57fe78d2015-06-08 19:43:59 +0000183 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000184 if (Sym.isCommon()) {
185 Chunk *C = new (Alloc) CommonChunk(Sym);
186 Chunks.push_back(C);
Rui Ueyama57fe78d2015-06-08 19:43:59 +0000187 return new (Alloc) DefinedRegular(COFFObj.get(), Sym, C);
Rui Ueyama411c63602015-05-28 19:09:30 +0000188 }
Rui Ueyama57fe78d2015-06-08 19:43:59 +0000189 if (Sym.isAbsolute()) {
190 COFFObj->getSymbolName(Sym, Name);
191 // Skip special symbols.
192 if (Name == "@comp.id" || Name == "@feat.00")
193 return nullptr;
Rui Ueyama411c63602015-05-28 19:09:30 +0000194 return new (Alloc) DefinedAbsolute(Name, Sym.getValue());
Rui Ueyama57fe78d2015-06-08 19:43:59 +0000195 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000196 // TODO: Handle IMAGE_WEAK_EXTERN_SEARCH_ALIAS
197 if (Sym.isWeakExternal()) {
Rui Ueyama57fe78d2015-06-08 19:43:59 +0000198 COFFObj->getSymbolName(Sym, Name);
Rui Ueyama411c63602015-05-28 19:09:30 +0000199 auto *Aux = (const coff_aux_weak_external *)AuxP;
200 return new (Alloc) Undefined(Name, &SparseSymbolBodies[Aux->TagIndex]);
201 }
Rui Ueyama80141a42015-06-08 05:00:42 +0000202 // Handle associative sections
Rui Ueyama411c63602015-05-28 19:09:30 +0000203 if (IsFirst && AuxP) {
204 if (Chunk *C = SparseChunks[Sym.getSectionNumber()]) {
Rui Ueyama1db1ef92015-06-01 21:49:21 +0000205 auto *Aux = reinterpret_cast<const coff_aux_section_definition *>(AuxP);
Rui Ueyama80141a42015-06-08 05:00:42 +0000206 if (Aux->Selection == IMAGE_COMDAT_SELECT_ASSOCIATIVE) {
207 auto *Parent =
Rui Ueyama411c63602015-05-28 19:09:30 +0000208 (SectionChunk *)(SparseChunks[Aux->getNumber(Sym.isBigObj())]);
Rui Ueyama80141a42015-06-08 05:00:42 +0000209 if (Parent)
210 Parent->addAssociative((SectionChunk *)C);
211 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000212 }
213 }
214 if (Chunk *C = SparseChunks[Sym.getSectionNumber()])
Rui Ueyama57fe78d2015-06-08 19:43:59 +0000215 return new (Alloc) DefinedRegular(COFFObj.get(), Sym, C);
Rui Ueyama411c63602015-05-28 19:09:30 +0000216 return nullptr;
217}
218
219std::error_code ImportFile::parse() {
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000220 const char *Buf = MB.getBufferStart();
221 const char *End = MB.getBufferEnd();
Rui Ueyama411c63602015-05-28 19:09:30 +0000222 const auto *Hdr = reinterpret_cast<const coff_import_header *>(Buf);
223
224 // Check if the total size is valid.
Denis Protivensky68336902015-06-01 09:26:32 +0000225 if ((size_t)(End - Buf) != (sizeof(*Hdr) + Hdr->SizeOfData)) {
Rui Ueyama8fd9fb92015-06-01 02:58:15 +0000226 llvm::errs() << "broken import library\n";
227 return make_error_code(LLDError::BrokenFile);
228 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000229
230 // Read names and create an __imp_ symbol.
231 StringRef Name = StringAlloc.save(StringRef(Buf + sizeof(*Hdr)));
232 StringRef ImpName = StringAlloc.save(Twine("__imp_") + Name);
233 StringRef DLLName(Buf + sizeof(coff_import_header) + Name.size() + 1);
Rui Ueyamafd99e012015-06-01 21:05:27 +0000234 StringRef ExternalName = Name;
235 if (Hdr->getNameType() == llvm::COFF::IMPORT_ORDINAL)
236 ExternalName = "";
237 auto *ImpSym = new (Alloc) DefinedImportData(DLLName, ImpName, ExternalName,
238 Hdr);
Rui Ueyama411c63602015-05-28 19:09:30 +0000239 SymbolBodies.push_back(ImpSym);
240
241 // If type is function, we need to create a thunk which jump to an
242 // address pointed by the __imp_ symbol. (This allows you to call
243 // DLL functions just like regular non-DLL functions.)
244 if (Hdr->getType() == llvm::COFF::IMPORT_CODE)
245 SymbolBodies.push_back(new (Alloc) DefinedImportThunk(Name, ImpSym));
246 return std::error_code();
247}
248
Peter Collingbourne60c16162015-06-01 20:10:10 +0000249std::error_code BitcodeFile::parse() {
250 std::string Err;
Rui Ueyama81b030c2015-06-01 21:19:43 +0000251 M.reset(LTOModule::createFromBuffer(MB.getBufferStart(),
252 MB.getBufferSize(),
253 llvm::TargetOptions(), Err));
Peter Collingbourne60c16162015-06-01 20:10:10 +0000254 if (!Err.empty()) {
255 llvm::errs() << Err << '\n';
256 return make_error_code(LLDError::BrokenFile);
257 }
258
Rui Ueyama223fe1b2015-06-18 20:29:41 +0000259 llvm::BumpPtrStringSaver Saver(Alloc);
Peter Collingbourne60c16162015-06-01 20:10:10 +0000260 for (unsigned I = 0, E = M->getSymbolCount(); I != E; ++I) {
Peter Collingbournedf637ea2015-06-08 20:21:28 +0000261 lto_symbol_attributes Attrs = M->getSymbolAttributes(I);
262 if ((Attrs & LTO_SYMBOL_SCOPE_MASK) == LTO_SYMBOL_SCOPE_INTERNAL)
263 continue;
264
Rui Ueyama223fe1b2015-06-18 20:29:41 +0000265 StringRef SymName = Saver.save(M->getSymbolName(I));
Peter Collingbournedf637ea2015-06-08 20:21:28 +0000266 int SymbolDef = Attrs & LTO_SYMBOL_DEFINITION_MASK;
267 if (SymbolDef == LTO_SYMBOL_DEFINITION_UNDEFINED) {
Peter Collingbourne60c16162015-06-01 20:10:10 +0000268 SymbolBodies.push_back(new (Alloc) Undefined(SymName));
269 } else {
Peter Collingbourne1b6fd1f2015-06-11 21:49:54 +0000270 bool Replaceable = (SymbolDef == LTO_SYMBOL_DEFINITION_TENTATIVE ||
271 (Attrs & LTO_SYMBOL_COMDAT));
272 SymbolBodies.push_back(new (Alloc) DefinedBitcode(SymName, Replaceable));
Peter Collingbourne8b2492f2015-06-18 05:22:15 +0000273
274 const llvm::GlobalValue *GV = M->getSymbolGV(I);
275 if (GV && GV->hasDLLExportStorageClass()) {
276 Directives += " /export:";
277 Directives += SymName;
278 if (!GV->getValueType()->isFunctionTy())
279 Directives += ",data";
280 }
Peter Collingbourne60c16162015-06-01 20:10:10 +0000281 }
282 }
Peter Collingbourneace2f092015-06-06 02:00:45 +0000283
284 // Extract any linker directives from the bitcode file, which are represented
285 // as module flags with the key "Linker Options".
286 llvm::SmallVector<llvm::Module::ModuleFlagEntry, 8> Flags;
287 M->getModule().getModuleFlagsMetadata(Flags);
288 for (auto &&Flag : Flags) {
289 if (Flag.Key->getString() != "Linker Options")
290 continue;
291
292 for (llvm::Metadata *Op : cast<llvm::MDNode>(Flag.Val)->operands()) {
293 for (llvm::Metadata *InnerOp : cast<llvm::MDNode>(Op)->operands()) {
294 Directives += " ";
295 Directives += cast<llvm::MDString>(InnerOp)->getString();
296 }
297 }
298 }
299
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