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     COFFSymbolRef Sym = check(COFFObj->getSymbol(I));
184 
185     const void *AuxP = nullptr;
186     if (Sym.getNumberOfAuxSymbols())
187       AuxP = check(COFFObj->getSymbol(I + 1)).getRawPtr();
188     bool IsFirst = (LastSectionNumber != Sym.getSectionNumber());
189 
190     SymbolBody *Body = nullptr;
191     if (Sym.isUndefined()) {
192       Body = createUndefined(Sym);
193     } else if (Sym.isWeakExternal()) {
194       Body = createUndefined(Sym);
195       uint32_t TagIndex =
196           static_cast<const coff_aux_weak_external *>(AuxP)->TagIndex;
197       WeakAliases.emplace_back(Body, TagIndex);
198     } else {
199       Body = createDefined(Sym, AuxP, IsFirst);
200     }
201     if (Body) {
202       SymbolBodies.push_back(Body);
203       SparseSymbolBodies[I] = Body;
204     }
205     I += Sym.getNumberOfAuxSymbols();
206     LastSectionNumber = Sym.getSectionNumber();
207   }
208 
209   for (auto &KV : WeakAliases) {
210     SymbolBody *Sym = KV.first;
211     uint32_t Idx = KV.second;
212     checkAndSetWeakAlias(Symtab, this, Sym, SparseSymbolBodies[Idx]);
213   }
214 }
215 
216 SymbolBody *ObjFile::createUndefined(COFFSymbolRef Sym) {
217   StringRef Name;
218   COFFObj->getSymbolName(Sym, Name);
219   return Symtab->addUndefined(Name, this, Sym.isWeakExternal())->body();
220 }
221 
222 SymbolBody *ObjFile::createDefined(COFFSymbolRef Sym, const void *AuxP,
223                                    bool IsFirst) {
224   StringRef Name;
225   if (Sym.isCommon()) {
226     auto *C = make<CommonChunk>(Sym);
227     Chunks.push_back(C);
228     COFFObj->getSymbolName(Sym, Name);
229     Symbol *S =
230         Symtab->addCommon(this, Name, Sym.getValue(), Sym.getGeneric(), C);
231     return S->body();
232   }
233   if (Sym.isAbsolute()) {
234     COFFObj->getSymbolName(Sym, Name);
235     // Skip special symbols.
236     if (Name == "@comp.id")
237       return nullptr;
238     // COFF spec 5.10.1. The .sxdata section.
239     if (Name == "@feat.00") {
240       if (Sym.getValue() & 1)
241         SEHCompat = true;
242       return nullptr;
243     }
244     if (Sym.isExternal())
245       return Symtab->addAbsolute(Name, Sym)->body();
246     else
247       return make<DefinedAbsolute>(Name, Sym);
248   }
249   int32_t SectionNumber = Sym.getSectionNumber();
250   if (SectionNumber == llvm::COFF::IMAGE_SYM_DEBUG)
251     return nullptr;
252 
253   // Reserved sections numbers don't have contents.
254   if (llvm::COFF::isReservedSectionNumber(SectionNumber))
255     fatal("broken object file: " + toString(this));
256 
257   // This symbol references a section which is not present in the section
258   // header.
259   if ((uint32_t)SectionNumber >= SparseChunks.size())
260     fatal("broken object file: " + toString(this));
261 
262   // Nothing else to do without a section chunk.
263   auto *SC = cast_or_null<SectionChunk>(SparseChunks[SectionNumber]);
264   if (!SC)
265     return nullptr;
266 
267   // Handle section definitions
268   if (IsFirst && AuxP) {
269     auto *Aux = reinterpret_cast<const coff_aux_section_definition *>(AuxP);
270     if (Aux->Selection == IMAGE_COMDAT_SELECT_ASSOCIATIVE)
271       if (auto *ParentSC = cast_or_null<SectionChunk>(
272               SparseChunks[Aux->getNumber(Sym.isBigObj())])) {
273         ParentSC->addAssociative(SC);
274         // If we already discarded the parent, discard the child.
275         if (ParentSC->isDiscarded())
276           SC->markDiscarded();
277       }
278     SC->Checksum = Aux->CheckSum;
279   }
280 
281   DefinedRegular *B;
282   if (Sym.isExternal()) {
283     COFFObj->getSymbolName(Sym, Name);
284     Symbol *S =
285         Symtab->addRegular(this, Name, SC->isCOMDAT(), Sym.getGeneric(), SC);
286     B = cast<DefinedRegular>(S->body());
287   } else
288     B = make<DefinedRegular>(this, /*Name*/ "", SC->isCOMDAT(),
289                              /*IsExternal*/ false, Sym.getGeneric(), SC);
290   if (SC->isCOMDAT() && Sym.getValue() == 0 && !AuxP)
291     SC->setSymbol(B);
292 
293   return B;
294 }
295 
296 void ObjFile::initializeSEH() {
297   if (!SEHCompat || !SXData)
298     return;
299   ArrayRef<uint8_t> A;
300   COFFObj->getSectionContents(SXData, A);
301   if (A.size() % 4 != 0)
302     fatal(".sxdata must be an array of symbol table indices");
303   auto *I = reinterpret_cast<const ulittle32_t *>(A.data());
304   auto *E = reinterpret_cast<const ulittle32_t *>(A.data() + A.size());
305   for (; I != E; ++I)
306     SEHandlers.insert(SparseSymbolBodies[*I]);
307 }
308 
309 MachineTypes ObjFile::getMachineType() {
310   if (COFFObj)
311     return static_cast<MachineTypes>(COFFObj->getMachine());
312   return IMAGE_FILE_MACHINE_UNKNOWN;
313 }
314 
315 StringRef ltrim1(StringRef S, const char *Chars) {
316   if (!S.empty() && strchr(Chars, S[0]))
317     return S.substr(1);
318   return S;
319 }
320 
321 void ImportFile::parse() {
322   const char *Buf = MB.getBufferStart();
323   const char *End = MB.getBufferEnd();
324   const auto *Hdr = reinterpret_cast<const coff_import_header *>(Buf);
325 
326   // Check if the total size is valid.
327   if ((size_t)(End - Buf) != (sizeof(*Hdr) + Hdr->SizeOfData))
328     fatal("broken import library");
329 
330   // Read names and create an __imp_ symbol.
331   StringRef Name = Saver.save(StringRef(Buf + sizeof(*Hdr)));
332   StringRef ImpName = Saver.save("__imp_" + Name);
333   const char *NameStart = Buf + sizeof(coff_import_header) + Name.size() + 1;
334   DLLName = StringRef(NameStart);
335   StringRef ExtName;
336   switch (Hdr->getNameType()) {
337   case IMPORT_ORDINAL:
338     ExtName = "";
339     break;
340   case IMPORT_NAME:
341     ExtName = Name;
342     break;
343   case IMPORT_NAME_NOPREFIX:
344     ExtName = ltrim1(Name, "?@_");
345     break;
346   case IMPORT_NAME_UNDECORATE:
347     ExtName = ltrim1(Name, "?@_");
348     ExtName = ExtName.substr(0, ExtName.find('@'));
349     break;
350   }
351 
352   this->Hdr = Hdr;
353   ExternalName = ExtName;
354 
355   ImpSym = Symtab->addImportData(ImpName, this);
356 
357   if (Hdr->getType() == llvm::COFF::IMPORT_CONST)
358     static_cast<void>(Symtab->addImportData(Name, this));
359 
360   // If type is function, we need to create a thunk which jump to an
361   // address pointed by the __imp_ symbol. (This allows you to call
362   // DLL functions just like regular non-DLL functions.)
363   if (Hdr->getType() == llvm::COFF::IMPORT_CODE)
364     ThunkSym = Symtab->addImportThunk(Name, ImpSym, Hdr->Machine);
365 }
366 
367 void BitcodeFile::parse() {
368   Obj = check(lto::InputFile::create(MemoryBufferRef(
369       MB.getBuffer(), Saver.save(ParentName + MB.getBufferIdentifier()))));
370   for (const lto::InputFile::Symbol &ObjSym : Obj->symbols()) {
371     StringRef SymName = Saver.save(ObjSym.getName());
372     Symbol *Sym;
373     if (ObjSym.isUndefined()) {
374       Sym = Symtab->addUndefined(SymName, this, false);
375     } else if (ObjSym.isCommon()) {
376       Sym = Symtab->addCommon(this, SymName, ObjSym.getCommonSize());
377     } else if (ObjSym.isWeak() && ObjSym.isIndirect()) {
378       // Weak external.
379       Sym = Symtab->addUndefined(SymName, this, true);
380       std::string Fallback = ObjSym.getCOFFWeakExternalFallback();
381       SymbolBody *Alias = Symtab->addUndefined(Saver.save(Fallback));
382       checkAndSetWeakAlias(Symtab, this, Sym->body(), Alias);
383     } else {
384       bool IsCOMDAT = ObjSym.getComdatIndex() != -1;
385       Sym = Symtab->addRegular(this, SymName, IsCOMDAT);
386     }
387     SymbolBodies.push_back(Sym->body());
388   }
389   Directives = Obj->getCOFFLinkerOpts();
390 }
391 
392 MachineTypes BitcodeFile::getMachineType() {
393   switch (Triple(Obj->getTargetTriple()).getArch()) {
394   case Triple::x86_64:
395     return AMD64;
396   case Triple::x86:
397     return I386;
398   case Triple::arm:
399     return ARMNT;
400   case Triple::aarch64:
401     return ARM64;
402   default:
403     return IMAGE_FILE_MACHINE_UNKNOWN;
404   }
405 }
406 } // namespace coff
407 } // namespace lld
408 
409 // Returns the last element of a path, which is supposed to be a filename.
410 static StringRef getBasename(StringRef Path) {
411   size_t Pos = Path.find_last_of("\\/");
412   if (Pos == StringRef::npos)
413     return Path;
414   return Path.substr(Pos + 1);
415 }
416 
417 // Returns a string in the format of "foo.obj" or "foo.obj(bar.lib)".
418 std::string lld::toString(coff::InputFile *File) {
419   if (!File)
420     return "(internal)";
421   if (File->ParentName.empty())
422     return File->getName().lower();
423 
424   std::string Res =
425       (getBasename(File->ParentName) + "(" + getBasename(File->getName()) + ")")
426           .str();
427   return StringRef(Res).lower();
428 }
429