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