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