blob: 6737e0f5312d95ec0b46a44655e34e6de6f84282 [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"
15#include "llvm/Object/COFF.h"
16#include "llvm/Support/COFF.h"
17#include "llvm/Support/Debug.h"
18#include "llvm/Support/Endian.h"
19#include "llvm/Support/raw_ostream.h"
20
21using namespace llvm::object;
22using namespace llvm::support::endian;
23using llvm::COFF::ImportHeader;
24using llvm::RoundUpToAlignment;
25using llvm::sys::fs::identify_magic;
26using llvm::sys::fs::file_magic;
27
28namespace lld {
29namespace coff {
30
31// Returns the last element of a path, which is supposed to be a filename.
32static StringRef getBasename(StringRef Path) {
33 size_t Pos = Path.rfind('\\');
34 if (Pos == StringRef::npos)
35 return Path;
36 return Path.substr(Pos + 1);
37}
38
39// Returns a string in the format of "foo.obj" or "foo.obj(bar.lib)".
40std::string InputFile::getShortName() {
41 if (ParentName == "")
42 return getName().lower();
43 std::string Res = (getBasename(ParentName) + "(" +
44 getBasename(getName()) + ")").str();
45 return StringRef(Res).lower();
46}
47
48std::error_code ArchiveFile::parse() {
Rui Ueyamad7c2f582015-05-31 21:04:56 +000049 // Parse a MemoryBufferRef as an archive file.
50 auto ArchiveOrErr = Archive::create(MB);
Rui Ueyama411c63602015-05-28 19:09:30 +000051 if (auto EC = ArchiveOrErr.getError())
52 return EC;
53 File = std::move(ArchiveOrErr.get());
54
55 // Allocate a buffer for Lazy objects.
56 size_t BufSize = File->getNumberOfSymbols() * sizeof(Lazy);
57 Lazy *Buf = (Lazy *)Alloc.Allocate(BufSize, llvm::alignOf<Lazy>());
58
59 // Read the symbol table to construct Lazy objects.
60 uint32_t I = 0;
61 for (const Archive::Symbol &Sym : File->symbols()) {
62 // Skip special symbol exists in import library files.
63 if (Sym.getName() == "__NULL_IMPORT_DESCRIPTOR")
64 continue;
65 SymbolBodies.push_back(new (&Buf[I++]) Lazy(this, Sym));
66 }
67 return std::error_code();
68}
69
70// Returns a buffer pointing to a member file containing a given symbol.
71ErrorOr<MemoryBufferRef> ArchiveFile::getMember(const Archive::Symbol *Sym) {
72 auto ItOrErr = Sym->getMember();
73 if (auto EC = ItOrErr.getError())
74 return EC;
75 Archive::child_iterator It = ItOrErr.get();
76
77 // Return an empty buffer if we have already returned the same buffer.
78 const char *StartAddr = It->getBuffer().data();
79 auto Pair = Seen.insert(StartAddr);
80 if (!Pair.second)
81 return MemoryBufferRef();
82 return It->getMemoryBufferRef();
83}
84
85std::error_code ObjectFile::parse() {
Rui Ueyama411c63602015-05-28 19:09:30 +000086 // Parse a memory buffer as a COFF file.
Rui Ueyamad7c2f582015-05-31 21:04:56 +000087 auto BinOrErr = createBinary(MB);
Rui Ueyama411c63602015-05-28 19:09:30 +000088 if (auto EC = BinOrErr.getError())
89 return EC;
90 std::unique_ptr<Binary> Bin = std::move(BinOrErr.get());
91
92 if (auto *Obj = dyn_cast<COFFObjectFile>(Bin.get())) {
93 Bin.release();
94 COFFObj.reset(Obj);
95 } else {
Rui Ueyama8fd9fb92015-06-01 02:58:15 +000096 llvm::errs() << getName() << " is not a COFF file.\n";
97 return make_error_code(LLDError::InvalidFile);
Rui Ueyama411c63602015-05-28 19:09:30 +000098 }
99
100 // Read section and symbol tables.
101 if (auto EC = initializeChunks())
102 return EC;
103 return initializeSymbols();
104}
105
106SymbolBody *ObjectFile::getSymbolBody(uint32_t SymbolIndex) {
107 return SparseSymbolBodies[SymbolIndex]->getReplacement();
108}
109
110std::error_code ObjectFile::initializeChunks() {
111 uint32_t NumSections = COFFObj->getNumberOfSections();
112 Chunks.reserve(NumSections);
113 SparseChunks.resize(NumSections + 1);
114 for (uint32_t I = 1; I < NumSections + 1; ++I) {
115 const coff_section *Sec;
116 StringRef Name;
Rui Ueyama8fd9fb92015-06-01 02:58:15 +0000117 if (auto EC = COFFObj->getSection(I, Sec)) {
118 llvm::errs() << "getSection failed: " << Name << ": "
119 << EC.message() << "\n";
120 return make_error_code(LLDError::BrokenFile);
121 }
122 if (auto EC = COFFObj->getSectionName(Sec, Name)) {
123 llvm::errs() << "getSectionName failed: " << Name << ": "
124 << EC.message() << "\n";
125 return make_error_code(LLDError::BrokenFile);
126 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000127 if (Name == ".drectve") {
128 ArrayRef<uint8_t> Data;
129 COFFObj->getSectionContents(Sec, Data);
130 Directives = StringRef((char *)Data.data(), Data.size()).trim();
131 continue;
132 }
133 if (Name.startswith(".debug"))
134 continue;
135 if (Sec->Characteristics & llvm::COFF::IMAGE_SCN_LNK_REMOVE)
136 continue;
137 auto *C = new (Alloc) SectionChunk(this, Sec, I);
138 Chunks.push_back(C);
139 SparseChunks[I] = C;
140 }
141 return std::error_code();
142}
143
144std::error_code ObjectFile::initializeSymbols() {
145 uint32_t NumSymbols = COFFObj->getNumberOfSymbols();
146 SymbolBodies.reserve(NumSymbols);
147 SparseSymbolBodies.resize(NumSymbols);
148 int32_t LastSectionNumber = 0;
149 for (uint32_t I = 0; I < NumSymbols; ++I) {
150 // Get a COFFSymbolRef object.
151 auto SymOrErr = COFFObj->getSymbol(I);
Rui Ueyama8fd9fb92015-06-01 02:58:15 +0000152 if (auto EC = SymOrErr.getError()) {
153 llvm::errs() << "broken object file: " << getName() << ": "
154 << EC.message() << "\n";
155 return make_error_code(LLDError::BrokenFile);
156 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000157 COFFSymbolRef Sym = SymOrErr.get();
158
159 // Get a symbol name.
160 StringRef SymbolName;
Rui Ueyama8fd9fb92015-06-01 02:58:15 +0000161 if (auto EC = COFFObj->getSymbolName(Sym, SymbolName)) {
162 llvm::errs() << "broken object file: " << getName() << ": "
163 << EC.message() << "\n";
164 return make_error_code(LLDError::BrokenFile);
165 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000166 // Skip special symbols.
167 if (SymbolName == "@comp.id" || SymbolName == "@feat.00")
168 continue;
169
170 const void *AuxP = nullptr;
171 if (Sym.getNumberOfAuxSymbols())
172 AuxP = COFFObj->getSymbol(I + 1)->getRawPtr();
173 bool IsFirst = (LastSectionNumber != Sym.getSectionNumber());
174
175 SymbolBody *Body = createSymbolBody(SymbolName, Sym, AuxP, IsFirst);
176 if (Body) {
177 SymbolBodies.push_back(Body);
178 SparseSymbolBodies[I] = Body;
179 }
180 I += Sym.getNumberOfAuxSymbols();
181 LastSectionNumber = Sym.getSectionNumber();
182 }
183 return std::error_code();
184}
185
186SymbolBody *ObjectFile::createSymbolBody(StringRef Name, COFFSymbolRef Sym,
187 const void *AuxP, bool IsFirst) {
188 if (Sym.isUndefined())
189 return new Undefined(Name);
190 if (Sym.isCommon()) {
191 Chunk *C = new (Alloc) CommonChunk(Sym);
192 Chunks.push_back(C);
193 return new (Alloc) DefinedRegular(Name, Sym, C);
194 }
195 if (Sym.isAbsolute())
196 return new (Alloc) DefinedAbsolute(Name, Sym.getValue());
197 // TODO: Handle IMAGE_WEAK_EXTERN_SEARCH_ALIAS
198 if (Sym.isWeakExternal()) {
199 auto *Aux = (const coff_aux_weak_external *)AuxP;
200 return new (Alloc) Undefined(Name, &SparseSymbolBodies[Aux->TagIndex]);
201 }
202 if (IsFirst && AuxP) {
203 if (Chunk *C = SparseChunks[Sym.getSectionNumber()]) {
204 auto *Aux = (coff_aux_section_definition *)AuxP;
205 auto *Parent =
206 (SectionChunk *)(SparseChunks[Aux->getNumber(Sym.isBigObj())]);
207 if (Parent)
208 Parent->addAssociative((SectionChunk *)C);
209 }
210 }
211 if (Chunk *C = SparseChunks[Sym.getSectionNumber()])
212 return new (Alloc) DefinedRegular(Name, Sym, C);
213 return nullptr;
214}
215
216std::error_code ImportFile::parse() {
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000217 const char *Buf = MB.getBufferStart();
218 const char *End = MB.getBufferEnd();
Rui Ueyama411c63602015-05-28 19:09:30 +0000219 const auto *Hdr = reinterpret_cast<const coff_import_header *>(Buf);
220
221 // Check if the total size is valid.
Rui Ueyama8fd9fb92015-06-01 02:58:15 +0000222 if (End - Buf != sizeof(*Hdr) + Hdr->SizeOfData) {
223 llvm::errs() << "broken import library\n";
224 return make_error_code(LLDError::BrokenFile);
225 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000226
227 // Read names and create an __imp_ symbol.
228 StringRef Name = StringAlloc.save(StringRef(Buf + sizeof(*Hdr)));
229 StringRef ImpName = StringAlloc.save(Twine("__imp_") + Name);
230 StringRef DLLName(Buf + sizeof(coff_import_header) + Name.size() + 1);
Rui Ueyamac9bfe322015-05-29 15:45:35 +0000231 auto *ImpSym = new (Alloc) DefinedImportData(DLLName, ImpName, Name, Hdr);
Rui Ueyama411c63602015-05-28 19:09:30 +0000232 SymbolBodies.push_back(ImpSym);
233
234 // If type is function, we need to create a thunk which jump to an
235 // address pointed by the __imp_ symbol. (This allows you to call
236 // DLL functions just like regular non-DLL functions.)
237 if (Hdr->getType() == llvm::COFF::IMPORT_CODE)
238 SymbolBodies.push_back(new (Alloc) DefinedImportThunk(Name, ImpSym));
239 return std::error_code();
240}
241
242} // namespace coff
243} // namespace lld