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.get());
58 
59   // Allocate a buffer for Lazy objects.
60   size_t NumSyms = File->getNumberOfSymbols();
61   size_t BufSize = NumSyms * sizeof(Lazy);
62   Lazy *Buf = (Lazy *)Alloc.Allocate(BufSize, llvm::alignOf<Lazy>());
63   LazySymbols.reserve(NumSyms);
64 
65   // Read the symbol table to construct Lazy objects.
66   uint32_t I = 0;
67   for (const Archive::Symbol &Sym : File->symbols()) {
68     auto *B = new (&Buf[I++]) Lazy(this, Sym);
69     // Skip special symbol exists in import library files.
70     if (B->getName() != "__NULL_IMPORT_DESCRIPTOR")
71       LazySymbols.push_back(B);
72   }
73 
74   // Seen is a map from member files to boolean values. Initially
75   // all members are mapped to false, which indicates all these files
76   // are not read yet.
77   for (const Archive::Child &Child : File->children())
78     Seen[Child.getChildOffset()].clear();
79 }
80 
81 // Returns a buffer pointing to a member file containing a given symbol.
82 // This function is thread-safe.
83 MemoryBufferRef ArchiveFile::getMember(const Archive::Symbol *Sym) {
84   auto ItOrErr = Sym->getMember();
85   error(ItOrErr,
86         Twine("Could not get the member for symbol ") + Sym->getName());
87   Archive::child_iterator It = ItOrErr.get();
88 
89   // Return an empty buffer if we have already returned the same buffer.
90   if (Seen[It->getChildOffset()].test_and_set())
91     return MemoryBufferRef();
92   ErrorOr<MemoryBufferRef> Ret = It->getMemoryBufferRef();
93   error(Ret, Twine("Could not get the buffer for the member defining symbol ") +
94                  Sym->getName());
95   return *Ret;
96 }
97 
98 void ObjectFile::parse() {
99   // Parse a memory buffer as a COFF file.
100   auto BinOrErr = createBinary(MB);
101   error(BinOrErr, "Failed to parse object file");
102   std::unique_ptr<Binary> Bin = std::move(BinOrErr.get());
103 
104   if (auto *Obj = dyn_cast<COFFObjectFile>(Bin.get())) {
105     Bin.release();
106     COFFObj.reset(Obj);
107   } else {
108     error(Twine(getName()) + " is not a COFF file.");
109   }
110 
111   // Read section and symbol tables.
112   initializeChunks();
113   initializeSymbols();
114   initializeSEH();
115 }
116 
117 void ObjectFile::initializeChunks() {
118   uint32_t NumSections = COFFObj->getNumberOfSections();
119   Chunks.reserve(NumSections);
120   SparseChunks.resize(NumSections + 1);
121   for (uint32_t I = 1; I < NumSections + 1; ++I) {
122     const coff_section *Sec;
123     StringRef Name;
124     std::error_code EC = COFFObj->getSection(I, Sec);
125     error(EC, Twine("getSection failed: ") + Name);
126     EC = COFFObj->getSectionName(Sec, Name);
127     error(EC, Twine("getSectionName failed: ") + Name);
128     if (Name == ".sxdata") {
129       SXData = Sec;
130       continue;
131     }
132     if (Name == ".drectve") {
133       ArrayRef<uint8_t> Data;
134       COFFObj->getSectionContents(Sec, Data);
135       Directives = std::string((const char *)Data.data(), Data.size());
136       continue;
137     }
138     // Skip non-DWARF debug info. MSVC linker converts the sections into
139     // a PDB file, but we don't support that.
140     if (Name == ".debug" || Name.startswith(".debug$"))
141       continue;
142     // We want to preserve DWARF debug sections only when /debug is on.
143     if (!Config->Debug && Name.startswith(".debug"))
144       continue;
145     if (Sec->Characteristics & llvm::COFF::IMAGE_SCN_LNK_REMOVE)
146       continue;
147     auto *C = new (Alloc) SectionChunk(this, Sec);
148     Chunks.push_back(C);
149     SparseChunks[I] = C;
150   }
151 }
152 
153 void ObjectFile::initializeSymbols() {
154   uint32_t NumSymbols = COFFObj->getNumberOfSymbols();
155   SymbolBodies.reserve(NumSymbols);
156   SparseSymbolBodies.resize(NumSymbols);
157   int32_t LastSectionNumber = 0;
158   for (uint32_t I = 0; I < NumSymbols; ++I) {
159     // Get a COFFSymbolRef object.
160     auto SymOrErr = COFFObj->getSymbol(I);
161     error(SymOrErr, Twine("broken object file: ") + getName());
162 
163     COFFSymbolRef Sym = SymOrErr.get();
164 
165     const void *AuxP = nullptr;
166     if (Sym.getNumberOfAuxSymbols())
167       AuxP = COFFObj->getSymbol(I + 1)->getRawPtr();
168     bool IsFirst = (LastSectionNumber != Sym.getSectionNumber());
169 
170     SymbolBody *Body = nullptr;
171     if (Sym.isUndefined()) {
172       Body = createUndefined(Sym);
173     } else if (Sym.isWeakExternal()) {
174       Body = createWeakExternal(Sym, AuxP);
175     } else {
176       Body = createDefined(Sym, AuxP, IsFirst);
177     }
178     if (Body) {
179       SymbolBodies.push_back(Body);
180       SparseSymbolBodies[I] = Body;
181     }
182     I += Sym.getNumberOfAuxSymbols();
183     LastSectionNumber = Sym.getSectionNumber();
184   }
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")
214       return nullptr;
215     // COFF spec 5.10.1. The .sxdata section.
216     if (Name == "@feat.00") {
217       if (Sym.getValue() & 1)
218         SEHCompat = true;
219       return nullptr;
220     }
221     return new (Alloc) DefinedAbsolute(Name, Sym);
222   }
223   if (Sym.getSectionNumber() == llvm::COFF::IMAGE_SYM_DEBUG)
224     return nullptr;
225 
226   // Nothing else to do without a section chunk.
227   auto *SC = cast_or_null<SectionChunk>(SparseChunks[Sym.getSectionNumber()]);
228   if (!SC)
229     return nullptr;
230 
231   // Handle associative sections
232   if (IsFirst && AuxP) {
233     auto *Aux = reinterpret_cast<const coff_aux_section_definition *>(AuxP);
234     if (Aux->Selection == IMAGE_COMDAT_SELECT_ASSOCIATIVE)
235       if (auto *ParentSC = cast_or_null<SectionChunk>(
236               SparseChunks[Aux->getNumber(Sym.isBigObj())]))
237         ParentSC->addAssociative(SC);
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   StringRef DLLName(Buf + sizeof(coff_import_header) + Name.size() + 1);
285   StringRef ExtName;
286   switch (Hdr->getNameType()) {
287   case IMPORT_ORDINAL:
288     ExtName = "";
289     break;
290   case IMPORT_NAME:
291     ExtName = Name;
292     break;
293   case IMPORT_NAME_NOPREFIX:
294     ExtName = ltrim1(Name, "?@_");
295     break;
296   case IMPORT_NAME_UNDECORATE:
297     ExtName = ltrim1(Name, "?@_");
298     ExtName = ExtName.substr(0, ExtName.find('@'));
299     break;
300   }
301   auto *ImpSym = new (Alloc) DefinedImportData(DLLName, ImpName, ExtName, Hdr);
302   SymbolBodies.push_back(ImpSym);
303 
304   // If type is function, we need to create a thunk which jump to an
305   // address pointed by the __imp_ symbol. (This allows you to call
306   // DLL functions just like regular non-DLL functions.)
307   if (Hdr->getType() == llvm::COFF::IMPORT_CODE) {
308     auto *B = new (Alloc) DefinedImportThunk(Name, ImpSym, Hdr->Machine);
309     SymbolBodies.push_back(B);
310   }
311 }
312 
313 void BitcodeFile::parse() {
314   std::string Err;
315   M.reset(LTOModule::createFromBuffer(MB.getBufferStart(),
316                                       MB.getBufferSize(),
317                                       llvm::TargetOptions(), Err));
318   if (!Err.empty())
319     error(Err);
320 
321   llvm::StringSaver Saver(Alloc);
322   for (unsigned I = 0, E = M->getSymbolCount(); I != E; ++I) {
323     lto_symbol_attributes Attrs = M->getSymbolAttributes(I);
324     if ((Attrs & LTO_SYMBOL_SCOPE_MASK) == LTO_SYMBOL_SCOPE_INTERNAL)
325       continue;
326 
327     StringRef SymName = Saver.save(M->getSymbolName(I));
328     int SymbolDef = Attrs & LTO_SYMBOL_DEFINITION_MASK;
329     if (SymbolDef == LTO_SYMBOL_DEFINITION_UNDEFINED) {
330       SymbolBodies.push_back(new (Alloc) Undefined(SymName));
331     } else {
332       bool Replaceable =
333           (SymbolDef == LTO_SYMBOL_DEFINITION_TENTATIVE || // common
334            (Attrs & LTO_SYMBOL_COMDAT) ||                  // comdat
335            (SymbolDef == LTO_SYMBOL_DEFINITION_WEAK &&     // weak external
336             (Attrs & LTO_SYMBOL_ALIAS)));
337       SymbolBodies.push_back(new (Alloc) DefinedBitcode(this, SymName,
338                                                         Replaceable));
339     }
340   }
341 
342   Directives = M->getLinkerOpts();
343 }
344 
345 MachineTypes BitcodeFile::getMachineType() {
346   if (!M)
347     return IMAGE_FILE_MACHINE_UNKNOWN;
348   switch (Triple(M->getTargetTriple()).getArch()) {
349   case Triple::x86_64:
350     return AMD64;
351   case Triple::x86:
352     return I386;
353   case Triple::arm:
354     return ARMNT;
355   default:
356     return IMAGE_FILE_MACHINE_UNKNOWN;
357   }
358 }
359 
360 } // namespace coff
361 } // namespace lld
362