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 
22 using namespace llvm::object;
23 using namespace llvm::support::endian;
24 using llvm::COFF::ImportHeader;
25 using llvm::COFF::IMAGE_COMDAT_SELECT_ASSOCIATIVE;
26 using llvm::COFF::IMAGE_FILE_MACHINE_AMD64;
27 using llvm::COFF::IMAGE_FILE_MACHINE_UNKNOWN;
28 using llvm::RoundUpToAlignment;
29 using llvm::sys::fs::identify_magic;
30 using llvm::sys::fs::file_magic;
31 
32 namespace lld {
33 namespace coff {
34 
35 // Returns the last element of a path, which is supposed to be a filename.
36 static StringRef getBasename(StringRef Path) {
37   size_t Pos = Path.find_last_of("\\/");
38   if (Pos == StringRef::npos)
39     return Path;
40   return Path.substr(Pos + 1);
41 }
42 
43 // Returns a string in the format of "foo.obj" or "foo.obj(bar.lib)".
44 std::string InputFile::getShortName() {
45   if (ParentName == "")
46     return getName().lower();
47   std::string Res = (getBasename(ParentName) + "(" +
48                      getBasename(getName()) + ")").str();
49   return StringRef(Res).lower();
50 }
51 
52 std::error_code ArchiveFile::parse() {
53   // Parse a MemoryBufferRef as an archive file.
54   auto ArchiveOrErr = Archive::create(MB);
55   if (auto EC = ArchiveOrErr.getError())
56     return EC;
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   return std::error_code();
74 }
75 
76 // Returns a buffer pointing to a member file containing a given symbol.
77 ErrorOr<MemoryBufferRef> ArchiveFile::getMember(const Archive::Symbol *Sym) {
78   auto ItOrErr = Sym->getMember();
79   if (auto EC = ItOrErr.getError())
80     return EC;
81   Archive::child_iterator It = ItOrErr.get();
82 
83   // Return an empty buffer if we have already returned the same buffer.
84   const char *StartAddr = It->getBuffer().data();
85   auto Pair = Seen.insert(StartAddr);
86   if (!Pair.second)
87     return MemoryBufferRef();
88   return It->getMemoryBufferRef();
89 }
90 
91 std::error_code ObjectFile::parse() {
92   // Parse a memory buffer as a COFF file.
93   auto BinOrErr = createBinary(MB);
94   if (auto EC = BinOrErr.getError())
95     return EC;
96   std::unique_ptr<Binary> Bin = std::move(BinOrErr.get());
97 
98   if (auto *Obj = dyn_cast<COFFObjectFile>(Bin.get())) {
99     Bin.release();
100     COFFObj.reset(Obj);
101   } else {
102     llvm::errs() << getName() << " is not a COFF file.\n";
103     return make_error_code(LLDError::InvalidFile);
104   }
105   if (COFFObj->getMachine() != IMAGE_FILE_MACHINE_AMD64 &&
106       COFFObj->getMachine() != IMAGE_FILE_MACHINE_UNKNOWN) {
107     llvm::errs() << getName() << " is not an x64 object file.\n";
108     return make_error_code(LLDError::InvalidFile);
109   }
110 
111   // Read section and symbol tables.
112   if (auto EC = initializeChunks())
113     return EC;
114   return initializeSymbols();
115 }
116 
117 std::error_code 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     if (auto EC = COFFObj->getSection(I, Sec)) {
125       llvm::errs() << "getSection failed: " << Name << ": "
126                    << EC.message() << "\n";
127       return make_error_code(LLDError::BrokenFile);
128     }
129     if (auto EC = COFFObj->getSectionName(Sec, Name)) {
130       llvm::errs() << "getSectionName failed: " << Name << ": "
131                    << EC.message() << "\n";
132       return make_error_code(LLDError::BrokenFile);
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     if (Name.startswith(".debug"))
141       continue;
142     if (Sec->Characteristics & llvm::COFF::IMAGE_SCN_LNK_REMOVE)
143       continue;
144     auto *C = new (Alloc) SectionChunk(this, Sec);
145     Chunks.push_back(C);
146     SparseChunks[I] = C;
147   }
148   return std::error_code();
149 }
150 
151 std::error_code ObjectFile::initializeSymbols() {
152   uint32_t NumSymbols = COFFObj->getNumberOfSymbols();
153   SymbolBodies.reserve(NumSymbols);
154   SparseSymbolBodies.resize(NumSymbols);
155   int32_t LastSectionNumber = 0;
156   for (uint32_t I = 0; I < NumSymbols; ++I) {
157     // Get a COFFSymbolRef object.
158     auto SymOrErr = COFFObj->getSymbol(I);
159     if (auto EC = SymOrErr.getError()) {
160       llvm::errs() << "broken object file: " << getName() << ": "
161                    << EC.message() << "\n";
162       return make_error_code(LLDError::BrokenFile);
163     }
164     COFFSymbolRef Sym = SymOrErr.get();
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 = createWeakExternal(Sym, AuxP);
176     } else {
177       Body = createDefined(Sym, AuxP, IsFirst);
178     }
179     if (Body) {
180       SymbolBodies.push_back(Body);
181       SparseSymbolBodies[I] = Body;
182     }
183     I += Sym.getNumberOfAuxSymbols();
184     LastSectionNumber = Sym.getSectionNumber();
185   }
186   return std::error_code();
187 }
188 
189 Undefined *ObjectFile::createUndefined(COFFSymbolRef Sym) {
190   StringRef Name;
191   COFFObj->getSymbolName(Sym, Name);
192   return new (Alloc) Undefined(Name);
193 }
194 
195 Undefined *ObjectFile::createWeakExternal(COFFSymbolRef Sym, const void *AuxP) {
196   StringRef Name;
197   COFFObj->getSymbolName(Sym, Name);
198   auto *U = new (Alloc) Undefined(Name);
199   auto *Aux = (const coff_aux_weak_external *)AuxP;
200   U->WeakAlias = cast<Undefined>(SparseSymbolBodies[Aux->TagIndex]);
201   return U;
202 }
203 
204 Defined *ObjectFile::createDefined(COFFSymbolRef Sym, const void *AuxP,
205                                    bool IsFirst) {
206   StringRef Name;
207   if (Sym.isCommon()) {
208     auto *C = new (Alloc) CommonChunk(Sym);
209     Chunks.push_back(C);
210     return new (Alloc) DefinedCommon(this, Sym, C);
211   }
212   if (Sym.isAbsolute()) {
213     COFFObj->getSymbolName(Sym, Name);
214     // Skip special symbols.
215     if (Name == "@comp.id" || Name == "@feat.00")
216       return nullptr;
217     return new (Alloc) DefinedAbsolute(Name, Sym);
218   }
219   if (Sym.getSectionNumber() == llvm::COFF::IMAGE_SYM_DEBUG)
220     return nullptr;
221 
222   // Nothing else to do without a section chunk.
223   auto *SC = cast_or_null<SectionChunk>(SparseChunks[Sym.getSectionNumber()]);
224   if (!SC)
225     return nullptr;
226 
227   // Handle associative sections
228   if (IsFirst && AuxP) {
229     auto *Aux = reinterpret_cast<const coff_aux_section_definition *>(AuxP);
230     if (Aux->Selection == IMAGE_COMDAT_SELECT_ASSOCIATIVE)
231       if (auto *ParentSC = cast_or_null<SectionChunk>(
232               SparseChunks[Aux->getNumber(Sym.isBigObj())]))
233         ParentSC->addAssociative(SC);
234   }
235 
236   auto *B = new (Alloc) DefinedRegular(this, Sym, SC);
237   if (SC->isCOMDAT() && Sym.getValue() == 0 && !AuxP)
238     SC->setSymbol(B);
239 
240   return B;
241 }
242 
243 std::error_code ImportFile::parse() {
244   const char *Buf = MB.getBufferStart();
245   const char *End = MB.getBufferEnd();
246   const auto *Hdr = reinterpret_cast<const coff_import_header *>(Buf);
247 
248   // Check if the total size is valid.
249   if ((size_t)(End - Buf) != (sizeof(*Hdr) + Hdr->SizeOfData)) {
250     llvm::errs() << "broken import library\n";
251     return make_error_code(LLDError::BrokenFile);
252   }
253 
254   // Read names and create an __imp_ symbol.
255   StringRef Name = StringAlloc.save(StringRef(Buf + sizeof(*Hdr)));
256   StringRef ImpName = StringAlloc.save(Twine("__imp_") + Name);
257   StringRef DLLName(Buf + sizeof(coff_import_header) + Name.size() + 1);
258   StringRef ExternalName = Name;
259   if (Hdr->getNameType() == llvm::COFF::IMPORT_ORDINAL)
260     ExternalName = "";
261   auto *ImpSym = new (Alloc) DefinedImportData(DLLName, ImpName, ExternalName,
262                                                Hdr);
263   SymbolBodies.push_back(ImpSym);
264 
265   // If type is function, we need to create a thunk which jump to an
266   // address pointed by the __imp_ symbol. (This allows you to call
267   // DLL functions just like regular non-DLL functions.)
268   if (Hdr->getType() == llvm::COFF::IMPORT_CODE)
269     SymbolBodies.push_back(new (Alloc) DefinedImportThunk(Name, ImpSym));
270   return std::error_code();
271 }
272 
273 std::error_code BitcodeFile::parse() {
274   std::string Err;
275   M.reset(LTOModule::createFromBuffer(MB.getBufferStart(),
276                                       MB.getBufferSize(),
277                                       llvm::TargetOptions(), Err));
278   if (!Err.empty()) {
279     llvm::errs() << Err << '\n';
280     return make_error_code(LLDError::BrokenFile);
281   }
282 
283   llvm::BumpPtrStringSaver Saver(Alloc);
284   for (unsigned I = 0, E = M->getSymbolCount(); I != E; ++I) {
285     lto_symbol_attributes Attrs = M->getSymbolAttributes(I);
286     if ((Attrs & LTO_SYMBOL_SCOPE_MASK) == LTO_SYMBOL_SCOPE_INTERNAL)
287       continue;
288 
289     StringRef SymName = Saver.save(M->getSymbolName(I));
290     int SymbolDef = Attrs & LTO_SYMBOL_DEFINITION_MASK;
291     if (SymbolDef == LTO_SYMBOL_DEFINITION_UNDEFINED) {
292       SymbolBodies.push_back(new (Alloc) Undefined(SymName));
293     } else {
294       bool Replaceable = (SymbolDef == LTO_SYMBOL_DEFINITION_TENTATIVE ||
295                           (Attrs & LTO_SYMBOL_COMDAT));
296       SymbolBodies.push_back(new (Alloc) DefinedBitcode(this, SymName,
297                                                         Replaceable));
298     }
299   }
300 
301   Directives = M->getLinkerOpts();
302   return std::error_code();
303 }
304 
305 } // namespace coff
306 } // namespace lld
307