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   if (!BinOrErr)
97     error(errorToErrorCode(BinOrErr.takeError()),
98                            "Failed to parse object file");
99   std::unique_ptr<Binary> Bin = std::move(*BinOrErr);
100 
101   if (auto *Obj = dyn_cast<COFFObjectFile>(Bin.get())) {
102     Bin.release();
103     COFFObj.reset(Obj);
104   } else {
105     error(Twine(getName()) + " is not a COFF file.");
106   }
107 
108   // Read section and symbol tables.
109   initializeChunks();
110   initializeSymbols();
111   initializeSEH();
112 }
113 
114 void ObjectFile::initializeChunks() {
115   uint32_t NumSections = COFFObj->getNumberOfSections();
116   Chunks.reserve(NumSections);
117   SparseChunks.resize(NumSections + 1);
118   for (uint32_t I = 1; I < NumSections + 1; ++I) {
119     const coff_section *Sec;
120     StringRef Name;
121     std::error_code EC = COFFObj->getSection(I, Sec);
122     error(EC, Twine("getSection failed: #") + Twine(I));
123     EC = COFFObj->getSectionName(Sec, Name);
124     error(EC, Twine("getSectionName failed: #") + Twine(I));
125     if (Name == ".sxdata") {
126       SXData = Sec;
127       continue;
128     }
129     if (Name == ".drectve") {
130       ArrayRef<uint8_t> Data;
131       COFFObj->getSectionContents(Sec, Data);
132       Directives = std::string((const char *)Data.data(), Data.size());
133       continue;
134     }
135     // Skip non-DWARF debug info. MSVC linker converts the sections into
136     // a PDB file, but we don't support that.
137     if (Name == ".debug" || Name.startswith(".debug$"))
138       continue;
139     // We want to preserve DWARF debug sections only when /debug is on.
140     if (!Config->Debug && Name.startswith(".debug"))
141       continue;
142     if (Sec->Characteristics & llvm::COFF::IMAGE_SCN_LNK_REMOVE)
143       continue;
144     auto *C = new (Alloc) 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   llvm::SmallVector<std::pair<Undefined *, uint32_t>, 8> WeakAliases;
155   int32_t LastSectionNumber = 0;
156   for (uint32_t I = 0; I < NumSymbols; ++I) {
157     // Get a COFFSymbolRef object.
158     auto SymOrErr = COFFObj->getSymbol(I);
159     error(SymOrErr, Twine("broken object file: ") + getName());
160 
161     COFFSymbolRef Sym = *SymOrErr;
162 
163     const void *AuxP = nullptr;
164     if (Sym.getNumberOfAuxSymbols())
165       AuxP = COFFObj->getSymbol(I + 1)->getRawPtr();
166     bool IsFirst = (LastSectionNumber != Sym.getSectionNumber());
167 
168     SymbolBody *Body = nullptr;
169     if (Sym.isUndefined()) {
170       Body = createUndefined(Sym);
171     } else if (Sym.isWeakExternal()) {
172       Body = createUndefined(Sym);
173       uint32_t TagIndex =
174           static_cast<const coff_aux_weak_external *>(AuxP)->TagIndex;
175       WeakAliases.emplace_back((Undefined *)Body, TagIndex);
176     } else {
177       Body = createDefined(Sym, AuxP, IsFirst);
178     }
179     if (Body) {
180       SymbolBodies.push_back(Body);
181       SparseSymbolBodies[I] = Body;
182     }
183     I += Sym.getNumberOfAuxSymbols();
184     LastSectionNumber = Sym.getSectionNumber();
185   }
186   for (auto WeakAlias : WeakAliases)
187     WeakAlias.first->WeakAlias = SparseSymbolBodies[WeakAlias.second];
188 }
189 
190 Undefined *ObjectFile::createUndefined(COFFSymbolRef Sym) {
191   StringRef Name;
192   COFFObj->getSymbolName(Sym, Name);
193   return new (Alloc) Undefined(Name);
194 }
195 
196 Defined *ObjectFile::createDefined(COFFSymbolRef Sym, const void *AuxP,
197                                    bool IsFirst) {
198   StringRef Name;
199   if (Sym.isCommon()) {
200     auto *C = new (Alloc) CommonChunk(Sym);
201     Chunks.push_back(C);
202     return new (Alloc) DefinedCommon(this, Sym, C);
203   }
204   if (Sym.isAbsolute()) {
205     COFFObj->getSymbolName(Sym, Name);
206     // Skip special symbols.
207     if (Name == "@comp.id")
208       return nullptr;
209     // COFF spec 5.10.1. The .sxdata section.
210     if (Name == "@feat.00") {
211       if (Sym.getValue() & 1)
212         SEHCompat = true;
213       return nullptr;
214     }
215     return new (Alloc) DefinedAbsolute(Name, Sym);
216   }
217   int32_t SectionNumber = Sym.getSectionNumber();
218   if (SectionNumber == llvm::COFF::IMAGE_SYM_DEBUG)
219     return nullptr;
220 
221   // Reserved sections numbers don't have contents.
222   if (llvm::COFF::isReservedSectionNumber(SectionNumber))
223     error(Twine("broken object file: ") + getName());
224 
225   // This symbol references a section which is not present in the section
226   // header.
227   if ((uint32_t)SectionNumber >= SparseChunks.size())
228     error(Twine("broken object file: ") + getName());
229 
230   // Nothing else to do without a section chunk.
231   auto *SC = cast_or_null<SectionChunk>(SparseChunks[SectionNumber]);
232   if (!SC)
233     return nullptr;
234 
235   // Handle section definitions
236   if (IsFirst && AuxP) {
237     auto *Aux = reinterpret_cast<const coff_aux_section_definition *>(AuxP);
238     if (Aux->Selection == IMAGE_COMDAT_SELECT_ASSOCIATIVE)
239       if (auto *ParentSC = cast_or_null<SectionChunk>(
240               SparseChunks[Aux->getNumber(Sym.isBigObj())]))
241         ParentSC->addAssociative(SC);
242     SC->Checksum = Aux->CheckSum;
243   }
244 
245   auto *B = new (Alloc) DefinedRegular(this, Sym, SC);
246   if (SC->isCOMDAT() && Sym.getValue() == 0 && !AuxP)
247     SC->setSymbol(B);
248 
249   return B;
250 }
251 
252 void ObjectFile::initializeSEH() {
253   if (!SEHCompat || !SXData)
254     return;
255   ArrayRef<uint8_t> A;
256   COFFObj->getSectionContents(SXData, A);
257   if (A.size() % 4 != 0)
258     error(".sxdata must be an array of symbol table indices");
259   auto *I = reinterpret_cast<const ulittle32_t *>(A.data());
260   auto *E = reinterpret_cast<const ulittle32_t *>(A.data() + A.size());
261   for (; I != E; ++I)
262     SEHandlers.insert(SparseSymbolBodies[*I]);
263 }
264 
265 MachineTypes ObjectFile::getMachineType() {
266   if (COFFObj)
267     return static_cast<MachineTypes>(COFFObj->getMachine());
268   return IMAGE_FILE_MACHINE_UNKNOWN;
269 }
270 
271 StringRef ltrim1(StringRef S, const char *Chars) {
272   if (!S.empty() && strchr(Chars, S[0]))
273     return S.substr(1);
274   return S;
275 }
276 
277 void ImportFile::parse() {
278   const char *Buf = MB.getBufferStart();
279   const char *End = MB.getBufferEnd();
280   const auto *Hdr = reinterpret_cast<const coff_import_header *>(Buf);
281 
282   // Check if the total size is valid.
283   if ((size_t)(End - Buf) != (sizeof(*Hdr) + Hdr->SizeOfData))
284     error("broken import library");
285 
286   // Read names and create an __imp_ symbol.
287   StringRef Name = StringAlloc.save(StringRef(Buf + sizeof(*Hdr)));
288   StringRef ImpName = StringAlloc.save(Twine("__imp_") + Name);
289   const char *NameStart = Buf + sizeof(coff_import_header) + Name.size() + 1;
290   DLLName = StringRef(NameStart);
291   StringRef ExtName;
292   switch (Hdr->getNameType()) {
293   case IMPORT_ORDINAL:
294     ExtName = "";
295     break;
296   case IMPORT_NAME:
297     ExtName = Name;
298     break;
299   case IMPORT_NAME_NOPREFIX:
300     ExtName = ltrim1(Name, "?@_");
301     break;
302   case IMPORT_NAME_UNDECORATE:
303     ExtName = ltrim1(Name, "?@_");
304     ExtName = ExtName.substr(0, ExtName.find('@'));
305     break;
306   }
307   ImpSym = new (Alloc) DefinedImportData(DLLName, ImpName, ExtName, Hdr);
308   SymbolBodies.push_back(ImpSym);
309 
310   // If type is function, we need to create a thunk which jump to an
311   // address pointed by the __imp_ symbol. (This allows you to call
312   // DLL functions just like regular non-DLL functions.)
313   if (Hdr->getType() != llvm::COFF::IMPORT_CODE)
314     return;
315   ThunkSym = new (Alloc) DefinedImportThunk(Name, ImpSym, Hdr->Machine);
316   SymbolBodies.push_back(ThunkSym);
317 }
318 
319 void BitcodeFile::parse() {
320   // Usually parse() is thread-safe, but bitcode file is an exception.
321   std::lock_guard<std::mutex> Lock(Mu);
322 
323   ErrorOr<std::unique_ptr<LTOModule>> ModOrErr =
324       LTOModule::createFromBuffer(llvm::getGlobalContext(), MB.getBufferStart(),
325                                   MB.getBufferSize(), llvm::TargetOptions());
326   error(ModOrErr, "Could not create lto module");
327   M = std::move(*ModOrErr);
328 
329   llvm::StringSaver Saver(Alloc);
330   for (unsigned I = 0, E = M->getSymbolCount(); I != E; ++I) {
331     lto_symbol_attributes Attrs = M->getSymbolAttributes(I);
332     if ((Attrs & LTO_SYMBOL_SCOPE_MASK) == LTO_SYMBOL_SCOPE_INTERNAL)
333       continue;
334 
335     StringRef SymName = Saver.save(M->getSymbolName(I));
336     int SymbolDef = Attrs & LTO_SYMBOL_DEFINITION_MASK;
337     if (SymbolDef == LTO_SYMBOL_DEFINITION_UNDEFINED) {
338       SymbolBodies.push_back(new (Alloc) Undefined(SymName));
339     } else {
340       bool Replaceable =
341           (SymbolDef == LTO_SYMBOL_DEFINITION_TENTATIVE || // common
342            (Attrs & LTO_SYMBOL_COMDAT) ||                  // comdat
343            (SymbolDef == LTO_SYMBOL_DEFINITION_WEAK &&     // weak external
344             (Attrs & LTO_SYMBOL_ALIAS)));
345       SymbolBodies.push_back(new (Alloc) DefinedBitcode(this, SymName,
346                                                         Replaceable));
347     }
348   }
349 
350   Directives = M->getLinkerOpts();
351 }
352 
353 MachineTypes BitcodeFile::getMachineType() {
354   if (!M)
355     return IMAGE_FILE_MACHINE_UNKNOWN;
356   switch (Triple(M->getTargetTriple()).getArch()) {
357   case Triple::x86_64:
358     return AMD64;
359   case Triple::x86:
360     return I386;
361   case Triple::arm:
362     return ARMNT;
363   default:
364     return IMAGE_FILE_MACHINE_UNKNOWN;
365   }
366 }
367 
368 std::mutex BitcodeFile::Mu;
369 
370 } // namespace coff
371 } // namespace lld
372