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/LTO/LTOModule.h"
16 #include "llvm/Object/COFF.h"
17 #include "llvm/Support/COFF.h"
18 #include "llvm/Support/Debug.h"
19 #include "llvm/Support/Endian.h"
20 #include "llvm/Support/raw_ostream.h"
21 
22 using namespace llvm::COFF;
23 using namespace llvm::object;
24 using namespace llvm::support::endian;
25 using llvm::RoundUpToAlignment;
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<Undefined *, 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 = createWeakExternal(Sym, AuxP);
171       WeakAliases.push_back((Undefined *)Body);
172     } else {
173       Body = createDefined(Sym, AuxP, IsFirst);
174     }
175     if (Body) {
176       SymbolBodies.push_back(Body);
177       SparseSymbolBodies[I] = Body;
178     }
179     I += Sym.getNumberOfAuxSymbols();
180     LastSectionNumber = Sym.getSectionNumber();
181   }
182   for (Undefined *U : WeakAliases)
183     U->WeakAlias = SparseSymbolBodies[(uintptr_t)U->WeakAlias];
184 }
185 
186 Undefined *ObjectFile::createUndefined(COFFSymbolRef Sym) {
187   StringRef Name;
188   COFFObj->getSymbolName(Sym, Name);
189   return new (Alloc) Undefined(Name);
190 }
191 
192 Undefined *ObjectFile::createWeakExternal(COFFSymbolRef Sym, const void *AuxP) {
193   StringRef Name;
194   COFFObj->getSymbolName(Sym, Name);
195   auto *U = new (Alloc) Undefined(Name);
196   auto *Aux = (const coff_aux_weak_external *)AuxP;
197   U->WeakAlias = (Undefined *)(uintptr_t)Aux->TagIndex;
198   return U;
199 }
200 
201 Defined *ObjectFile::createDefined(COFFSymbolRef Sym, const void *AuxP,
202                                    bool IsFirst) {
203   StringRef Name;
204   if (Sym.isCommon()) {
205     auto *C = new (Alloc) CommonChunk(Sym);
206     Chunks.push_back(C);
207     return new (Alloc) DefinedCommon(this, Sym, C);
208   }
209   if (Sym.isAbsolute()) {
210     COFFObj->getSymbolName(Sym, Name);
211     // Skip special symbols.
212     if (Name == "@comp.id")
213       return nullptr;
214     // COFF spec 5.10.1. The .sxdata section.
215     if (Name == "@feat.00") {
216       if (Sym.getValue() & 1)
217         SEHCompat = true;
218       return nullptr;
219     }
220     return new (Alloc) DefinedAbsolute(Name, Sym);
221   }
222   if (Sym.getSectionNumber() == llvm::COFF::IMAGE_SYM_DEBUG)
223     return nullptr;
224 
225   // Nothing else to do without a section chunk.
226   auto *SC = cast_or_null<SectionChunk>(SparseChunks[Sym.getSectionNumber()]);
227   if (!SC)
228     return nullptr;
229 
230   // Handle section definitions
231   if (IsFirst && AuxP) {
232     auto *Aux = reinterpret_cast<const coff_aux_section_definition *>(AuxP);
233     if (Aux->Selection == IMAGE_COMDAT_SELECT_ASSOCIATIVE)
234       if (auto *ParentSC = cast_or_null<SectionChunk>(
235               SparseChunks[Aux->getNumber(Sym.isBigObj())]))
236         ParentSC->addAssociative(SC);
237     SC->Checksum = Aux->CheckSum;
238   }
239 
240   auto *B = new (Alloc) DefinedRegular(this, Sym, SC);
241   if (SC->isCOMDAT() && Sym.getValue() == 0 && !AuxP)
242     SC->setSymbol(B);
243 
244   return B;
245 }
246 
247 void ObjectFile::initializeSEH() {
248   if (!SEHCompat || !SXData)
249     return;
250   ArrayRef<uint8_t> A;
251   COFFObj->getSectionContents(SXData, A);
252   if (A.size() % 4 != 0)
253     error(".sxdata must be an array of symbol table indices");
254   auto *I = reinterpret_cast<const ulittle32_t *>(A.data());
255   auto *E = reinterpret_cast<const ulittle32_t *>(A.data() + A.size());
256   for (; I != E; ++I)
257     SEHandlers.insert(SparseSymbolBodies[*I]);
258 }
259 
260 MachineTypes ObjectFile::getMachineType() {
261   if (COFFObj)
262     return static_cast<MachineTypes>(COFFObj->getMachine());
263   return IMAGE_FILE_MACHINE_UNKNOWN;
264 }
265 
266 StringRef ltrim1(StringRef S, const char *Chars) {
267   if (!S.empty() && strchr(Chars, S[0]))
268     return S.substr(1);
269   return S;
270 }
271 
272 void ImportFile::parse() {
273   const char *Buf = MB.getBufferStart();
274   const char *End = MB.getBufferEnd();
275   const auto *Hdr = reinterpret_cast<const coff_import_header *>(Buf);
276 
277   // Check if the total size is valid.
278   if ((size_t)(End - Buf) != (sizeof(*Hdr) + Hdr->SizeOfData))
279     error("broken import library");
280 
281   // Read names and create an __imp_ symbol.
282   StringRef Name = StringAlloc.save(StringRef(Buf + sizeof(*Hdr)));
283   StringRef ImpName = StringAlloc.save(Twine("__imp_") + Name);
284   const char *NameStart = Buf + sizeof(coff_import_header) + Name.size() + 1;
285   DLLName = StringRef(NameStart);
286   StringRef ExtName;
287   switch (Hdr->getNameType()) {
288   case IMPORT_ORDINAL:
289     ExtName = "";
290     break;
291   case IMPORT_NAME:
292     ExtName = Name;
293     break;
294   case IMPORT_NAME_NOPREFIX:
295     ExtName = ltrim1(Name, "?@_");
296     break;
297   case IMPORT_NAME_UNDECORATE:
298     ExtName = ltrim1(Name, "?@_");
299     ExtName = ExtName.substr(0, ExtName.find('@'));
300     break;
301   }
302   ImpSym = new (Alloc) DefinedImportData(DLLName, ImpName, ExtName, Hdr);
303   SymbolBodies.push_back(ImpSym);
304 
305   // If type is function, we need to create a thunk which jump to an
306   // address pointed by the __imp_ symbol. (This allows you to call
307   // DLL functions just like regular non-DLL functions.)
308   if (Hdr->getType() != llvm::COFF::IMPORT_CODE)
309     return;
310   ThunkSym = new (Alloc) DefinedImportThunk(Name, ImpSym, Hdr->Machine);
311   SymbolBodies.push_back(ThunkSym);
312 }
313 
314 void BitcodeFile::parse() {
315   // Usually parse() is thread-safe, but bitcode file is an exception.
316   std::lock_guard<std::mutex> Lock(Mu);
317 
318   std::string Err;
319   M.reset(LTOModule::createFromBuffer(MB.getBufferStart(),
320                                       MB.getBufferSize(),
321                                       llvm::TargetOptions(), Err));
322   if (!Err.empty())
323     error(Err);
324 
325   llvm::StringSaver Saver(Alloc);
326   for (unsigned I = 0, E = M->getSymbolCount(); I != E; ++I) {
327     lto_symbol_attributes Attrs = M->getSymbolAttributes(I);
328     if ((Attrs & LTO_SYMBOL_SCOPE_MASK) == LTO_SYMBOL_SCOPE_INTERNAL)
329       continue;
330 
331     StringRef SymName = Saver.save(M->getSymbolName(I));
332     int SymbolDef = Attrs & LTO_SYMBOL_DEFINITION_MASK;
333     if (SymbolDef == LTO_SYMBOL_DEFINITION_UNDEFINED) {
334       SymbolBodies.push_back(new (Alloc) Undefined(SymName));
335     } else {
336       bool Replaceable =
337           (SymbolDef == LTO_SYMBOL_DEFINITION_TENTATIVE || // common
338            (Attrs & LTO_SYMBOL_COMDAT) ||                  // comdat
339            (SymbolDef == LTO_SYMBOL_DEFINITION_WEAK &&     // weak external
340             (Attrs & LTO_SYMBOL_ALIAS)));
341       SymbolBodies.push_back(new (Alloc) DefinedBitcode(this, SymName,
342                                                         Replaceable));
343     }
344   }
345 
346   Directives = M->getLinkerOpts();
347 }
348 
349 MachineTypes BitcodeFile::getMachineType() {
350   if (!M)
351     return IMAGE_FILE_MACHINE_UNKNOWN;
352   switch (Triple(M->getTargetTriple()).getArch()) {
353   case Triple::x86_64:
354     return AMD64;
355   case Triple::x86:
356     return I386;
357   case Triple::arm:
358     return ARMNT;
359   default:
360     return IMAGE_FILE_MACHINE_UNKNOWN;
361   }
362 }
363 
364 std::mutex BitcodeFile::Mu;
365 
366 } // namespace coff
367 } // namespace lld
368