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 "InputFiles.h"
11 #include "Chunks.h"
12 #include "Config.h"
13 #include "Driver.h"
14 #include "Error.h"
15 #include "Memory.h"
16 #include "SymbolTable.h"
17 #include "Symbols.h"
18 #include "llvm-c/lto.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/ADT/Triple.h"
21 #include "llvm/ADT/Twine.h"
22 #include "llvm/BinaryFormat/COFF.h"
23 #include "llvm/Object/Binary.h"
24 #include "llvm/Object/COFF.h"
25 #include "llvm/Support/Casting.h"
26 #include "llvm/Support/Endian.h"
27 #include "llvm/Support/Error.h"
28 #include "llvm/Support/ErrorOr.h"
29 #include "llvm/Support/FileSystem.h"
30 #include "llvm/Target/TargetOptions.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 std::vector<ObjFile *> ObjFile::Instances;
47 std::vector<ImportFile *> ImportFile::Instances;
48 std::vector<BitcodeFile *> BitcodeFile::Instances;
49 
50 /// Checks that Source is compatible with being a weak alias to Target.
51 /// If Source is Undefined and has no weak alias set, makes it a weak
52 /// alias to Target.
53 static void checkAndSetWeakAlias(SymbolTable *Symtab, InputFile *F,
54                                  SymbolBody *Source, SymbolBody *Target) {
55   if (auto *U = dyn_cast<Undefined>(Source)) {
56     if (U->WeakAlias && U->WeakAlias != Target)
57       Symtab->reportDuplicate(Source->symbol(), F);
58     U->WeakAlias = Target;
59   }
60 }
61 
62 ArchiveFile::ArchiveFile(MemoryBufferRef M) : InputFile(ArchiveKind, M) {}
63 
64 void ArchiveFile::parse() {
65   // Parse a MemoryBufferRef as an archive file.
66   File = check(Archive::create(MB), toString(this));
67 
68   // Read the symbol table to construct Lazy objects.
69   for (const Archive::Symbol &Sym : File->symbols())
70     Symtab->addLazy(this, Sym);
71 }
72 
73 // Returns a buffer pointing to a member file containing a given symbol.
74 void ArchiveFile::addMember(const Archive::Symbol *Sym) {
75   const Archive::Child &C =
76       check(Sym->getMember(),
77             "could not get the member for symbol " + Sym->getName());
78 
79   // Return an empty buffer if we have already returned the same buffer.
80   if (!Seen.insert(C.getChildOffset()).second)
81     return;
82 
83   Driver->enqueueArchiveMember(C, Sym->getName(), getName());
84 }
85 
86 std::vector<MemoryBufferRef> getArchiveMembers(Archive *File) {
87   std::vector<MemoryBufferRef> V;
88   Error Err = Error::success();
89   for (const ErrorOr<Archive::Child> &COrErr : File->children(Err)) {
90     Archive::Child C =
91         check(COrErr,
92               File->getFileName() + ": could not get the child of the archive");
93     MemoryBufferRef MBRef =
94         check(C.getMemoryBufferRef(),
95               File->getFileName() +
96                   ": could not get the buffer for a child of the archive");
97     V.push_back(MBRef);
98   }
99   if (Err)
100     fatal(File->getFileName() +
101           ": Archive::children failed: " + toString(std::move(Err)));
102   return V;
103 }
104 
105 void ObjFile::parse() {
106   // Parse a memory buffer as a COFF file.
107   std::unique_ptr<Binary> Bin = check(createBinary(MB), toString(this));
108 
109   if (auto *Obj = dyn_cast<COFFObjectFile>(Bin.get())) {
110     Bin.release();
111     COFFObj.reset(Obj);
112   } else {
113     fatal(toString(this) + " is not a COFF file");
114   }
115 
116   // Read section and symbol tables.
117   initializeChunks();
118   initializeSymbols();
119   initializeSEH();
120 }
121 
122 void ObjFile::initializeChunks() {
123   uint32_t NumSections = COFFObj->getNumberOfSections();
124   Chunks.reserve(NumSections);
125   SparseChunks.resize(NumSections + 1);
126   for (uint32_t I = 1; I < NumSections + 1; ++I) {
127     const coff_section *Sec;
128     StringRef Name;
129     if (auto EC = COFFObj->getSection(I, Sec))
130       fatal(EC, "getSection failed: #" + Twine(I));
131     if (auto EC = COFFObj->getSectionName(Sec, Name))
132       fatal(EC, "getSectionName failed: #" + Twine(I));
133     if (Name == ".sxdata") {
134       SXData = Sec;
135       continue;
136     }
137     if (Name == ".drectve") {
138       ArrayRef<uint8_t> Data;
139       COFFObj->getSectionContents(Sec, Data);
140       Directives = std::string((const char *)Data.data(), Data.size());
141       continue;
142     }
143 
144     // Object files may have DWARF debug info or MS CodeView debug info
145     // (or both).
146     //
147     // DWARF sections don't need any special handling from the perspective
148     // of the linker; they are just a data section containing relocations.
149     // We can just link them to complete debug info.
150     //
151     // CodeView needs a linker support. We need to interpret and debug
152     // info, and then write it to a separate .pdb file.
153 
154     // Ignore debug info unless /debug is given.
155     if (!Config->Debug && Name.startswith(".debug"))
156       continue;
157 
158     if (Sec->Characteristics & llvm::COFF::IMAGE_SCN_LNK_REMOVE)
159       continue;
160     auto *C = make<SectionChunk>(this, Sec);
161 
162     // CodeView sections are stored to a different vector because they are not
163     // linked in the regular manner.
164     if (C->isCodeView())
165       DebugChunks.push_back(C);
166     else
167       Chunks.push_back(C);
168 
169     SparseChunks[I] = C;
170   }
171 }
172 
173 void ObjFile::initializeSymbols() {
174   uint32_t NumSymbols = COFFObj->getNumberOfSymbols();
175   SymbolBodies.reserve(NumSymbols);
176   SparseSymbolBodies.resize(NumSymbols);
177 
178   SmallVector<std::pair<SymbolBody *, uint32_t>, 8> WeakAliases;
179   int32_t LastSectionNumber = 0;
180 
181   for (uint32_t I = 0; I < NumSymbols; ++I) {
182     // Get a COFFSymbolRef object.
183     ErrorOr<COFFSymbolRef> SymOrErr = COFFObj->getSymbol(I);
184     if (!SymOrErr)
185       fatal(SymOrErr.getError(), "broken object file: " + toString(this));
186     COFFSymbolRef Sym = *SymOrErr;
187 
188     const void *AuxP = nullptr;
189     if (Sym.getNumberOfAuxSymbols())
190       AuxP = COFFObj->getSymbol(I + 1)->getRawPtr();
191     bool IsFirst = (LastSectionNumber != Sym.getSectionNumber());
192 
193     SymbolBody *Body = nullptr;
194     if (Sym.isUndefined()) {
195       Body = createUndefined(Sym);
196     } else if (Sym.isWeakExternal()) {
197       Body = createUndefined(Sym);
198       uint32_t TagIndex =
199           static_cast<const coff_aux_weak_external *>(AuxP)->TagIndex;
200       WeakAliases.emplace_back(Body, TagIndex);
201     } else {
202       Body = createDefined(Sym, AuxP, IsFirst);
203     }
204     if (Body) {
205       SymbolBodies.push_back(Body);
206       SparseSymbolBodies[I] = Body;
207     }
208     I += Sym.getNumberOfAuxSymbols();
209     LastSectionNumber = Sym.getSectionNumber();
210   }
211 
212   for (auto &KV : WeakAliases) {
213     SymbolBody *Sym = KV.first;
214     uint32_t Idx = KV.second;
215     checkAndSetWeakAlias(Symtab, this, Sym, SparseSymbolBodies[Idx]);
216   }
217 }
218 
219 SymbolBody *ObjFile::createUndefined(COFFSymbolRef Sym) {
220   StringRef Name;
221   COFFObj->getSymbolName(Sym, Name);
222   return Symtab->addUndefined(Name, this, Sym.isWeakExternal())->body();
223 }
224 
225 SymbolBody *ObjFile::createDefined(COFFSymbolRef Sym, const void *AuxP,
226                                    bool IsFirst) {
227   StringRef Name;
228   if (Sym.isCommon()) {
229     auto *C = make<CommonChunk>(Sym);
230     Chunks.push_back(C);
231     COFFObj->getSymbolName(Sym, Name);
232     Symbol *S =
233         Symtab->addCommon(this, Name, Sym.getValue(), Sym.getGeneric(), C);
234     return S->body();
235   }
236   if (Sym.isAbsolute()) {
237     COFFObj->getSymbolName(Sym, Name);
238     // Skip special symbols.
239     if (Name == "@comp.id")
240       return nullptr;
241     // COFF spec 5.10.1. The .sxdata section.
242     if (Name == "@feat.00") {
243       if (Sym.getValue() & 1)
244         SEHCompat = true;
245       return nullptr;
246     }
247     if (Sym.isExternal())
248       return Symtab->addAbsolute(Name, Sym)->body();
249     else
250       return make<DefinedAbsolute>(Name, Sym);
251   }
252   int32_t SectionNumber = Sym.getSectionNumber();
253   if (SectionNumber == llvm::COFF::IMAGE_SYM_DEBUG)
254     return nullptr;
255 
256   // Reserved sections numbers don't have contents.
257   if (llvm::COFF::isReservedSectionNumber(SectionNumber))
258     fatal("broken object file: " + toString(this));
259 
260   // This symbol references a section which is not present in the section
261   // header.
262   if ((uint32_t)SectionNumber >= SparseChunks.size())
263     fatal("broken object file: " + toString(this));
264 
265   // Nothing else to do without a section chunk.
266   auto *SC = cast_or_null<SectionChunk>(SparseChunks[SectionNumber]);
267   if (!SC)
268     return nullptr;
269 
270   // Handle section definitions
271   if (IsFirst && AuxP) {
272     auto *Aux = reinterpret_cast<const coff_aux_section_definition *>(AuxP);
273     if (Aux->Selection == IMAGE_COMDAT_SELECT_ASSOCIATIVE)
274       if (auto *ParentSC = cast_or_null<SectionChunk>(
275               SparseChunks[Aux->getNumber(Sym.isBigObj())])) {
276         ParentSC->addAssociative(SC);
277         // If we already discarded the parent, discard the child.
278         if (ParentSC->isDiscarded())
279           SC->markDiscarded();
280       }
281     SC->Checksum = Aux->CheckSum;
282   }
283 
284   DefinedRegular *B;
285   if (Sym.isExternal()) {
286     COFFObj->getSymbolName(Sym, Name);
287     Symbol *S =
288         Symtab->addRegular(this, Name, SC->isCOMDAT(), Sym.getGeneric(), SC);
289     B = cast<DefinedRegular>(S->body());
290   } else
291     B = make<DefinedRegular>(this, /*Name*/ "", SC->isCOMDAT(),
292                              /*IsExternal*/ false, Sym.getGeneric(), SC);
293   if (SC->isCOMDAT() && Sym.getValue() == 0 && !AuxP)
294     SC->setSymbol(B);
295 
296   return B;
297 }
298 
299 void ObjFile::initializeSEH() {
300   if (!SEHCompat || !SXData)
301     return;
302   ArrayRef<uint8_t> A;
303   COFFObj->getSectionContents(SXData, A);
304   if (A.size() % 4 != 0)
305     fatal(".sxdata must be an array of symbol table indices");
306   auto *I = reinterpret_cast<const ulittle32_t *>(A.data());
307   auto *E = reinterpret_cast<const ulittle32_t *>(A.data() + A.size());
308   for (; I != E; ++I)
309     SEHandlers.insert(SparseSymbolBodies[*I]);
310 }
311 
312 MachineTypes ObjFile::getMachineType() {
313   if (COFFObj)
314     return static_cast<MachineTypes>(COFFObj->getMachine());
315   return IMAGE_FILE_MACHINE_UNKNOWN;
316 }
317 
318 StringRef ltrim1(StringRef S, const char *Chars) {
319   if (!S.empty() && strchr(Chars, S[0]))
320     return S.substr(1);
321   return S;
322 }
323 
324 void ImportFile::parse() {
325   const char *Buf = MB.getBufferStart();
326   const char *End = MB.getBufferEnd();
327   const auto *Hdr = reinterpret_cast<const coff_import_header *>(Buf);
328 
329   // Check if the total size is valid.
330   if ((size_t)(End - Buf) != (sizeof(*Hdr) + Hdr->SizeOfData))
331     fatal("broken import library");
332 
333   // Read names and create an __imp_ symbol.
334   StringRef Name = Saver.save(StringRef(Buf + sizeof(*Hdr)));
335   StringRef ImpName = Saver.save("__imp_" + Name);
336   const char *NameStart = Buf + sizeof(coff_import_header) + Name.size() + 1;
337   DLLName = StringRef(NameStart);
338   StringRef ExtName;
339   switch (Hdr->getNameType()) {
340   case IMPORT_ORDINAL:
341     ExtName = "";
342     break;
343   case IMPORT_NAME:
344     ExtName = Name;
345     break;
346   case IMPORT_NAME_NOPREFIX:
347     ExtName = ltrim1(Name, "?@_");
348     break;
349   case IMPORT_NAME_UNDECORATE:
350     ExtName = ltrim1(Name, "?@_");
351     ExtName = ExtName.substr(0, ExtName.find('@'));
352     break;
353   }
354 
355   this->Hdr = Hdr;
356   ExternalName = ExtName;
357 
358   ImpSym = Symtab->addImportData(ImpName, this);
359 
360   if (Hdr->getType() == llvm::COFF::IMPORT_CONST)
361     static_cast<void>(Symtab->addImportData(Name, this));
362 
363   // If type is function, we need to create a thunk which jump to an
364   // address pointed by the __imp_ symbol. (This allows you to call
365   // DLL functions just like regular non-DLL functions.)
366   if (Hdr->getType() == llvm::COFF::IMPORT_CODE)
367     ThunkSym = Symtab->addImportThunk(Name, ImpSym, Hdr->Machine);
368 }
369 
370 void BitcodeFile::parse() {
371   Obj = check(lto::InputFile::create(MemoryBufferRef(
372       MB.getBuffer(), Saver.save(ParentName + MB.getBufferIdentifier()))));
373   for (const lto::InputFile::Symbol &ObjSym : Obj->symbols()) {
374     StringRef SymName = Saver.save(ObjSym.getName());
375     Symbol *Sym;
376     if (ObjSym.isUndefined()) {
377       Sym = Symtab->addUndefined(SymName, this, false);
378     } else if (ObjSym.isCommon()) {
379       Sym = Symtab->addCommon(this, SymName, ObjSym.getCommonSize());
380     } else if (ObjSym.isWeak() && ObjSym.isIndirect()) {
381       // Weak external.
382       Sym = Symtab->addUndefined(SymName, this, true);
383       std::string Fallback = ObjSym.getCOFFWeakExternalFallback();
384       SymbolBody *Alias = Symtab->addUndefined(Saver.save(Fallback));
385       checkAndSetWeakAlias(Symtab, this, Sym->body(), Alias);
386     } else {
387       bool IsCOMDAT = ObjSym.getComdatIndex() != -1;
388       Sym = Symtab->addRegular(this, SymName, IsCOMDAT);
389     }
390     SymbolBodies.push_back(Sym->body());
391   }
392   Directives = Obj->getCOFFLinkerOpts();
393 }
394 
395 MachineTypes BitcodeFile::getMachineType() {
396   switch (Triple(Obj->getTargetTriple()).getArch()) {
397   case Triple::x86_64:
398     return AMD64;
399   case Triple::x86:
400     return I386;
401   case Triple::arm:
402     return ARMNT;
403   case Triple::aarch64:
404     return ARM64;
405   default:
406     return IMAGE_FILE_MACHINE_UNKNOWN;
407   }
408 }
409 } // namespace coff
410 } // namespace lld
411 
412 // Returns the last element of a path, which is supposed to be a filename.
413 static StringRef getBasename(StringRef Path) {
414   size_t Pos = Path.find_last_of("\\/");
415   if (Pos == StringRef::npos)
416     return Path;
417   return Path.substr(Pos + 1);
418 }
419 
420 // Returns a string in the format of "foo.obj" or "foo.obj(bar.lib)".
421 std::string lld::toString(coff::InputFile *File) {
422   if (!File)
423     return "(internal)";
424   if (File->ParentName.empty())
425     return File->getName().lower();
426 
427   std::string Res =
428       (getBasename(File->ParentName) + "(" + getBasename(File->getName()) + ")")
429           .str();
430   return StringRef(Res).lower();
431 }
432