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