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::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 std::error_code ArchiveFile::parse() {
54   // Parse a MemoryBufferRef as an archive file.
55   auto ArchiveOrErr = Archive::create(MB);
56   if (auto EC = ArchiveOrErr.getError())
57     return EC;
58   File = std::move(ArchiveOrErr.get());
59 
60   // Allocate a buffer for Lazy objects.
61   size_t NumSyms = File->getNumberOfSymbols();
62   size_t BufSize = NumSyms * sizeof(Lazy);
63   Lazy *Buf = (Lazy *)Alloc.Allocate(BufSize, llvm::alignOf<Lazy>());
64   LazySymbols.reserve(NumSyms);
65 
66   // Read the symbol table to construct Lazy objects.
67   uint32_t I = 0;
68   for (const Archive::Symbol &Sym : File->symbols()) {
69     auto *B = new (&Buf[I++]) Lazy(this, Sym);
70     // Skip special symbol exists in import library files.
71     if (B->getName() != "__NULL_IMPORT_DESCRIPTOR")
72       LazySymbols.push_back(B);
73   }
74   return std::error_code();
75 }
76 
77 // Returns a buffer pointing to a member file containing a given symbol.
78 // This function is thread-safe.
79 ErrorOr<MemoryBufferRef> ArchiveFile::getMember(const Archive::Symbol *Sym) {
80   auto ItOrErr = Sym->getMember();
81   if (auto EC = ItOrErr.getError())
82     return EC;
83   Archive::child_iterator It = ItOrErr.get();
84 
85   // Return an empty buffer if we have already returned the same buffer.
86   const char *StartAddr = It->getBuffer().data();
87   auto Pair = Seen.insert(StartAddr);
88   if (!Pair.second)
89     return MemoryBufferRef();
90   return It->getMemoryBufferRef();
91 }
92 
93 std::error_code ObjectFile::parse() {
94   // Parse a memory buffer as a COFF file.
95   auto BinOrErr = createBinary(MB);
96   if (auto EC = BinOrErr.getError())
97     return EC;
98   std::unique_ptr<Binary> Bin = std::move(BinOrErr.get());
99 
100   if (auto *Obj = dyn_cast<COFFObjectFile>(Bin.get())) {
101     Bin.release();
102     COFFObj.reset(Obj);
103   } else {
104     llvm::errs() << getName() << " is not a COFF file.\n";
105     return make_error_code(LLDError::InvalidFile);
106   }
107 
108   // Read section and symbol tables.
109   if (auto EC = initializeChunks())
110     return EC;
111   return initializeSymbols();
112 }
113 
114 std::error_code 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     if (auto EC = COFFObj->getSection(I, Sec)) {
122       llvm::errs() << "getSection failed: " << Name << ": "
123                    << EC.message() << "\n";
124       return make_error_code(LLDError::BrokenFile);
125     }
126     if (auto EC = COFFObj->getSectionName(Sec, Name)) {
127       llvm::errs() << "getSectionName failed: " << Name << ": "
128                    << EC.message() << "\n";
129       return make_error_code(LLDError::BrokenFile);
130     }
131     if (Name == ".drectve") {
132       ArrayRef<uint8_t> Data;
133       COFFObj->getSectionContents(Sec, Data);
134       Directives = std::string((const char *)Data.data(), Data.size());
135       continue;
136     }
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   return std::error_code();
147 }
148 
149 std::error_code ObjectFile::initializeSymbols() {
150   uint32_t NumSymbols = COFFObj->getNumberOfSymbols();
151   SymbolBodies.reserve(NumSymbols);
152   SparseSymbolBodies.resize(NumSymbols);
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     if (auto EC = SymOrErr.getError()) {
158       llvm::errs() << "broken object file: " << getName() << ": "
159                    << EC.message() << "\n";
160       return make_error_code(LLDError::BrokenFile);
161     }
162     COFFSymbolRef Sym = SymOrErr.get();
163 
164     const void *AuxP = nullptr;
165     if (Sym.getNumberOfAuxSymbols())
166       AuxP = COFFObj->getSymbol(I + 1)->getRawPtr();
167     bool IsFirst = (LastSectionNumber != Sym.getSectionNumber());
168 
169     SymbolBody *Body = nullptr;
170     if (Sym.isUndefined()) {
171       Body = createUndefined(Sym);
172     } else if (Sym.isWeakExternal()) {
173       Body = createWeakExternal(Sym, AuxP);
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   return std::error_code();
185 }
186 
187 Undefined *ObjectFile::createUndefined(COFFSymbolRef Sym) {
188   StringRef Name;
189   COFFObj->getSymbolName(Sym, Name);
190   return new (Alloc) Undefined(Name);
191 }
192 
193 Undefined *ObjectFile::createWeakExternal(COFFSymbolRef Sym, const void *AuxP) {
194   StringRef Name;
195   COFFObj->getSymbolName(Sym, Name);
196   auto *U = new (Alloc) Undefined(Name);
197   auto *Aux = (const coff_aux_weak_external *)AuxP;
198   U->WeakAlias = SparseSymbolBodies[Aux->TagIndex];
199   return U;
200 }
201 
202 Defined *ObjectFile::createDefined(COFFSymbolRef Sym, const void *AuxP,
203                                    bool IsFirst) {
204   StringRef Name;
205   if (Sym.isCommon()) {
206     auto *C = new (Alloc) CommonChunk(Sym);
207     Chunks.push_back(C);
208     return new (Alloc) DefinedCommon(this, Sym, C);
209   }
210   if (Sym.isAbsolute()) {
211     COFFObj->getSymbolName(Sym, Name);
212     // Skip special symbols.
213     if (Name == "@comp.id" || Name == "@feat.00")
214       return nullptr;
215     return new (Alloc) DefinedAbsolute(Name, Sym);
216   }
217   if (Sym.getSectionNumber() == llvm::COFF::IMAGE_SYM_DEBUG)
218     return nullptr;
219 
220   // Nothing else to do without a section chunk.
221   auto *SC = cast_or_null<SectionChunk>(SparseChunks[Sym.getSectionNumber()]);
222   if (!SC)
223     return nullptr;
224 
225   // Handle associative sections
226   if (IsFirst && AuxP) {
227     auto *Aux = reinterpret_cast<const coff_aux_section_definition *>(AuxP);
228     if (Aux->Selection == IMAGE_COMDAT_SELECT_ASSOCIATIVE)
229       if (auto *ParentSC = cast_or_null<SectionChunk>(
230               SparseChunks[Aux->getNumber(Sym.isBigObj())]))
231         ParentSC->addAssociative(SC);
232   }
233 
234   auto *B = new (Alloc) DefinedRegular(this, Sym, SC);
235   if (SC->isCOMDAT() && Sym.getValue() == 0 && !AuxP)
236     SC->setSymbol(B);
237 
238   return B;
239 }
240 
241 MachineTypes ObjectFile::getMachineType() {
242   if (COFFObj)
243     return static_cast<MachineTypes>(COFFObj->getMachine());
244   return IMAGE_FILE_MACHINE_UNKNOWN;
245 }
246 
247 StringRef ltrim1(StringRef S, const char *Chars) {
248   if (!S.empty() && strchr(Chars, S[0]))
249     return S.substr(1);
250   return S;
251 }
252 
253 std::error_code ImportFile::parse() {
254   const char *Buf = MB.getBufferStart();
255   const char *End = MB.getBufferEnd();
256   const auto *Hdr = reinterpret_cast<const coff_import_header *>(Buf);
257 
258   // Check if the total size is valid.
259   if ((size_t)(End - Buf) != (sizeof(*Hdr) + Hdr->SizeOfData)) {
260     llvm::errs() << "broken import library\n";
261     return make_error_code(LLDError::BrokenFile);
262   }
263 
264   // Read names and create an __imp_ symbol.
265   StringRef Name = StringAlloc.save(StringRef(Buf + sizeof(*Hdr)));
266   StringRef ImpName = StringAlloc.save(Twine("__imp_") + Name);
267   StringRef DLLName(Buf + sizeof(coff_import_header) + Name.size() + 1);
268   StringRef ExtName;
269   switch (Hdr->getNameType()) {
270   case IMPORT_ORDINAL:
271     ExtName = "";
272     break;
273   case IMPORT_NAME:
274     ExtName = Name;
275     break;
276   case IMPORT_NAME_NOPREFIX:
277     ExtName = ltrim1(Name, "?@_");
278     break;
279   case IMPORT_NAME_UNDECORATE:
280     ExtName = ltrim1(Name, "?@_");
281     ExtName = ExtName.substr(0, ExtName.find('@'));
282     break;
283   }
284   auto *ImpSym = new (Alloc) DefinedImportData(DLLName, ImpName, ExtName, Hdr);
285   SymbolBodies.push_back(ImpSym);
286 
287   // If type is function, we need to create a thunk which jump to an
288   // address pointed by the __imp_ symbol. (This allows you to call
289   // DLL functions just like regular non-DLL functions.)
290   if (Hdr->getType() == llvm::COFF::IMPORT_CODE)
291     SymbolBodies.push_back(new (Alloc) DefinedImportThunk(Name, ImpSym));
292   return std::error_code();
293 }
294 
295 std::error_code BitcodeFile::parse() {
296   std::string Err;
297   M.reset(LTOModule::createFromBuffer(MB.getBufferStart(),
298                                       MB.getBufferSize(),
299                                       llvm::TargetOptions(), Err));
300   if (!Err.empty()) {
301     llvm::errs() << Err << '\n';
302     return make_error_code(LLDError::BrokenFile);
303   }
304 
305   llvm::BumpPtrStringSaver Saver(Alloc);
306   for (unsigned I = 0, E = M->getSymbolCount(); I != E; ++I) {
307     lto_symbol_attributes Attrs = M->getSymbolAttributes(I);
308     if ((Attrs & LTO_SYMBOL_SCOPE_MASK) == LTO_SYMBOL_SCOPE_INTERNAL)
309       continue;
310 
311     StringRef SymName = Saver.save(M->getSymbolName(I));
312     int SymbolDef = Attrs & LTO_SYMBOL_DEFINITION_MASK;
313     if (SymbolDef == LTO_SYMBOL_DEFINITION_UNDEFINED) {
314       SymbolBodies.push_back(new (Alloc) Undefined(SymName));
315     } else {
316       bool Replaceable =
317           (SymbolDef == LTO_SYMBOL_DEFINITION_TENTATIVE || // common
318            (Attrs & LTO_SYMBOL_COMDAT) ||                  // comdat
319            (SymbolDef == LTO_SYMBOL_DEFINITION_WEAK &&     // weak external
320             (Attrs & LTO_SYMBOL_ALIAS)));
321       SymbolBodies.push_back(new (Alloc) DefinedBitcode(this, SymName,
322                                                         Replaceable));
323     }
324   }
325 
326   Directives = M->getLinkerOpts();
327   return std::error_code();
328 }
329 
330 MachineTypes BitcodeFile::getMachineType() {
331   if (!M)
332     return IMAGE_FILE_MACHINE_UNKNOWN;
333   switch (Triple(M->getTargetTriple()).getArch()) {
334   case Triple::x86_64:
335     return IMAGE_FILE_MACHINE_AMD64;
336   case Triple::x86:
337     return IMAGE_FILE_MACHINE_I386;
338   case Triple::arm:
339     return IMAGE_FILE_MACHINE_ARMNT;
340   default:
341     return IMAGE_FILE_MACHINE_UNKNOWN;
342   }
343 }
344 
345 } // namespace coff
346 } // namespace lld
347