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