1 //===- 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 "Error.h"
12 #include "InputFiles.h"
13 #include "Symbols.h"
14 #include "llvm/ADT/STLExtras.h"
15 #include "llvm/LTO/LTOModule.h"
16 #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 
22 using namespace llvm::COFF;
23 using namespace llvm::object;
24 using namespace llvm::support::endian;
25 using llvm::RoundUpToAlignment;
26 using llvm::Triple;
27 using llvm::support::ulittle32_t;
28 using llvm::sys::fs::file_magic;
29 using llvm::sys::fs::identify_magic;
30 
31 namespace lld {
32 namespace coff {
33 
34 int InputFile::NextIndex = 0;
35 
36 // Returns the last element of a path, which is supposed to be a filename.
37 static StringRef getBasename(StringRef Path) {
38   size_t Pos = Path.find_last_of("\\/");
39   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)".
45 std::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 
53 void ArchiveFile::parse() {
54   // Parse a MemoryBufferRef as an archive file.
55   auto ArchiveOrErr = Archive::create(MB);
56   error(ArchiveOrErr, "Failed to parse static library");
57   File = std::move(*ArchiveOrErr);
58 
59   // Allocate a buffer for Lazy objects.
60   size_t NumSyms = File->getNumberOfSymbols();
61   LazySymbols.reserve(NumSyms);
62 
63   // Read the symbol table to construct Lazy objects.
64   for (const Archive::Symbol &Sym : File->symbols())
65     LazySymbols.emplace_back(this, Sym);
66 
67   // Seen is a map from member files to boolean values. Initially
68   // all members are mapped to false, which indicates all these files
69   // are not read yet.
70   for (const Archive::Child &Child : File->children())
71     Seen[Child.getChildOffset()].clear();
72 }
73 
74 // Returns a buffer pointing to a member file containing a given symbol.
75 // This function is thread-safe.
76 MemoryBufferRef ArchiveFile::getMember(const Archive::Symbol *Sym) {
77   auto ItOrErr = Sym->getMember();
78   error(ItOrErr,
79         Twine("Could not get the member for symbol ") + Sym->getName());
80   Archive::child_iterator It = *ItOrErr;
81 
82   // Return an empty buffer if we have already returned the same buffer.
83   if (Seen[It->getChildOffset()].test_and_set())
84     return MemoryBufferRef();
85   ErrorOr<MemoryBufferRef> Ret = It->getMemoryBufferRef();
86   error(Ret, Twine("Could not get the buffer for the member defining symbol ") +
87                  Sym->getName());
88   return *Ret;
89 }
90 
91 void ObjectFile::parse() {
92   // Parse a memory buffer as a COFF file.
93   auto BinOrErr = createBinary(MB);
94   error(BinOrErr, "Failed to parse object file");
95   std::unique_ptr<Binary> Bin = std::move(*BinOrErr);
96 
97   if (auto *Obj = dyn_cast<COFFObjectFile>(Bin.get())) {
98     Bin.release();
99     COFFObj.reset(Obj);
100   } else {
101     error(Twine(getName()) + " is not a COFF file.");
102   }
103 
104   // Read section and symbol tables.
105   initializeChunks();
106   initializeSymbols();
107   initializeSEH();
108 }
109 
110 void 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;
117     std::error_code EC = COFFObj->getSection(I, Sec);
118     error(EC, Twine("getSection failed: #") + Twine(I));
119     EC = COFFObj->getSectionName(Sec, Name);
120     error(EC, Twine("getSectionName failed: #") + Twine(I));
121     if (Name == ".sxdata") {
122       SXData = Sec;
123       continue;
124     }
125     if (Name == ".drectve") {
126       ArrayRef<uint8_t> Data;
127       COFFObj->getSectionContents(Sec, Data);
128       Directives = std::string((const char *)Data.data(), Data.size());
129       continue;
130     }
131     // Skip non-DWARF debug info. MSVC linker converts the sections into
132     // a PDB file, but we don't support that.
133     if (Name == ".debug" || Name.startswith(".debug$"))
134       continue;
135     // We want to preserve DWARF debug sections only when /debug is on.
136     if (!Config->Debug && Name.startswith(".debug"))
137       continue;
138     if (Sec->Characteristics & llvm::COFF::IMAGE_SCN_LNK_REMOVE)
139       continue;
140     auto *C = new (Alloc) SectionChunk(this, Sec);
141     Chunks.push_back(C);
142     SparseChunks[I] = C;
143   }
144 }
145 
146 void ObjectFile::initializeSymbols() {
147   uint32_t NumSymbols = COFFObj->getNumberOfSymbols();
148   SymbolBodies.reserve(NumSymbols);
149   SparseSymbolBodies.resize(NumSymbols);
150   llvm::SmallVector<Undefined *, 8> WeakAliases;
151   int32_t LastSectionNumber = 0;
152   for (uint32_t I = 0; I < NumSymbols; ++I) {
153     // Get a COFFSymbolRef object.
154     auto SymOrErr = COFFObj->getSymbol(I);
155     error(SymOrErr, Twine("broken object file: ") + getName());
156 
157     COFFSymbolRef Sym = *SymOrErr;
158 
159     const void *AuxP = nullptr;
160     if (Sym.getNumberOfAuxSymbols())
161       AuxP = COFFObj->getSymbol(I + 1)->getRawPtr();
162     bool IsFirst = (LastSectionNumber != Sym.getSectionNumber());
163 
164     SymbolBody *Body = nullptr;
165     if (Sym.isUndefined()) {
166       Body = createUndefined(Sym);
167     } else if (Sym.isWeakExternal()) {
168       Body = createWeakExternal(Sym, AuxP);
169       WeakAliases.push_back((Undefined *)Body);
170     } else {
171       Body = createDefined(Sym, AuxP, IsFirst);
172     }
173     if (Body) {
174       SymbolBodies.push_back(Body);
175       SparseSymbolBodies[I] = Body;
176     }
177     I += Sym.getNumberOfAuxSymbols();
178     LastSectionNumber = Sym.getSectionNumber();
179   }
180   for (Undefined *U : WeakAliases)
181     U->WeakAlias = SparseSymbolBodies[(uintptr_t)U->WeakAlias];
182 }
183 
184 Undefined *ObjectFile::createUndefined(COFFSymbolRef Sym) {
185   StringRef Name;
186   COFFObj->getSymbolName(Sym, Name);
187   return new (Alloc) Undefined(Name);
188 }
189 
190 Undefined *ObjectFile::createWeakExternal(COFFSymbolRef Sym, const void *AuxP) {
191   StringRef Name;
192   COFFObj->getSymbolName(Sym, Name);
193   auto *U = new (Alloc) Undefined(Name);
194   auto *Aux = (const coff_aux_weak_external *)AuxP;
195   U->WeakAlias = (Undefined *)(uintptr_t)Aux->TagIndex;
196   return U;
197 }
198 
199 Defined *ObjectFile::createDefined(COFFSymbolRef Sym, const void *AuxP,
200                                    bool IsFirst) {
201   StringRef Name;
202   if (Sym.isCommon()) {
203     auto *C = new (Alloc) CommonChunk(Sym);
204     Chunks.push_back(C);
205     return new (Alloc) DefinedCommon(this, Sym, C);
206   }
207   if (Sym.isAbsolute()) {
208     COFFObj->getSymbolName(Sym, Name);
209     // Skip special symbols.
210     if (Name == "@comp.id")
211       return nullptr;
212     // COFF spec 5.10.1. The .sxdata section.
213     if (Name == "@feat.00") {
214       if (Sym.getValue() & 1)
215         SEHCompat = true;
216       return nullptr;
217     }
218     return new (Alloc) DefinedAbsolute(Name, Sym);
219   }
220   if (Sym.getSectionNumber() == llvm::COFF::IMAGE_SYM_DEBUG)
221     return nullptr;
222 
223   // Nothing else to do without a section chunk.
224   auto *SC = cast_or_null<SectionChunk>(SparseChunks[Sym.getSectionNumber()]);
225   if (!SC)
226     return nullptr;
227 
228   // Handle section definitions
229   if (IsFirst && AuxP) {
230     auto *Aux = reinterpret_cast<const coff_aux_section_definition *>(AuxP);
231     if (Aux->Selection == IMAGE_COMDAT_SELECT_ASSOCIATIVE)
232       if (auto *ParentSC = cast_or_null<SectionChunk>(
233               SparseChunks[Aux->getNumber(Sym.isBigObj())]))
234         ParentSC->addAssociative(SC);
235     SC->Checksum = Aux->CheckSum;
236   }
237 
238   auto *B = new (Alloc) DefinedRegular(this, Sym, SC);
239   if (SC->isCOMDAT() && Sym.getValue() == 0 && !AuxP)
240     SC->setSymbol(B);
241 
242   return B;
243 }
244 
245 void ObjectFile::initializeSEH() {
246   if (!SEHCompat || !SXData)
247     return;
248   ArrayRef<uint8_t> A;
249   COFFObj->getSectionContents(SXData, A);
250   if (A.size() % 4 != 0)
251     error(".sxdata must be an array of symbol table indices");
252   auto *I = reinterpret_cast<const ulittle32_t *>(A.data());
253   auto *E = reinterpret_cast<const ulittle32_t *>(A.data() + A.size());
254   for (; I != E; ++I)
255     SEHandlers.insert(SparseSymbolBodies[*I]);
256 }
257 
258 MachineTypes ObjectFile::getMachineType() {
259   if (COFFObj)
260     return static_cast<MachineTypes>(COFFObj->getMachine());
261   return IMAGE_FILE_MACHINE_UNKNOWN;
262 }
263 
264 StringRef ltrim1(StringRef S, const char *Chars) {
265   if (!S.empty() && strchr(Chars, S[0]))
266     return S.substr(1);
267   return S;
268 }
269 
270 void ImportFile::parse() {
271   const char *Buf = MB.getBufferStart();
272   const char *End = MB.getBufferEnd();
273   const auto *Hdr = reinterpret_cast<const coff_import_header *>(Buf);
274 
275   // Check if the total size is valid.
276   if ((size_t)(End - Buf) != (sizeof(*Hdr) + Hdr->SizeOfData))
277     error("broken import library");
278 
279   // Read names and create an __imp_ symbol.
280   StringRef Name = StringAlloc.save(StringRef(Buf + sizeof(*Hdr)));
281   StringRef ImpName = StringAlloc.save(Twine("__imp_") + Name);
282   const char *NameStart = Buf + sizeof(coff_import_header) + Name.size() + 1;
283   DLLName = StringRef(NameStart);
284   StringRef ExtName;
285   switch (Hdr->getNameType()) {
286   case IMPORT_ORDINAL:
287     ExtName = "";
288     break;
289   case IMPORT_NAME:
290     ExtName = Name;
291     break;
292   case IMPORT_NAME_NOPREFIX:
293     ExtName = ltrim1(Name, "?@_");
294     break;
295   case IMPORT_NAME_UNDECORATE:
296     ExtName = ltrim1(Name, "?@_");
297     ExtName = ExtName.substr(0, ExtName.find('@'));
298     break;
299   }
300   ImpSym = new (Alloc) DefinedImportData(DLLName, ImpName, ExtName, Hdr);
301   SymbolBodies.push_back(ImpSym);
302 
303   // If type is function, we need to create a thunk which jump to an
304   // address pointed by the __imp_ symbol. (This allows you to call
305   // DLL functions just like regular non-DLL functions.)
306   if (Hdr->getType() != llvm::COFF::IMPORT_CODE)
307     return;
308   ThunkSym = new (Alloc) DefinedImportThunk(Name, ImpSym, Hdr->Machine);
309   SymbolBodies.push_back(ThunkSym);
310 }
311 
312 void BitcodeFile::parse() {
313   // Usually parse() is thread-safe, but bitcode file is an exception.
314   std::lock_guard<std::mutex> Lock(Mu);
315 
316   std::string Err;
317   M.reset(LTOModule::createFromBuffer(MB.getBufferStart(),
318                                       MB.getBufferSize(),
319                                       llvm::TargetOptions(), Err));
320   if (!Err.empty())
321     error(Err);
322 
323   llvm::StringSaver Saver(Alloc);
324   for (unsigned I = 0, E = M->getSymbolCount(); I != E; ++I) {
325     lto_symbol_attributes Attrs = M->getSymbolAttributes(I);
326     if ((Attrs & LTO_SYMBOL_SCOPE_MASK) == LTO_SYMBOL_SCOPE_INTERNAL)
327       continue;
328 
329     StringRef SymName = Saver.save(M->getSymbolName(I));
330     int SymbolDef = Attrs & LTO_SYMBOL_DEFINITION_MASK;
331     if (SymbolDef == LTO_SYMBOL_DEFINITION_UNDEFINED) {
332       SymbolBodies.push_back(new (Alloc) Undefined(SymName));
333     } else {
334       bool Replaceable =
335           (SymbolDef == LTO_SYMBOL_DEFINITION_TENTATIVE || // common
336            (Attrs & LTO_SYMBOL_COMDAT) ||                  // comdat
337            (SymbolDef == LTO_SYMBOL_DEFINITION_WEAK &&     // weak external
338             (Attrs & LTO_SYMBOL_ALIAS)));
339       SymbolBodies.push_back(new (Alloc) DefinedBitcode(this, SymName,
340                                                         Replaceable));
341     }
342   }
343 
344   Directives = M->getLinkerOpts();
345 }
346 
347 MachineTypes BitcodeFile::getMachineType() {
348   if (!M)
349     return IMAGE_FILE_MACHINE_UNKNOWN;
350   switch (Triple(M->getTargetTriple()).getArch()) {
351   case Triple::x86_64:
352     return AMD64;
353   case Triple::x86:
354     return I386;
355   case Triple::arm:
356     return ARMNT;
357   default:
358     return IMAGE_FILE_MACHINE_UNKNOWN;
359   }
360 }
361 
362 std::mutex BitcodeFile::Mu;
363 
364 } // namespace coff
365 } // namespace lld
366