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