blob: 88406bef7fa5c1ae8569baed6dff87272d31d401 [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"
11#include "InputFiles.h"
12#include "Writer.h"
13#include "lld/Core/Error.h"
14#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 Ueyamad7c2f582015-05-31 21:04:56 +000096 return make_dynamic_error_code(getName() + " is not a COFF file.");
Rui Ueyama411c63602015-05-28 19:09:30 +000097 }
98
99 // Read section and symbol tables.
100 if (auto EC = initializeChunks())
101 return EC;
102 return initializeSymbols();
103}
104
105SymbolBody *ObjectFile::getSymbolBody(uint32_t SymbolIndex) {
106 return SparseSymbolBodies[SymbolIndex]->getReplacement();
107}
108
109std::error_code ObjectFile::initializeChunks() {
110 uint32_t NumSections = COFFObj->getNumberOfSections();
111 Chunks.reserve(NumSections);
112 SparseChunks.resize(NumSections + 1);
113 for (uint32_t I = 1; I < NumSections + 1; ++I) {
114 const coff_section *Sec;
115 StringRef Name;
116 if (auto EC = COFFObj->getSection(I, Sec))
117 return make_dynamic_error_code(Twine("getSection failed: ") + Name +
118 ": " + EC.message());
119 if (auto EC = COFFObj->getSectionName(Sec, Name))
120 return make_dynamic_error_code(Twine("getSectionName failed: ") + Name +
121 ": " + EC.message());
122 if (Name == ".drectve") {
123 ArrayRef<uint8_t> Data;
124 COFFObj->getSectionContents(Sec, Data);
125 Directives = StringRef((char *)Data.data(), Data.size()).trim();
126 continue;
127 }
128 if (Name.startswith(".debug"))
129 continue;
130 if (Sec->Characteristics & llvm::COFF::IMAGE_SCN_LNK_REMOVE)
131 continue;
132 auto *C = new (Alloc) SectionChunk(this, Sec, I);
133 Chunks.push_back(C);
134 SparseChunks[I] = C;
135 }
136 return std::error_code();
137}
138
139std::error_code ObjectFile::initializeSymbols() {
140 uint32_t NumSymbols = COFFObj->getNumberOfSymbols();
141 SymbolBodies.reserve(NumSymbols);
142 SparseSymbolBodies.resize(NumSymbols);
143 int32_t LastSectionNumber = 0;
144 for (uint32_t I = 0; I < NumSymbols; ++I) {
145 // Get a COFFSymbolRef object.
146 auto SymOrErr = COFFObj->getSymbol(I);
147 if (auto EC = SymOrErr.getError())
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000148 return make_dynamic_error_code("broken object file: " + getName() +
Rui Ueyama411c63602015-05-28 19:09:30 +0000149 ": " + EC.message());
150 COFFSymbolRef Sym = SymOrErr.get();
151
152 // Get a symbol name.
153 StringRef SymbolName;
154 if (auto EC = COFFObj->getSymbolName(Sym, SymbolName))
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000155 return make_dynamic_error_code("broken object file: " + getName() +
Rui Ueyama411c63602015-05-28 19:09:30 +0000156 ": " + EC.message());
157 // Skip special symbols.
158 if (SymbolName == "@comp.id" || SymbolName == "@feat.00")
159 continue;
160
161 const void *AuxP = nullptr;
162 if (Sym.getNumberOfAuxSymbols())
163 AuxP = COFFObj->getSymbol(I + 1)->getRawPtr();
164 bool IsFirst = (LastSectionNumber != Sym.getSectionNumber());
165
166 SymbolBody *Body = createSymbolBody(SymbolName, Sym, AuxP, IsFirst);
167 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
177SymbolBody *ObjectFile::createSymbolBody(StringRef Name, COFFSymbolRef Sym,
178 const void *AuxP, bool IsFirst) {
179 if (Sym.isUndefined())
180 return new Undefined(Name);
181 if (Sym.isCommon()) {
182 Chunk *C = new (Alloc) CommonChunk(Sym);
183 Chunks.push_back(C);
184 return new (Alloc) DefinedRegular(Name, Sym, C);
185 }
186 if (Sym.isAbsolute())
187 return new (Alloc) DefinedAbsolute(Name, Sym.getValue());
188 // TODO: Handle IMAGE_WEAK_EXTERN_SEARCH_ALIAS
189 if (Sym.isWeakExternal()) {
190 auto *Aux = (const coff_aux_weak_external *)AuxP;
191 return new (Alloc) Undefined(Name, &SparseSymbolBodies[Aux->TagIndex]);
192 }
193 if (IsFirst && AuxP) {
194 if (Chunk *C = SparseChunks[Sym.getSectionNumber()]) {
195 auto *Aux = (coff_aux_section_definition *)AuxP;
196 auto *Parent =
197 (SectionChunk *)(SparseChunks[Aux->getNumber(Sym.isBigObj())]);
198 if (Parent)
199 Parent->addAssociative((SectionChunk *)C);
200 }
201 }
202 if (Chunk *C = SparseChunks[Sym.getSectionNumber()])
203 return new (Alloc) DefinedRegular(Name, Sym, C);
204 return nullptr;
205}
206
207std::error_code ImportFile::parse() {
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000208 const char *Buf = MB.getBufferStart();
209 const char *End = MB.getBufferEnd();
Rui Ueyama411c63602015-05-28 19:09:30 +0000210 const auto *Hdr = reinterpret_cast<const coff_import_header *>(Buf);
211
212 // Check if the total size is valid.
213 if (End - Buf != sizeof(*Hdr) + Hdr->SizeOfData)
214 return make_dynamic_error_code("broken import library");
215
216 // Read names and create an __imp_ symbol.
217 StringRef Name = StringAlloc.save(StringRef(Buf + sizeof(*Hdr)));
218 StringRef ImpName = StringAlloc.save(Twine("__imp_") + Name);
219 StringRef DLLName(Buf + sizeof(coff_import_header) + Name.size() + 1);
Rui Ueyamac9bfe322015-05-29 15:45:35 +0000220 auto *ImpSym = new (Alloc) DefinedImportData(DLLName, ImpName, Name, Hdr);
Rui Ueyama411c63602015-05-28 19:09:30 +0000221 SymbolBodies.push_back(ImpSym);
222
223 // If type is function, we need to create a thunk which jump to an
224 // address pointed by the __imp_ symbol. (This allows you to call
225 // DLL functions just like regular non-DLL functions.)
226 if (Hdr->getType() == llvm::COFF::IMPORT_CODE)
227 SymbolBodies.push_back(new (Alloc) DefinedImportThunk(Name, ImpSym));
228 return std::error_code();
229}
230
231} // namespace coff
232} // namespace lld