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.getChildOffset()].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   if (Seen[It->getChildOffset()].test_and_set())
93     return MemoryBufferRef();
94   return It->getMemoryBufferRef();
95 }
96 
97 std::error_code ObjectFile::parse() {
98   // Parse a memory buffer as a COFF file.
99   auto BinOrErr = createBinary(MB);
100   if (auto EC = BinOrErr.getError())
101     return EC;
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     llvm::errs() << getName() << " is not a COFF file.\n";
109     return make_error_code(LLDError::InvalidFile);
110   }
111 
112   // Read section and symbol tables.
113   if (auto EC = initializeChunks())
114     return EC;
115   return initializeSymbols();
116 }
117 
118 std::error_code ObjectFile::initializeChunks() {
119   uint32_t NumSections = COFFObj->getNumberOfSections();
120   Chunks.reserve(NumSections);
121   SparseChunks.resize(NumSections + 1);
122   for (uint32_t I = 1; I < NumSections + 1; ++I) {
123     const coff_section *Sec;
124     StringRef Name;
125     if (auto EC = COFFObj->getSection(I, Sec)) {
126       llvm::errs() << "getSection failed: " << Name << ": "
127                    << EC.message() << "\n";
128       return make_error_code(LLDError::BrokenFile);
129     }
130     if (auto EC = COFFObj->getSectionName(Sec, Name)) {
131       llvm::errs() << "getSectionName failed: " << Name << ": "
132                    << EC.message() << "\n";
133       return make_error_code(LLDError::BrokenFile);
134     }
135     if (Name == ".drectve") {
136       ArrayRef<uint8_t> Data;
137       COFFObj->getSectionContents(Sec, Data);
138       Directives = std::string((const char *)Data.data(), Data.size());
139       continue;
140     }
141     // We want to preserve DWARF debug sections only when /debug is on.
142     if (!Config->Debug && Name.startswith(".debug"))
143       continue;
144     if (Sec->Characteristics & llvm::COFF::IMAGE_SCN_LNK_REMOVE)
145       continue;
146     auto *C = new (Alloc) SectionChunk(this, Sec);
147     Chunks.push_back(C);
148     SparseChunks[I] = C;
149   }
150   return std::error_code();
151 }
152 
153 std::error_code 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     if (auto EC = SymOrErr.getError()) {
162       llvm::errs() << "broken object file: " << getName() << ": "
163                    << EC.message() << "\n";
164       return make_error_code(LLDError::BrokenFile);
165     }
166     COFFSymbolRef Sym = SymOrErr.get();
167 
168     const void *AuxP = nullptr;
169     if (Sym.getNumberOfAuxSymbols())
170       AuxP = COFFObj->getSymbol(I + 1)->getRawPtr();
171     bool IsFirst = (LastSectionNumber != Sym.getSectionNumber());
172 
173     SymbolBody *Body = nullptr;
174     if (Sym.isUndefined()) {
175       Body = createUndefined(Sym);
176     } else if (Sym.isWeakExternal()) {
177       Body = createWeakExternal(Sym, AuxP);
178     } else {
179       Body = createDefined(Sym, AuxP, IsFirst);
180     }
181     if (Body) {
182       SymbolBodies.push_back(Body);
183       SparseSymbolBodies[I] = Body;
184     }
185     I += Sym.getNumberOfAuxSymbols();
186     LastSectionNumber = Sym.getSectionNumber();
187   }
188   return std::error_code();
189 }
190 
191 Undefined *ObjectFile::createUndefined(COFFSymbolRef Sym) {
192   StringRef Name;
193   COFFObj->getSymbolName(Sym, Name);
194   return new (Alloc) Undefined(Name);
195 }
196 
197 Undefined *ObjectFile::createWeakExternal(COFFSymbolRef Sym, const void *AuxP) {
198   StringRef Name;
199   COFFObj->getSymbolName(Sym, Name);
200   auto *U = new (Alloc) Undefined(Name);
201   auto *Aux = (const coff_aux_weak_external *)AuxP;
202   U->WeakAlias = SparseSymbolBodies[Aux->TagIndex];
203   return U;
204 }
205 
206 Defined *ObjectFile::createDefined(COFFSymbolRef Sym, const void *AuxP,
207                                    bool IsFirst) {
208   StringRef Name;
209   if (Sym.isCommon()) {
210     auto *C = new (Alloc) CommonChunk(Sym);
211     Chunks.push_back(C);
212     return new (Alloc) DefinedCommon(this, Sym, C);
213   }
214   if (Sym.isAbsolute()) {
215     COFFObj->getSymbolName(Sym, Name);
216     // Skip special symbols.
217     if (Name == "@comp.id" || Name == "@feat.00")
218       return nullptr;
219     return new (Alloc) DefinedAbsolute(Name, Sym);
220   }
221   if (Sym.getSectionNumber() == llvm::COFF::IMAGE_SYM_DEBUG)
222     return nullptr;
223 
224   // Nothing else to do without a section chunk.
225   auto *SC = cast_or_null<SectionChunk>(SparseChunks[Sym.getSectionNumber()]);
226   if (!SC)
227     return nullptr;
228 
229   // Handle associative sections
230   if (IsFirst && AuxP) {
231     auto *Aux = reinterpret_cast<const coff_aux_section_definition *>(AuxP);
232     if (Aux->Selection == IMAGE_COMDAT_SELECT_ASSOCIATIVE)
233       if (auto *ParentSC = cast_or_null<SectionChunk>(
234               SparseChunks[Aux->getNumber(Sym.isBigObj())]))
235         ParentSC->addAssociative(SC);
236   }
237 
238   auto *B = new (Alloc) DefinedRegular(this, Sym, SC);
239   if (SC->isCOMDAT() && Sym.getValue() == 0 && !AuxP)
240     SC->setSymbol(B);
241 
242   return B;
243 }
244 
245 MachineTypes ObjectFile::getMachineType() {
246   if (COFFObj)
247     return static_cast<MachineTypes>(COFFObj->getMachine());
248   return IMAGE_FILE_MACHINE_UNKNOWN;
249 }
250 
251 StringRef ltrim1(StringRef S, const char *Chars) {
252   if (!S.empty() && strchr(Chars, S[0]))
253     return S.substr(1);
254   return S;
255 }
256 
257 std::error_code ImportFile::parse() {
258   const char *Buf = MB.getBufferStart();
259   const char *End = MB.getBufferEnd();
260   const auto *Hdr = reinterpret_cast<const coff_import_header *>(Buf);
261 
262   // Check if the total size is valid.
263   if ((size_t)(End - Buf) != (sizeof(*Hdr) + Hdr->SizeOfData)) {
264     llvm::errs() << "broken import library\n";
265     return make_error_code(LLDError::BrokenFile);
266   }
267 
268   // Read names and create an __imp_ symbol.
269   StringRef Name = StringAlloc.save(StringRef(Buf + sizeof(*Hdr)));
270   StringRef ImpName = StringAlloc.save(Twine("__imp_") + Name);
271   StringRef DLLName(Buf + sizeof(coff_import_header) + Name.size() + 1);
272   StringRef ExtName;
273   switch (Hdr->getNameType()) {
274   case IMPORT_ORDINAL:
275     ExtName = "";
276     break;
277   case IMPORT_NAME:
278     ExtName = Name;
279     break;
280   case IMPORT_NAME_NOPREFIX:
281     ExtName = ltrim1(Name, "?@_");
282     break;
283   case IMPORT_NAME_UNDECORATE:
284     ExtName = ltrim1(Name, "?@_");
285     ExtName = ExtName.substr(0, ExtName.find('@'));
286     break;
287   }
288   auto *ImpSym = new (Alloc) DefinedImportData(DLLName, ImpName, ExtName, Hdr);
289   SymbolBodies.push_back(ImpSym);
290 
291   // If type is function, we need to create a thunk which jump to an
292   // address pointed by the __imp_ symbol. (This allows you to call
293   // DLL functions just like regular non-DLL functions.)
294   if (Hdr->getType() == llvm::COFF::IMPORT_CODE)
295     SymbolBodies.push_back(new (Alloc) DefinedImportThunk(Name, ImpSym));
296   return std::error_code();
297 }
298 
299 std::error_code BitcodeFile::parse() {
300   std::string Err;
301   M.reset(LTOModule::createFromBuffer(MB.getBufferStart(),
302                                       MB.getBufferSize(),
303                                       llvm::TargetOptions(), Err));
304   if (!Err.empty()) {
305     llvm::errs() << Err << '\n';
306     return make_error_code(LLDError::BrokenFile);
307   }
308 
309   llvm::BumpPtrStringSaver Saver(Alloc);
310   for (unsigned I = 0, E = M->getSymbolCount(); I != E; ++I) {
311     lto_symbol_attributes Attrs = M->getSymbolAttributes(I);
312     if ((Attrs & LTO_SYMBOL_SCOPE_MASK) == LTO_SYMBOL_SCOPE_INTERNAL)
313       continue;
314 
315     StringRef SymName = Saver.save(M->getSymbolName(I));
316     int SymbolDef = Attrs & LTO_SYMBOL_DEFINITION_MASK;
317     if (SymbolDef == LTO_SYMBOL_DEFINITION_UNDEFINED) {
318       SymbolBodies.push_back(new (Alloc) Undefined(SymName));
319     } else {
320       bool Replaceable =
321           (SymbolDef == LTO_SYMBOL_DEFINITION_TENTATIVE || // common
322            (Attrs & LTO_SYMBOL_COMDAT) ||                  // comdat
323            (SymbolDef == LTO_SYMBOL_DEFINITION_WEAK &&     // weak external
324             (Attrs & LTO_SYMBOL_ALIAS)));
325       SymbolBodies.push_back(new (Alloc) DefinedBitcode(this, SymName,
326                                                         Replaceable));
327     }
328   }
329 
330   Directives = M->getLinkerOpts();
331   return std::error_code();
332 }
333 
334 MachineTypes BitcodeFile::getMachineType() {
335   if (!M)
336     return IMAGE_FILE_MACHINE_UNKNOWN;
337   switch (Triple(M->getTargetTriple()).getArch()) {
338   case Triple::x86_64:
339     return IMAGE_FILE_MACHINE_AMD64;
340   case Triple::x86:
341     return IMAGE_FILE_MACHINE_I386;
342   case Triple::arm:
343     return IMAGE_FILE_MACHINE_ARMNT;
344   default:
345     return IMAGE_FILE_MACHINE_UNKNOWN;
346   }
347 }
348 
349 } // namespace coff
350 } // namespace lld
351