blob: 62bb144ad8f3a75c62c6e4017d35d5eecf175873 [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;
25using llvm::RoundUpToAlignment;
26using llvm::sys::fs::identify_magic;
27using llvm::sys::fs::file_magic;
28
29namespace lld {
30namespace coff {
31
32// Returns the last element of a path, which is supposed to be a filename.
33static StringRef getBasename(StringRef Path) {
34 size_t Pos = Path.rfind('\\');
35 if (Pos == StringRef::npos)
36 return Path;
37 return Path.substr(Pos + 1);
38}
39
40// Returns a string in the format of "foo.obj" or "foo.obj(bar.lib)".
41std::string InputFile::getShortName() {
42 if (ParentName == "")
43 return getName().lower();
44 std::string Res = (getBasename(ParentName) + "(" +
45 getBasename(getName()) + ")").str();
46 return StringRef(Res).lower();
47}
48
49std::error_code ArchiveFile::parse() {
Rui Ueyamad7c2f582015-05-31 21:04:56 +000050 // Parse a MemoryBufferRef as an archive file.
51 auto ArchiveOrErr = Archive::create(MB);
Rui Ueyama411c63602015-05-28 19:09:30 +000052 if (auto EC = ArchiveOrErr.getError())
53 return EC;
54 File = std::move(ArchiveOrErr.get());
55
56 // Allocate a buffer for Lazy objects.
57 size_t BufSize = File->getNumberOfSymbols() * sizeof(Lazy);
58 Lazy *Buf = (Lazy *)Alloc.Allocate(BufSize, llvm::alignOf<Lazy>());
59
60 // Read the symbol table to construct Lazy objects.
61 uint32_t I = 0;
62 for (const Archive::Symbol &Sym : File->symbols()) {
63 // Skip special symbol exists in import library files.
64 if (Sym.getName() == "__NULL_IMPORT_DESCRIPTOR")
65 continue;
66 SymbolBodies.push_back(new (&Buf[I++]) Lazy(this, Sym));
67 }
68 return std::error_code();
69}
70
71// Returns a buffer pointing to a member file containing a given symbol.
72ErrorOr<MemoryBufferRef> ArchiveFile::getMember(const Archive::Symbol *Sym) {
73 auto ItOrErr = Sym->getMember();
74 if (auto EC = ItOrErr.getError())
75 return EC;
76 Archive::child_iterator It = ItOrErr.get();
77
78 // Return an empty buffer if we have already returned the same buffer.
79 const char *StartAddr = It->getBuffer().data();
80 auto Pair = Seen.insert(StartAddr);
81 if (!Pair.second)
82 return MemoryBufferRef();
83 return It->getMemoryBufferRef();
84}
85
86std::error_code ObjectFile::parse() {
Rui Ueyama411c63602015-05-28 19:09:30 +000087 // Parse a memory buffer as a COFF file.
Rui Ueyamad7c2f582015-05-31 21:04:56 +000088 auto BinOrErr = createBinary(MB);
Rui Ueyama411c63602015-05-28 19:09:30 +000089 if (auto EC = BinOrErr.getError())
90 return EC;
91 std::unique_ptr<Binary> Bin = std::move(BinOrErr.get());
92
93 if (auto *Obj = dyn_cast<COFFObjectFile>(Bin.get())) {
94 Bin.release();
95 COFFObj.reset(Obj);
96 } else {
Rui Ueyama8fd9fb92015-06-01 02:58:15 +000097 llvm::errs() << getName() << " is not a COFF file.\n";
98 return make_error_code(LLDError::InvalidFile);
Rui Ueyama411c63602015-05-28 19:09:30 +000099 }
100
101 // Read section and symbol tables.
102 if (auto EC = initializeChunks())
103 return EC;
104 return initializeSymbols();
105}
106
107SymbolBody *ObjectFile::getSymbolBody(uint32_t SymbolIndex) {
108 return SparseSymbolBodies[SymbolIndex]->getReplacement();
109}
110
111std::error_code ObjectFile::initializeChunks() {
112 uint32_t NumSections = COFFObj->getNumberOfSections();
113 Chunks.reserve(NumSections);
114 SparseChunks.resize(NumSections + 1);
115 for (uint32_t I = 1; I < NumSections + 1; ++I) {
116 const coff_section *Sec;
117 StringRef Name;
Rui Ueyama8fd9fb92015-06-01 02:58:15 +0000118 if (auto EC = COFFObj->getSection(I, Sec)) {
119 llvm::errs() << "getSection failed: " << Name << ": "
120 << EC.message() << "\n";
121 return make_error_code(LLDError::BrokenFile);
122 }
123 if (auto EC = COFFObj->getSectionName(Sec, Name)) {
124 llvm::errs() << "getSectionName failed: " << Name << ": "
125 << EC.message() << "\n";
126 return make_error_code(LLDError::BrokenFile);
127 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000128 if (Name == ".drectve") {
129 ArrayRef<uint8_t> Data;
130 COFFObj->getSectionContents(Sec, Data);
Denis Protivensky68336902015-06-01 09:26:32 +0000131 Directives = StringRef((const char *)Data.data(), Data.size()).trim();
Rui Ueyama411c63602015-05-28 19:09:30 +0000132 continue;
133 }
134 if (Name.startswith(".debug"))
135 continue;
136 if (Sec->Characteristics & llvm::COFF::IMAGE_SCN_LNK_REMOVE)
137 continue;
138 auto *C = new (Alloc) SectionChunk(this, Sec, I);
139 Chunks.push_back(C);
140 SparseChunks[I] = C;
141 }
142 return std::error_code();
143}
144
145std::error_code ObjectFile::initializeSymbols() {
146 uint32_t NumSymbols = COFFObj->getNumberOfSymbols();
147 SymbolBodies.reserve(NumSymbols);
148 SparseSymbolBodies.resize(NumSymbols);
149 int32_t LastSectionNumber = 0;
150 for (uint32_t I = 0; I < NumSymbols; ++I) {
151 // Get a COFFSymbolRef object.
152 auto SymOrErr = COFFObj->getSymbol(I);
Rui Ueyama8fd9fb92015-06-01 02:58:15 +0000153 if (auto EC = SymOrErr.getError()) {
154 llvm::errs() << "broken object file: " << getName() << ": "
155 << EC.message() << "\n";
156 return make_error_code(LLDError::BrokenFile);
157 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000158 COFFSymbolRef Sym = SymOrErr.get();
159
160 // Get a symbol name.
161 StringRef SymbolName;
Rui Ueyama8fd9fb92015-06-01 02:58:15 +0000162 if (auto EC = COFFObj->getSymbolName(Sym, SymbolName)) {
163 llvm::errs() << "broken object file: " << getName() << ": "
164 << EC.message() << "\n";
165 return make_error_code(LLDError::BrokenFile);
166 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000167 // Skip special symbols.
168 if (SymbolName == "@comp.id" || SymbolName == "@feat.00")
169 continue;
170
171 const void *AuxP = nullptr;
172 if (Sym.getNumberOfAuxSymbols())
173 AuxP = COFFObj->getSymbol(I + 1)->getRawPtr();
174 bool IsFirst = (LastSectionNumber != Sym.getSectionNumber());
175
176 SymbolBody *Body = createSymbolBody(SymbolName, Sym, AuxP, IsFirst);
177 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
187SymbolBody *ObjectFile::createSymbolBody(StringRef Name, COFFSymbolRef Sym,
188 const void *AuxP, bool IsFirst) {
189 if (Sym.isUndefined())
190 return new Undefined(Name);
191 if (Sym.isCommon()) {
192 Chunk *C = new (Alloc) CommonChunk(Sym);
193 Chunks.push_back(C);
194 return new (Alloc) DefinedRegular(Name, Sym, C);
195 }
196 if (Sym.isAbsolute())
197 return new (Alloc) DefinedAbsolute(Name, Sym.getValue());
198 // TODO: Handle IMAGE_WEAK_EXTERN_SEARCH_ALIAS
199 if (Sym.isWeakExternal()) {
200 auto *Aux = (const coff_aux_weak_external *)AuxP;
201 return new (Alloc) Undefined(Name, &SparseSymbolBodies[Aux->TagIndex]);
202 }
203 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 Ueyama411c63602015-05-28 19:09:30 +0000206 auto *Parent =
207 (SectionChunk *)(SparseChunks[Aux->getNumber(Sym.isBigObj())]);
208 if (Parent)
209 Parent->addAssociative((SectionChunk *)C);
210 }
211 }
212 if (Chunk *C = SparseChunks[Sym.getSectionNumber()])
213 return new (Alloc) DefinedRegular(Name, Sym, C);
214 return nullptr;
215}
216
217std::error_code ImportFile::parse() {
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000218 const char *Buf = MB.getBufferStart();
219 const char *End = MB.getBufferEnd();
Rui Ueyama411c63602015-05-28 19:09:30 +0000220 const auto *Hdr = reinterpret_cast<const coff_import_header *>(Buf);
221
222 // Check if the total size is valid.
Denis Protivensky68336902015-06-01 09:26:32 +0000223 if ((size_t)(End - Buf) != (sizeof(*Hdr) + Hdr->SizeOfData)) {
Rui Ueyama8fd9fb92015-06-01 02:58:15 +0000224 llvm::errs() << "broken import library\n";
225 return make_error_code(LLDError::BrokenFile);
226 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000227
228 // Read names and create an __imp_ symbol.
229 StringRef Name = StringAlloc.save(StringRef(Buf + sizeof(*Hdr)));
230 StringRef ImpName = StringAlloc.save(Twine("__imp_") + Name);
231 StringRef DLLName(Buf + sizeof(coff_import_header) + Name.size() + 1);
Rui Ueyamafd99e012015-06-01 21:05:27 +0000232 StringRef ExternalName = Name;
233 if (Hdr->getNameType() == llvm::COFF::IMPORT_ORDINAL)
234 ExternalName = "";
235 auto *ImpSym = new (Alloc) DefinedImportData(DLLName, ImpName, ExternalName,
236 Hdr);
Rui Ueyama411c63602015-05-28 19:09:30 +0000237 SymbolBodies.push_back(ImpSym);
238
239 // If type is function, we need to create a thunk which jump to an
240 // address pointed by the __imp_ symbol. (This allows you to call
241 // DLL functions just like regular non-DLL functions.)
242 if (Hdr->getType() == llvm::COFF::IMPORT_CODE)
243 SymbolBodies.push_back(new (Alloc) DefinedImportThunk(Name, ImpSym));
244 return std::error_code();
245}
246
Peter Collingbourne60c16162015-06-01 20:10:10 +0000247std::error_code BitcodeFile::parse() {
248 std::string Err;
Rui Ueyama81b030c2015-06-01 21:19:43 +0000249 M.reset(LTOModule::createFromBuffer(MB.getBufferStart(),
250 MB.getBufferSize(),
251 llvm::TargetOptions(), Err));
Peter Collingbourne60c16162015-06-01 20:10:10 +0000252 if (!Err.empty()) {
253 llvm::errs() << Err << '\n';
254 return make_error_code(LLDError::BrokenFile);
255 }
256
257 for (unsigned I = 0, E = M->getSymbolCount(); I != E; ++I) {
258 StringRef SymName = M->getSymbolName(I);
259 if ((M->getSymbolAttributes(I) & LTO_SYMBOL_DEFINITION_MASK) ==
260 LTO_SYMBOL_DEFINITION_UNDEFINED) {
261 SymbolBodies.push_back(new (Alloc) Undefined(SymName));
262 } else {
263 SymbolBodies.push_back(new (Alloc) DefinedBitcode(SymName));
264 }
265 }
Peter Collingbourneace2f092015-06-06 02:00:45 +0000266
267 // Extract any linker directives from the bitcode file, which are represented
268 // as module flags with the key "Linker Options".
269 llvm::SmallVector<llvm::Module::ModuleFlagEntry, 8> Flags;
270 M->getModule().getModuleFlagsMetadata(Flags);
271 for (auto &&Flag : Flags) {
272 if (Flag.Key->getString() != "Linker Options")
273 continue;
274
275 for (llvm::Metadata *Op : cast<llvm::MDNode>(Flag.Val)->operands()) {
276 for (llvm::Metadata *InnerOp : cast<llvm::MDNode>(Op)->operands()) {
277 Directives += " ";
278 Directives += cast<llvm::MDString>(InnerOp)->getString();
279 }
280 }
281 }
282
Peter Collingbourne60c16162015-06-01 20:10:10 +0000283 return std::error_code();
284}
Rui Ueyama81b030c2015-06-01 21:19:43 +0000285
Rui Ueyama411c63602015-05-28 19:09:30 +0000286} // namespace coff
287} // namespace lld