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 
75   // Seen is a map from member files to boolean values. Initially
76   // all members are mapped to false, which indicates all these files
77   // are not read yet.
78   for (const Archive::Child &Child : File->children())
79     Seen[Child.getBuffer().data()].clear();
80   return std::error_code();
81 }
82 
83 // Returns a buffer pointing to a member file containing a given symbol.
84 // This function is thread-safe.
85 ErrorOr<MemoryBufferRef> ArchiveFile::getMember(const Archive::Symbol *Sym) {
86   auto ItOrErr = Sym->getMember();
87   if (auto EC = ItOrErr.getError())
88     return EC;
89   Archive::child_iterator It = ItOrErr.get();
90 
91   // Return an empty buffer if we have already returned the same buffer.
92   const char *StartAddr = It->getBuffer().data();
93   if (Seen[StartAddr].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   return initializeSymbols();
117 }
118 
119 std::error_code 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       llvm::errs() << "getSection failed: " << Name << ": "
128                    << EC.message() << "\n";
129       return make_error_code(LLDError::BrokenFile);
130     }
131     if (auto EC = COFFObj->getSectionName(Sec, Name)) {
132       llvm::errs() << "getSectionName failed: " << Name << ": "
133                    << EC.message() << "\n";
134       return make_error_code(LLDError::BrokenFile);
135     }
136     if (Name == ".drectve") {
137       ArrayRef<uint8_t> Data;
138       COFFObj->getSectionContents(Sec, Data);
139       Directives = std::string((const char *)Data.data(), Data.size());
140       continue;
141     }
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   return std::error_code();
152 }
153 
154 std::error_code ObjectFile::initializeSymbols() {
155   uint32_t NumSymbols = COFFObj->getNumberOfSymbols();
156   SymbolBodies.reserve(NumSymbols);
157   SparseSymbolBodies.resize(NumSymbols);
158   int32_t LastSectionNumber = 0;
159   for (uint32_t I = 0; I < NumSymbols; ++I) {
160     // Get a COFFSymbolRef object.
161     auto SymOrErr = COFFObj->getSymbol(I);
162     if (auto EC = SymOrErr.getError()) {
163       llvm::errs() << "broken object file: " << getName() << ": "
164                    << EC.message() << "\n";
165       return make_error_code(LLDError::BrokenFile);
166     }
167     COFFSymbolRef Sym = SymOrErr.get();
168 
169     const void *AuxP = nullptr;
170     if (Sym.getNumberOfAuxSymbols())
171       AuxP = COFFObj->getSymbol(I + 1)->getRawPtr();
172     bool IsFirst = (LastSectionNumber != Sym.getSectionNumber());
173 
174     SymbolBody *Body = nullptr;
175     if (Sym.isUndefined()) {
176       Body = createUndefined(Sym);
177     } else if (Sym.isWeakExternal()) {
178       Body = createWeakExternal(Sym, AuxP);
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   return std::error_code();
190 }
191 
192 Undefined *ObjectFile::createUndefined(COFFSymbolRef Sym) {
193   StringRef Name;
194   COFFObj->getSymbolName(Sym, Name);
195   return new (Alloc) Undefined(Name);
196 }
197 
198 Undefined *ObjectFile::createWeakExternal(COFFSymbolRef Sym, const void *AuxP) {
199   StringRef Name;
200   COFFObj->getSymbolName(Sym, Name);
201   auto *U = new (Alloc) Undefined(Name);
202   auto *Aux = (const coff_aux_weak_external *)AuxP;
203   U->WeakAlias = SparseSymbolBodies[Aux->TagIndex];
204   return U;
205 }
206 
207 Defined *ObjectFile::createDefined(COFFSymbolRef Sym, const void *AuxP,
208                                    bool IsFirst) {
209   StringRef Name;
210   if (Sym.isCommon()) {
211     auto *C = new (Alloc) CommonChunk(Sym);
212     Chunks.push_back(C);
213     return new (Alloc) DefinedCommon(this, Sym, C);
214   }
215   if (Sym.isAbsolute()) {
216     COFFObj->getSymbolName(Sym, Name);
217     // Skip special symbols.
218     if (Name == "@comp.id" || Name == "@feat.00")
219       return nullptr;
220     return new (Alloc) DefinedAbsolute(Name, Sym);
221   }
222   if (Sym.getSectionNumber() == llvm::COFF::IMAGE_SYM_DEBUG)
223     return nullptr;
224 
225   // Nothing else to do without a section chunk.
226   auto *SC = cast_or_null<SectionChunk>(SparseChunks[Sym.getSectionNumber()]);
227   if (!SC)
228     return nullptr;
229 
230   // Handle associative sections
231   if (IsFirst && AuxP) {
232     auto *Aux = reinterpret_cast<const coff_aux_section_definition *>(AuxP);
233     if (Aux->Selection == IMAGE_COMDAT_SELECT_ASSOCIATIVE)
234       if (auto *ParentSC = cast_or_null<SectionChunk>(
235               SparseChunks[Aux->getNumber(Sym.isBigObj())]))
236         ParentSC->addAssociative(SC);
237   }
238 
239   auto *B = new (Alloc) DefinedRegular(this, Sym, SC);
240   if (SC->isCOMDAT() && Sym.getValue() == 0 && !AuxP)
241     SC->setSymbol(B);
242 
243   return B;
244 }
245 
246 MachineTypes ObjectFile::getMachineType() {
247   if (COFFObj)
248     return static_cast<MachineTypes>(COFFObj->getMachine());
249   return IMAGE_FILE_MACHINE_UNKNOWN;
250 }
251 
252 StringRef ltrim1(StringRef S, const char *Chars) {
253   if (!S.empty() && strchr(Chars, S[0]))
254     return S.substr(1);
255   return S;
256 }
257 
258 std::error_code ImportFile::parse() {
259   const char *Buf = MB.getBufferStart();
260   const char *End = MB.getBufferEnd();
261   const auto *Hdr = reinterpret_cast<const coff_import_header *>(Buf);
262 
263   // Check if the total size is valid.
264   if ((size_t)(End - Buf) != (sizeof(*Hdr) + Hdr->SizeOfData)) {
265     llvm::errs() << "broken import library\n";
266     return make_error_code(LLDError::BrokenFile);
267   }
268 
269   // Read names and create an __imp_ symbol.
270   StringRef Name = StringAlloc.save(StringRef(Buf + sizeof(*Hdr)));
271   StringRef ImpName = StringAlloc.save(Twine("__imp_") + Name);
272   StringRef DLLName(Buf + sizeof(coff_import_header) + Name.size() + 1);
273   StringRef ExtName;
274   switch (Hdr->getNameType()) {
275   case IMPORT_ORDINAL:
276     ExtName = "";
277     break;
278   case IMPORT_NAME:
279     ExtName = Name;
280     break;
281   case IMPORT_NAME_NOPREFIX:
282     ExtName = ltrim1(Name, "?@_");
283     break;
284   case IMPORT_NAME_UNDECORATE:
285     ExtName = ltrim1(Name, "?@_");
286     ExtName = ExtName.substr(0, ExtName.find('@'));
287     break;
288   }
289   auto *ImpSym = new (Alloc) DefinedImportData(DLLName, ImpName, ExtName, Hdr);
290   SymbolBodies.push_back(ImpSym);
291 
292   // If type is function, we need to create a thunk which jump to an
293   // address pointed by the __imp_ symbol. (This allows you to call
294   // DLL functions just like regular non-DLL functions.)
295   if (Hdr->getType() == llvm::COFF::IMPORT_CODE)
296     SymbolBodies.push_back(new (Alloc) DefinedImportThunk(Name, ImpSym));
297   return std::error_code();
298 }
299 
300 std::error_code BitcodeFile::parse() {
301   std::string Err;
302   M.reset(LTOModule::createFromBuffer(MB.getBufferStart(),
303                                       MB.getBufferSize(),
304                                       llvm::TargetOptions(), Err));
305   if (!Err.empty()) {
306     llvm::errs() << Err << '\n';
307     return make_error_code(LLDError::BrokenFile);
308   }
309 
310   llvm::BumpPtrStringSaver Saver(Alloc);
311   for (unsigned I = 0, E = M->getSymbolCount(); I != E; ++I) {
312     lto_symbol_attributes Attrs = M->getSymbolAttributes(I);
313     if ((Attrs & LTO_SYMBOL_SCOPE_MASK) == LTO_SYMBOL_SCOPE_INTERNAL)
314       continue;
315 
316     StringRef SymName = Saver.save(M->getSymbolName(I));
317     int SymbolDef = Attrs & LTO_SYMBOL_DEFINITION_MASK;
318     if (SymbolDef == LTO_SYMBOL_DEFINITION_UNDEFINED) {
319       SymbolBodies.push_back(new (Alloc) Undefined(SymName));
320     } else {
321       bool Replaceable =
322           (SymbolDef == LTO_SYMBOL_DEFINITION_TENTATIVE || // common
323            (Attrs & LTO_SYMBOL_COMDAT) ||                  // comdat
324            (SymbolDef == LTO_SYMBOL_DEFINITION_WEAK &&     // weak external
325             (Attrs & LTO_SYMBOL_ALIAS)));
326       SymbolBodies.push_back(new (Alloc) DefinedBitcode(this, SymName,
327                                                         Replaceable));
328     }
329   }
330 
331   Directives = M->getLinkerOpts();
332   return std::error_code();
333 }
334 
335 MachineTypes BitcodeFile::getMachineType() {
336   if (!M)
337     return IMAGE_FILE_MACHINE_UNKNOWN;
338   switch (Triple(M->getTargetTriple()).getArch()) {
339   case Triple::x86_64:
340     return IMAGE_FILE_MACHINE_AMD64;
341   case Triple::x86:
342     return IMAGE_FILE_MACHINE_I386;
343   case Triple::arm:
344     return IMAGE_FILE_MACHINE_ARMNT;
345   default:
346     return IMAGE_FILE_MACHINE_UNKNOWN;
347   }
348 }
349 
350 } // namespace coff
351 } // namespace lld
352