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