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