Don't own the buffer in object::Binary.
[oota-llvm.git] / lib / Object / COFFObjectFile.cpp
1 //===- COFFObjectFile.cpp - COFF object file implementation -----*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file declares the COFFObjectFile class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Object/COFF.h"
15 #include "llvm/ADT/ArrayRef.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/ADT/StringSwitch.h"
18 #include "llvm/ADT/Triple.h"
19 #include "llvm/Support/COFF.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/raw_ostream.h"
22 #include <cctype>
23 #include <limits>
24
25 using namespace llvm;
26 using namespace object;
27
28 using support::ulittle8_t;
29 using support::ulittle16_t;
30 using support::ulittle32_t;
31 using support::little16_t;
32
33 // Returns false if size is greater than the buffer size. And sets ec.
34 static bool checkSize(MemoryBufferRef M, std::error_code &EC, uint64_t Size) {
35   if (M.getBufferSize() < Size) {
36     EC = object_error::unexpected_eof;
37     return false;
38   }
39   return true;
40 }
41
42 // Sets Obj unless any bytes in [addr, addr + size) fall outsize of m.
43 // Returns unexpected_eof if error.
44 template <typename T>
45 static std::error_code getObject(const T *&Obj, MemoryBufferRef M,
46                                  const uint8_t *Ptr,
47                                  const size_t Size = sizeof(T)) {
48   uintptr_t Addr = uintptr_t(Ptr);
49   if (Addr + Size < Addr || Addr + Size < Size ||
50       Addr + Size > uintptr_t(M.getBufferEnd())) {
51     return object_error::unexpected_eof;
52   }
53   Obj = reinterpret_cast<const T *>(Addr);
54   return object_error::success;
55 }
56
57 // Decode a string table entry in base 64 (//AAAAAA). Expects \arg Str without
58 // prefixed slashes.
59 static bool decodeBase64StringEntry(StringRef Str, uint32_t &Result) {
60   assert(Str.size() <= 6 && "String too long, possible overflow.");
61   if (Str.size() > 6)
62     return true;
63
64   uint64_t Value = 0;
65   while (!Str.empty()) {
66     unsigned CharVal;
67     if (Str[0] >= 'A' && Str[0] <= 'Z') // 0..25
68       CharVal = Str[0] - 'A';
69     else if (Str[0] >= 'a' && Str[0] <= 'z') // 26..51
70       CharVal = Str[0] - 'a' + 26;
71     else if (Str[0] >= '0' && Str[0] <= '9') // 52..61
72       CharVal = Str[0] - '0' + 52;
73     else if (Str[0] == '+') // 62
74       CharVal = 62;
75     else if (Str[0] == '/') // 63
76       CharVal = 63;
77     else
78       return true;
79
80     Value = (Value * 64) + CharVal;
81     Str = Str.substr(1);
82   }
83
84   if (Value > std::numeric_limits<uint32_t>::max())
85     return true;
86
87   Result = static_cast<uint32_t>(Value);
88   return false;
89 }
90
91 const coff_symbol *COFFObjectFile::toSymb(DataRefImpl Ref) const {
92   const coff_symbol *Addr = reinterpret_cast<const coff_symbol*>(Ref.p);
93
94 # ifndef NDEBUG
95   // Verify that the symbol points to a valid entry in the symbol table.
96   uintptr_t Offset = uintptr_t(Addr) - uintptr_t(base());
97   if (Offset < COFFHeader->PointerToSymbolTable
98       || Offset >= COFFHeader->PointerToSymbolTable
99          + (COFFHeader->NumberOfSymbols * sizeof(coff_symbol)))
100     report_fatal_error("Symbol was outside of symbol table.");
101
102   assert((Offset - COFFHeader->PointerToSymbolTable) % sizeof(coff_symbol)
103          == 0 && "Symbol did not point to the beginning of a symbol");
104 # endif
105
106   return Addr;
107 }
108
109 const coff_section *COFFObjectFile::toSec(DataRefImpl Ref) const {
110   const coff_section *Addr = reinterpret_cast<const coff_section*>(Ref.p);
111
112 # ifndef NDEBUG
113   // Verify that the section points to a valid entry in the section table.
114   if (Addr < SectionTable
115       || Addr >= (SectionTable + COFFHeader->NumberOfSections))
116     report_fatal_error("Section was outside of section table.");
117
118   uintptr_t Offset = uintptr_t(Addr) - uintptr_t(SectionTable);
119   assert(Offset % sizeof(coff_section) == 0 &&
120          "Section did not point to the beginning of a section");
121 # endif
122
123   return Addr;
124 }
125
126 void COFFObjectFile::moveSymbolNext(DataRefImpl &Ref) const {
127   const coff_symbol *Symb = toSymb(Ref);
128   Symb += 1 + Symb->NumberOfAuxSymbols;
129   Ref.p = reinterpret_cast<uintptr_t>(Symb);
130 }
131
132 std::error_code COFFObjectFile::getSymbolName(DataRefImpl Ref,
133                                               StringRef &Result) const {
134   const coff_symbol *Symb = toSymb(Ref);
135   return getSymbolName(Symb, Result);
136 }
137
138 std::error_code COFFObjectFile::getSymbolAddress(DataRefImpl Ref,
139                                                  uint64_t &Result) const {
140   const coff_symbol *Symb = toSymb(Ref);
141   const coff_section *Section = nullptr;
142   if (std::error_code EC = getSection(Symb->SectionNumber, Section))
143     return EC;
144
145   if (Symb->SectionNumber == COFF::IMAGE_SYM_UNDEFINED)
146     Result = UnknownAddressOrSize;
147   else if (Section)
148     Result = Section->VirtualAddress + Symb->Value;
149   else
150     Result = Symb->Value;
151   return object_error::success;
152 }
153
154 std::error_code COFFObjectFile::getSymbolType(DataRefImpl Ref,
155                                               SymbolRef::Type &Result) const {
156   const coff_symbol *Symb = toSymb(Ref);
157   Result = SymbolRef::ST_Other;
158   if (Symb->StorageClass == COFF::IMAGE_SYM_CLASS_EXTERNAL &&
159       Symb->SectionNumber == COFF::IMAGE_SYM_UNDEFINED) {
160     Result = SymbolRef::ST_Unknown;
161   } else if (Symb->isFunctionDefinition()) {
162     Result = SymbolRef::ST_Function;
163   } else {
164     uint32_t Characteristics = 0;
165     if (!COFF::isReservedSectionNumber(Symb->SectionNumber)) {
166       const coff_section *Section = nullptr;
167       if (std::error_code EC = getSection(Symb->SectionNumber, Section))
168         return EC;
169       Characteristics = Section->Characteristics;
170     }
171     if (Characteristics & COFF::IMAGE_SCN_MEM_READ &&
172         ~Characteristics & COFF::IMAGE_SCN_MEM_WRITE) // Read only.
173       Result = SymbolRef::ST_Data;
174   }
175   return object_error::success;
176 }
177
178 uint32_t COFFObjectFile::getSymbolFlags(DataRefImpl Ref) const {
179   const coff_symbol *Symb = toSymb(Ref);
180   uint32_t Result = SymbolRef::SF_None;
181
182   // TODO: Correctly set SF_FormatSpecific, SF_Common
183
184   if (Symb->SectionNumber == COFF::IMAGE_SYM_UNDEFINED) {
185     if (Symb->Value == 0)
186       Result |= SymbolRef::SF_Undefined;
187     else
188       Result |= SymbolRef::SF_Common;
189   }
190
191
192   // TODO: This are certainly too restrictive.
193   if (Symb->StorageClass == COFF::IMAGE_SYM_CLASS_EXTERNAL)
194     Result |= SymbolRef::SF_Global;
195
196   if (Symb->StorageClass == COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL)
197     Result |= SymbolRef::SF_Weak;
198
199   if (Symb->SectionNumber == COFF::IMAGE_SYM_ABSOLUTE)
200     Result |= SymbolRef::SF_Absolute;
201
202   return Result;
203 }
204
205 std::error_code COFFObjectFile::getSymbolSize(DataRefImpl Ref,
206                                               uint64_t &Result) const {
207   // FIXME: Return the correct size. This requires looking at all the symbols
208   //        in the same section as this symbol, and looking for either the next
209   //        symbol, or the end of the section.
210   const coff_symbol *Symb = toSymb(Ref);
211   const coff_section *Section = nullptr;
212   if (std::error_code EC = getSection(Symb->SectionNumber, Section))
213     return EC;
214
215   if (Symb->SectionNumber == COFF::IMAGE_SYM_UNDEFINED)
216     Result = UnknownAddressOrSize;
217   else if (Section)
218     Result = Section->SizeOfRawData - Symb->Value;
219   else
220     Result = 0;
221   return object_error::success;
222 }
223
224 std::error_code
225 COFFObjectFile::getSymbolSection(DataRefImpl Ref,
226                                  section_iterator &Result) const {
227   const coff_symbol *Symb = toSymb(Ref);
228   if (COFF::isReservedSectionNumber(Symb->SectionNumber)) {
229     Result = section_end();
230   } else {
231     const coff_section *Sec = nullptr;
232     if (std::error_code EC = getSection(Symb->SectionNumber, Sec))
233       return EC;
234     DataRefImpl Ref;
235     Ref.p = reinterpret_cast<uintptr_t>(Sec);
236     Result = section_iterator(SectionRef(Ref, this));
237   }
238   return object_error::success;
239 }
240
241 void COFFObjectFile::moveSectionNext(DataRefImpl &Ref) const {
242   const coff_section *Sec = toSec(Ref);
243   Sec += 1;
244   Ref.p = reinterpret_cast<uintptr_t>(Sec);
245 }
246
247 std::error_code COFFObjectFile::getSectionName(DataRefImpl Ref,
248                                                StringRef &Result) const {
249   const coff_section *Sec = toSec(Ref);
250   return getSectionName(Sec, Result);
251 }
252
253 std::error_code COFFObjectFile::getSectionAddress(DataRefImpl Ref,
254                                                   uint64_t &Result) const {
255   const coff_section *Sec = toSec(Ref);
256   Result = Sec->VirtualAddress;
257   return object_error::success;
258 }
259
260 std::error_code COFFObjectFile::getSectionSize(DataRefImpl Ref,
261                                                uint64_t &Result) const {
262   const coff_section *Sec = toSec(Ref);
263   Result = Sec->SizeOfRawData;
264   return object_error::success;
265 }
266
267 std::error_code COFFObjectFile::getSectionContents(DataRefImpl Ref,
268                                                    StringRef &Result) const {
269   const coff_section *Sec = toSec(Ref);
270   ArrayRef<uint8_t> Res;
271   std::error_code EC = getSectionContents(Sec, Res);
272   Result = StringRef(reinterpret_cast<const char*>(Res.data()), Res.size());
273   return EC;
274 }
275
276 std::error_code COFFObjectFile::getSectionAlignment(DataRefImpl Ref,
277                                                     uint64_t &Res) const {
278   const coff_section *Sec = toSec(Ref);
279   if (!Sec)
280     return object_error::parse_failed;
281   Res = uint64_t(1) << (((Sec->Characteristics & 0x00F00000) >> 20) - 1);
282   return object_error::success;
283 }
284
285 std::error_code COFFObjectFile::isSectionText(DataRefImpl Ref,
286                                               bool &Result) const {
287   const coff_section *Sec = toSec(Ref);
288   Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_CODE;
289   return object_error::success;
290 }
291
292 std::error_code COFFObjectFile::isSectionData(DataRefImpl Ref,
293                                               bool &Result) const {
294   const coff_section *Sec = toSec(Ref);
295   Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA;
296   return object_error::success;
297 }
298
299 std::error_code COFFObjectFile::isSectionBSS(DataRefImpl Ref,
300                                              bool &Result) const {
301   const coff_section *Sec = toSec(Ref);
302   Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA;
303   return object_error::success;
304 }
305
306 std::error_code
307 COFFObjectFile::isSectionRequiredForExecution(DataRefImpl Ref,
308                                               bool &Result) const {
309   // FIXME: Unimplemented
310   Result = true;
311   return object_error::success;
312 }
313
314 std::error_code COFFObjectFile::isSectionVirtual(DataRefImpl Ref,
315                                                  bool &Result) const {
316   const coff_section *Sec = toSec(Ref);
317   Result = Sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA;
318   return object_error::success;
319 }
320
321 std::error_code COFFObjectFile::isSectionZeroInit(DataRefImpl Ref,
322                                                   bool &Result) const {
323   // FIXME: Unimplemented.
324   Result = false;
325   return object_error::success;
326 }
327
328 std::error_code COFFObjectFile::isSectionReadOnlyData(DataRefImpl Ref,
329                                                       bool &Result) const {
330   // FIXME: Unimplemented.
331   Result = false;
332   return object_error::success;
333 }
334
335 std::error_code COFFObjectFile::sectionContainsSymbol(DataRefImpl SecRef,
336                                                       DataRefImpl SymbRef,
337                                                       bool &Result) const {
338   const coff_section *Sec = toSec(SecRef);
339   const coff_symbol *Symb = toSymb(SymbRef);
340   const coff_section *SymbSec = nullptr;
341   if (std::error_code EC = getSection(Symb->SectionNumber, SymbSec))
342     return EC;
343   if (SymbSec == Sec)
344     Result = true;
345   else
346     Result = false;
347   return object_error::success;
348 }
349
350 relocation_iterator COFFObjectFile::section_rel_begin(DataRefImpl Ref) const {
351   const coff_section *Sec = toSec(Ref);
352   DataRefImpl Ret;
353   if (Sec->NumberOfRelocations == 0) {
354     Ret.p = 0;
355   } else {
356     auto begin = reinterpret_cast<const coff_relocation*>(
357         base() + Sec->PointerToRelocations);
358     if (Sec->hasExtendedRelocations()) {
359       // Skip the first relocation entry repurposed to store the number of
360       // relocations.
361       begin++;
362     }
363     Ret.p = reinterpret_cast<uintptr_t>(begin);
364   }
365   return relocation_iterator(RelocationRef(Ret, this));
366 }
367
368 static uint32_t getNumberOfRelocations(const coff_section *Sec,
369                                        const uint8_t *base) {
370   // The field for the number of relocations in COFF section table is only
371   // 16-bit wide. If a section has more than 65535 relocations, 0xFFFF is set to
372   // NumberOfRelocations field, and the actual relocation count is stored in the
373   // VirtualAddress field in the first relocation entry.
374   if (Sec->hasExtendedRelocations()) {
375     auto *FirstReloc = reinterpret_cast<const coff_relocation*>(
376         base + Sec->PointerToRelocations);
377     return FirstReloc->VirtualAddress;
378   }
379   return Sec->NumberOfRelocations;
380 }
381
382 relocation_iterator COFFObjectFile::section_rel_end(DataRefImpl Ref) const {
383   const coff_section *Sec = toSec(Ref);
384   DataRefImpl Ret;
385   if (Sec->NumberOfRelocations == 0) {
386     Ret.p = 0;
387   } else {
388     auto begin = reinterpret_cast<const coff_relocation*>(
389         base() + Sec->PointerToRelocations);
390     uint32_t NumReloc = getNumberOfRelocations(Sec, base());
391     Ret.p = reinterpret_cast<uintptr_t>(begin + NumReloc);
392   }
393   return relocation_iterator(RelocationRef(Ret, this));
394 }
395
396 // Initialize the pointer to the symbol table.
397 std::error_code COFFObjectFile::initSymbolTablePtr() {
398   if (std::error_code EC = getObject(
399           SymbolTable, Data, base() + COFFHeader->PointerToSymbolTable,
400           COFFHeader->NumberOfSymbols * sizeof(coff_symbol)))
401     return EC;
402
403   // Find string table. The first four byte of the string table contains the
404   // total size of the string table, including the size field itself. If the
405   // string table is empty, the value of the first four byte would be 4.
406   const uint8_t *StringTableAddr =
407       base() + COFFHeader->PointerToSymbolTable +
408       COFFHeader->NumberOfSymbols * sizeof(coff_symbol);
409   const ulittle32_t *StringTableSizePtr;
410   if (std::error_code EC = getObject(StringTableSizePtr, Data, StringTableAddr))
411     return EC;
412   StringTableSize = *StringTableSizePtr;
413   if (std::error_code EC =
414           getObject(StringTable, Data, StringTableAddr, StringTableSize))
415     return EC;
416
417   // Treat table sizes < 4 as empty because contrary to the PECOFF spec, some
418   // tools like cvtres write a size of 0 for an empty table instead of 4.
419   if (StringTableSize < 4)
420       StringTableSize = 4;
421
422   // Check that the string table is null terminated if has any in it.
423   if (StringTableSize > 4 && StringTable[StringTableSize - 1] != 0)
424     return  object_error::parse_failed;
425   return object_error::success;
426 }
427
428 // Returns the file offset for the given VA.
429 std::error_code COFFObjectFile::getVaPtr(uint64_t Addr, uintptr_t &Res) const {
430   uint64_t ImageBase = PE32Header ? (uint64_t)PE32Header->ImageBase
431                                   : (uint64_t)PE32PlusHeader->ImageBase;
432   uint64_t Rva = Addr - ImageBase;
433   assert(Rva <= UINT32_MAX);
434   return getRvaPtr((uint32_t)Rva, Res);
435 }
436
437 // Returns the file offset for the given RVA.
438 std::error_code COFFObjectFile::getRvaPtr(uint32_t Addr, uintptr_t &Res) const {
439   for (const SectionRef &S : sections()) {
440     const coff_section *Section = getCOFFSection(S);
441     uint32_t SectionStart = Section->VirtualAddress;
442     uint32_t SectionEnd = Section->VirtualAddress + Section->VirtualSize;
443     if (SectionStart <= Addr && Addr < SectionEnd) {
444       uint32_t Offset = Addr - SectionStart;
445       Res = uintptr_t(base()) + Section->PointerToRawData + Offset;
446       return object_error::success;
447     }
448   }
449   return object_error::parse_failed;
450 }
451
452 // Returns hint and name fields, assuming \p Rva is pointing to a Hint/Name
453 // table entry.
454 std::error_code COFFObjectFile::getHintName(uint32_t Rva, uint16_t &Hint,
455                                             StringRef &Name) const {
456   uintptr_t IntPtr = 0;
457   if (std::error_code EC = getRvaPtr(Rva, IntPtr))
458     return EC;
459   const uint8_t *Ptr = reinterpret_cast<const uint8_t *>(IntPtr);
460   Hint = *reinterpret_cast<const ulittle16_t *>(Ptr);
461   Name = StringRef(reinterpret_cast<const char *>(Ptr + 2));
462   return object_error::success;
463 }
464
465 // Find the import table.
466 std::error_code COFFObjectFile::initImportTablePtr() {
467   // First, we get the RVA of the import table. If the file lacks a pointer to
468   // the import table, do nothing.
469   const data_directory *DataEntry;
470   if (getDataDirectory(COFF::IMPORT_TABLE, DataEntry))
471     return object_error::success;
472
473   // Do nothing if the pointer to import table is NULL.
474   if (DataEntry->RelativeVirtualAddress == 0)
475     return object_error::success;
476
477   uint32_t ImportTableRva = DataEntry->RelativeVirtualAddress;
478   NumberOfImportDirectory = DataEntry->Size /
479       sizeof(import_directory_table_entry);
480
481   // Find the section that contains the RVA. This is needed because the RVA is
482   // the import table's memory address which is different from its file offset.
483   uintptr_t IntPtr = 0;
484   if (std::error_code EC = getRvaPtr(ImportTableRva, IntPtr))
485     return EC;
486   ImportDirectory = reinterpret_cast<
487       const import_directory_table_entry *>(IntPtr);
488   return object_error::success;
489 }
490
491 // Find the export table.
492 std::error_code COFFObjectFile::initExportTablePtr() {
493   // First, we get the RVA of the export table. If the file lacks a pointer to
494   // the export table, do nothing.
495   const data_directory *DataEntry;
496   if (getDataDirectory(COFF::EXPORT_TABLE, DataEntry))
497     return object_error::success;
498
499   // Do nothing if the pointer to export table is NULL.
500   if (DataEntry->RelativeVirtualAddress == 0)
501     return object_error::success;
502
503   uint32_t ExportTableRva = DataEntry->RelativeVirtualAddress;
504   uintptr_t IntPtr = 0;
505   if (std::error_code EC = getRvaPtr(ExportTableRva, IntPtr))
506     return EC;
507   ExportDirectory =
508       reinterpret_cast<const export_directory_table_entry *>(IntPtr);
509   return object_error::success;
510 }
511
512 COFFObjectFile::COFFObjectFile(MemoryBufferRef Object, std::error_code &EC)
513     : ObjectFile(Binary::ID_COFF, Object), COFFHeader(nullptr),
514       PE32Header(nullptr), PE32PlusHeader(nullptr), DataDirectory(nullptr),
515       SectionTable(nullptr), SymbolTable(nullptr), StringTable(nullptr),
516       StringTableSize(0), ImportDirectory(nullptr), NumberOfImportDirectory(0),
517       ExportDirectory(nullptr) {
518   // Check that we at least have enough room for a header.
519   if (!checkSize(Data, EC, sizeof(coff_file_header)))
520     return;
521
522   // The current location in the file where we are looking at.
523   uint64_t CurPtr = 0;
524
525   // PE header is optional and is present only in executables. If it exists,
526   // it is placed right after COFF header.
527   bool HasPEHeader = false;
528
529   // Check if this is a PE/COFF file.
530   if (base()[0] == 0x4d && base()[1] == 0x5a) {
531     // PE/COFF, seek through MS-DOS compatibility stub and 4-byte
532     // PE signature to find 'normal' COFF header.
533     if (!checkSize(Data, EC, 0x3c + 8))
534       return;
535     CurPtr = *reinterpret_cast<const ulittle16_t *>(base() + 0x3c);
536     // Check the PE magic bytes. ("PE\0\0")
537     if (std::memcmp(base() + CurPtr, "PE\0\0", 4) != 0) {
538       EC = object_error::parse_failed;
539       return;
540     }
541     CurPtr += 4; // Skip the PE magic bytes.
542     HasPEHeader = true;
543   }
544
545   if ((EC = getObject(COFFHeader, Data, base() + CurPtr)))
546     return;
547   CurPtr += sizeof(coff_file_header);
548
549   if (HasPEHeader) {
550     const pe32_header *Header;
551     if ((EC = getObject(Header, Data, base() + CurPtr)))
552       return;
553
554     const uint8_t *DataDirAddr;
555     uint64_t DataDirSize;
556     if (Header->Magic == 0x10b) {
557       PE32Header = Header;
558       DataDirAddr = base() + CurPtr + sizeof(pe32_header);
559       DataDirSize = sizeof(data_directory) * PE32Header->NumberOfRvaAndSize;
560     } else if (Header->Magic == 0x20b) {
561       PE32PlusHeader = reinterpret_cast<const pe32plus_header *>(Header);
562       DataDirAddr = base() + CurPtr + sizeof(pe32plus_header);
563       DataDirSize = sizeof(data_directory) * PE32PlusHeader->NumberOfRvaAndSize;
564     } else {
565       // It's neither PE32 nor PE32+.
566       EC = object_error::parse_failed;
567       return;
568     }
569     if ((EC = getObject(DataDirectory, Data, DataDirAddr, DataDirSize)))
570       return;
571     CurPtr += COFFHeader->SizeOfOptionalHeader;
572   }
573
574   if (COFFHeader->isImportLibrary())
575     return;
576
577   if ((EC = getObject(SectionTable, Data, base() + CurPtr,
578                       COFFHeader->NumberOfSections * sizeof(coff_section))))
579     return;
580
581   // Initialize the pointer to the symbol table.
582   if (COFFHeader->PointerToSymbolTable != 0)
583     if ((EC = initSymbolTablePtr()))
584       return;
585
586   // Initialize the pointer to the beginning of the import table.
587   if ((EC = initImportTablePtr()))
588     return;
589
590   // Initialize the pointer to the export table.
591   if ((EC = initExportTablePtr()))
592     return;
593
594   EC = object_error::success;
595 }
596
597 basic_symbol_iterator COFFObjectFile::symbol_begin_impl() const {
598   DataRefImpl Ret;
599   Ret.p = reinterpret_cast<uintptr_t>(SymbolTable);
600   return basic_symbol_iterator(SymbolRef(Ret, this));
601 }
602
603 basic_symbol_iterator COFFObjectFile::symbol_end_impl() const {
604   // The symbol table ends where the string table begins.
605   DataRefImpl Ret;
606   Ret.p = reinterpret_cast<uintptr_t>(StringTable);
607   return basic_symbol_iterator(SymbolRef(Ret, this));
608 }
609
610 import_directory_iterator COFFObjectFile::import_directory_begin() const {
611   return import_directory_iterator(
612       ImportDirectoryEntryRef(ImportDirectory, 0, this));
613 }
614
615 import_directory_iterator COFFObjectFile::import_directory_end() const {
616   return import_directory_iterator(
617       ImportDirectoryEntryRef(ImportDirectory, NumberOfImportDirectory, this));
618 }
619
620 export_directory_iterator COFFObjectFile::export_directory_begin() const {
621   return export_directory_iterator(
622       ExportDirectoryEntryRef(ExportDirectory, 0, this));
623 }
624
625 export_directory_iterator COFFObjectFile::export_directory_end() const {
626   if (!ExportDirectory)
627     return export_directory_iterator(ExportDirectoryEntryRef(nullptr, 0, this));
628   ExportDirectoryEntryRef Ref(ExportDirectory,
629                               ExportDirectory->AddressTableEntries, this);
630   return export_directory_iterator(Ref);
631 }
632
633 section_iterator COFFObjectFile::section_begin() const {
634   DataRefImpl Ret;
635   Ret.p = reinterpret_cast<uintptr_t>(SectionTable);
636   return section_iterator(SectionRef(Ret, this));
637 }
638
639 section_iterator COFFObjectFile::section_end() const {
640   DataRefImpl Ret;
641   int NumSections = COFFHeader->isImportLibrary()
642       ? 0 : COFFHeader->NumberOfSections;
643   Ret.p = reinterpret_cast<uintptr_t>(SectionTable + NumSections);
644   return section_iterator(SectionRef(Ret, this));
645 }
646
647 uint8_t COFFObjectFile::getBytesInAddress() const {
648   return getArch() == Triple::x86_64 ? 8 : 4;
649 }
650
651 StringRef COFFObjectFile::getFileFormatName() const {
652   switch(COFFHeader->Machine) {
653   case COFF::IMAGE_FILE_MACHINE_I386:
654     return "COFF-i386";
655   case COFF::IMAGE_FILE_MACHINE_AMD64:
656     return "COFF-x86-64";
657   case COFF::IMAGE_FILE_MACHINE_ARMNT:
658     return "COFF-ARM";
659   default:
660     return "COFF-<unknown arch>";
661   }
662 }
663
664 unsigned COFFObjectFile::getArch() const {
665   switch(COFFHeader->Machine) {
666   case COFF::IMAGE_FILE_MACHINE_I386:
667     return Triple::x86;
668   case COFF::IMAGE_FILE_MACHINE_AMD64:
669     return Triple::x86_64;
670   case COFF::IMAGE_FILE_MACHINE_ARMNT:
671     return Triple::thumb;
672   default:
673     return Triple::UnknownArch;
674   }
675 }
676
677 // This method is kept here because lld uses this. As soon as we make
678 // lld to use getCOFFHeader, this method will be removed.
679 std::error_code COFFObjectFile::getHeader(const coff_file_header *&Res) const {
680   return getCOFFHeader(Res);
681 }
682
683 std::error_code
684 COFFObjectFile::getCOFFHeader(const coff_file_header *&Res) const {
685   Res = COFFHeader;
686   return object_error::success;
687 }
688
689 std::error_code COFFObjectFile::getPE32Header(const pe32_header *&Res) const {
690   Res = PE32Header;
691   return object_error::success;
692 }
693
694 std::error_code
695 COFFObjectFile::getPE32PlusHeader(const pe32plus_header *&Res) const {
696   Res = PE32PlusHeader;
697   return object_error::success;
698 }
699
700 std::error_code
701 COFFObjectFile::getDataDirectory(uint32_t Index,
702                                  const data_directory *&Res) const {
703   // Error if if there's no data directory or the index is out of range.
704   if (!DataDirectory)
705     return object_error::parse_failed;
706   assert(PE32Header || PE32PlusHeader);
707   uint32_t NumEnt = PE32Header ? PE32Header->NumberOfRvaAndSize
708                                : PE32PlusHeader->NumberOfRvaAndSize;
709   if (Index > NumEnt)
710     return object_error::parse_failed;
711   Res = &DataDirectory[Index];
712   return object_error::success;
713 }
714
715 std::error_code COFFObjectFile::getSection(int32_t Index,
716                                            const coff_section *&Result) const {
717   // Check for special index values.
718   if (COFF::isReservedSectionNumber(Index))
719     Result = nullptr;
720   else if (Index > 0 && Index <= COFFHeader->NumberOfSections)
721     // We already verified the section table data, so no need to check again.
722     Result = SectionTable + (Index - 1);
723   else
724     return object_error::parse_failed;
725   return object_error::success;
726 }
727
728 std::error_code COFFObjectFile::getString(uint32_t Offset,
729                                           StringRef &Result) const {
730   if (StringTableSize <= 4)
731     // Tried to get a string from an empty string table.
732     return object_error::parse_failed;
733   if (Offset >= StringTableSize)
734     return object_error::unexpected_eof;
735   Result = StringRef(StringTable + Offset);
736   return object_error::success;
737 }
738
739 std::error_code COFFObjectFile::getSymbol(uint32_t Index,
740                                           const coff_symbol *&Result) const {
741   if (Index < COFFHeader->NumberOfSymbols)
742     Result = SymbolTable + Index;
743   else
744     return object_error::parse_failed;
745   return object_error::success;
746 }
747
748 std::error_code COFFObjectFile::getSymbolName(const coff_symbol *Symbol,
749                                               StringRef &Res) const {
750   // Check for string table entry. First 4 bytes are 0.
751   if (Symbol->Name.Offset.Zeroes == 0) {
752     uint32_t Offset = Symbol->Name.Offset.Offset;
753     if (std::error_code EC = getString(Offset, Res))
754       return EC;
755     return object_error::success;
756   }
757
758   if (Symbol->Name.ShortName[7] == 0)
759     // Null terminated, let ::strlen figure out the length.
760     Res = StringRef(Symbol->Name.ShortName);
761   else
762     // Not null terminated, use all 8 bytes.
763     Res = StringRef(Symbol->Name.ShortName, 8);
764   return object_error::success;
765 }
766
767 ArrayRef<uint8_t> COFFObjectFile::getSymbolAuxData(
768                                   const coff_symbol *Symbol) const {
769   const uint8_t *Aux = nullptr;
770
771   if (Symbol->NumberOfAuxSymbols > 0) {
772   // AUX data comes immediately after the symbol in COFF
773     Aux = reinterpret_cast<const uint8_t *>(Symbol + 1);
774 # ifndef NDEBUG
775     // Verify that the Aux symbol points to a valid entry in the symbol table.
776     uintptr_t Offset = uintptr_t(Aux) - uintptr_t(base());
777     if (Offset < COFFHeader->PointerToSymbolTable
778         || Offset >= COFFHeader->PointerToSymbolTable
779            + (COFFHeader->NumberOfSymbols * sizeof(coff_symbol)))
780       report_fatal_error("Aux Symbol data was outside of symbol table.");
781
782     assert((Offset - COFFHeader->PointerToSymbolTable) % sizeof(coff_symbol)
783          == 0 && "Aux Symbol data did not point to the beginning of a symbol");
784 # endif
785   }
786   return ArrayRef<uint8_t>(Aux,
787                            Symbol->NumberOfAuxSymbols * sizeof(coff_symbol));
788 }
789
790 std::error_code COFFObjectFile::getSectionName(const coff_section *Sec,
791                                                StringRef &Res) const {
792   StringRef Name;
793   if (Sec->Name[7] == 0)
794     // Null terminated, let ::strlen figure out the length.
795     Name = Sec->Name;
796   else
797     // Not null terminated, use all 8 bytes.
798     Name = StringRef(Sec->Name, 8);
799
800   // Check for string table entry. First byte is '/'.
801   if (Name[0] == '/') {
802     uint32_t Offset;
803     if (Name[1] == '/') {
804       if (decodeBase64StringEntry(Name.substr(2), Offset))
805         return object_error::parse_failed;
806     } else {
807       if (Name.substr(1).getAsInteger(10, Offset))
808         return object_error::parse_failed;
809     }
810     if (std::error_code EC = getString(Offset, Name))
811       return EC;
812   }
813
814   Res = Name;
815   return object_error::success;
816 }
817
818 std::error_code
819 COFFObjectFile::getSectionContents(const coff_section *Sec,
820                                    ArrayRef<uint8_t> &Res) const {
821   // The only thing that we need to verify is that the contents is contained
822   // within the file bounds. We don't need to make sure it doesn't cover other
823   // data, as there's nothing that says that is not allowed.
824   uintptr_t ConStart = uintptr_t(base()) + Sec->PointerToRawData;
825   uintptr_t ConEnd = ConStart + Sec->SizeOfRawData;
826   if (ConEnd > uintptr_t(Data.getBufferEnd()))
827     return object_error::parse_failed;
828   Res = ArrayRef<uint8_t>(reinterpret_cast<const unsigned char*>(ConStart),
829                           Sec->SizeOfRawData);
830   return object_error::success;
831 }
832
833 const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const {
834   return reinterpret_cast<const coff_relocation*>(Rel.p);
835 }
836
837 void COFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
838   Rel.p = reinterpret_cast<uintptr_t>(
839             reinterpret_cast<const coff_relocation*>(Rel.p) + 1);
840 }
841
842 std::error_code COFFObjectFile::getRelocationAddress(DataRefImpl Rel,
843                                                      uint64_t &Res) const {
844   report_fatal_error("getRelocationAddress not implemented in COFFObjectFile");
845 }
846
847 std::error_code COFFObjectFile::getRelocationOffset(DataRefImpl Rel,
848                                                     uint64_t &Res) const {
849   Res = toRel(Rel)->VirtualAddress;
850   return object_error::success;
851 }
852
853 symbol_iterator COFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
854   const coff_relocation* R = toRel(Rel);
855   DataRefImpl Ref;
856   Ref.p = reinterpret_cast<uintptr_t>(SymbolTable + R->SymbolTableIndex);
857   return symbol_iterator(SymbolRef(Ref, this));
858 }
859
860 std::error_code COFFObjectFile::getRelocationType(DataRefImpl Rel,
861                                                   uint64_t &Res) const {
862   const coff_relocation* R = toRel(Rel);
863   Res = R->Type;
864   return object_error::success;
865 }
866
867 const coff_section *
868 COFFObjectFile::getCOFFSection(const SectionRef &Section) const {
869   return toSec(Section.getRawDataRefImpl());
870 }
871
872 const coff_symbol *
873 COFFObjectFile::getCOFFSymbol(const SymbolRef &Symbol) const {
874   return toSymb(Symbol.getRawDataRefImpl());
875 }
876
877 const coff_relocation *
878 COFFObjectFile::getCOFFRelocation(const RelocationRef &Reloc) const {
879   return toRel(Reloc.getRawDataRefImpl());
880 }
881
882 #define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(reloc_type)                           \
883   case COFF::reloc_type:                                                       \
884     Res = #reloc_type;                                                         \
885     break;
886
887 std::error_code
888 COFFObjectFile::getRelocationTypeName(DataRefImpl Rel,
889                                       SmallVectorImpl<char> &Result) const {
890   const coff_relocation *Reloc = toRel(Rel);
891   StringRef Res;
892   switch (COFFHeader->Machine) {
893   case COFF::IMAGE_FILE_MACHINE_AMD64:
894     switch (Reloc->Type) {
895     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ABSOLUTE);
896     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR64);
897     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32);
898     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32NB);
899     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32);
900     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_1);
901     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_2);
902     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_3);
903     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_4);
904     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_5);
905     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECTION);
906     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL);
907     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL7);
908     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_TOKEN);
909     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SREL32);
910     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_PAIR);
911     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SSPAN32);
912     default:
913       Res = "Unknown";
914     }
915     break;
916   case COFF::IMAGE_FILE_MACHINE_ARMNT:
917     switch (Reloc->Type) {
918     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ABSOLUTE);
919     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32);
920     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32NB);
921     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24);
922     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH11);
923     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_TOKEN);
924     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX24);
925     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX11);
926     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECTION);
927     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECREL);
928     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32A);
929     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32T);
930     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH20T);
931     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24T);
932     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX23T);
933     default:
934       Res = "Unknown";
935     }
936     break;
937   case COFF::IMAGE_FILE_MACHINE_I386:
938     switch (Reloc->Type) {
939     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_ABSOLUTE);
940     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR16);
941     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL16);
942     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32);
943     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32NB);
944     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SEG12);
945     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECTION);
946     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL);
947     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_TOKEN);
948     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL7);
949     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL32);
950     default:
951       Res = "Unknown";
952     }
953     break;
954   default:
955     Res = "Unknown";
956   }
957   Result.append(Res.begin(), Res.end());
958   return object_error::success;
959 }
960
961 #undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME
962
963 std::error_code
964 COFFObjectFile::getRelocationValueString(DataRefImpl Rel,
965                                          SmallVectorImpl<char> &Result) const {
966   const coff_relocation *Reloc = toRel(Rel);
967   const coff_symbol *Symb = nullptr;
968   if (std::error_code EC = getSymbol(Reloc->SymbolTableIndex, Symb))
969     return EC;
970   DataRefImpl Sym;
971   Sym.p = reinterpret_cast<uintptr_t>(Symb);
972   StringRef SymName;
973   if (std::error_code EC = getSymbolName(Sym, SymName))
974     return EC;
975   Result.append(SymName.begin(), SymName.end());
976   return object_error::success;
977 }
978
979 bool COFFObjectFile::isRelocatableObject() const {
980   return !DataDirectory;
981 }
982
983 bool ImportDirectoryEntryRef::
984 operator==(const ImportDirectoryEntryRef &Other) const {
985   return ImportTable == Other.ImportTable && Index == Other.Index;
986 }
987
988 void ImportDirectoryEntryRef::moveNext() {
989   ++Index;
990 }
991
992 std::error_code ImportDirectoryEntryRef::getImportTableEntry(
993     const import_directory_table_entry *&Result) const {
994   Result = ImportTable;
995   return object_error::success;
996 }
997
998 std::error_code ImportDirectoryEntryRef::getName(StringRef &Result) const {
999   uintptr_t IntPtr = 0;
1000   if (std::error_code EC =
1001           OwningObject->getRvaPtr(ImportTable->NameRVA, IntPtr))
1002     return EC;
1003   Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1004   return object_error::success;
1005 }
1006
1007 std::error_code ImportDirectoryEntryRef::getImportLookupEntry(
1008     const import_lookup_table_entry32 *&Result) const {
1009   uintptr_t IntPtr = 0;
1010   if (std::error_code EC =
1011           OwningObject->getRvaPtr(ImportTable->ImportLookupTableRVA, IntPtr))
1012     return EC;
1013   Result = reinterpret_cast<const import_lookup_table_entry32 *>(IntPtr);
1014   return object_error::success;
1015 }
1016
1017 bool ExportDirectoryEntryRef::
1018 operator==(const ExportDirectoryEntryRef &Other) const {
1019   return ExportTable == Other.ExportTable && Index == Other.Index;
1020 }
1021
1022 void ExportDirectoryEntryRef::moveNext() {
1023   ++Index;
1024 }
1025
1026 // Returns the name of the current export symbol. If the symbol is exported only
1027 // by ordinal, the empty string is set as a result.
1028 std::error_code ExportDirectoryEntryRef::getDllName(StringRef &Result) const {
1029   uintptr_t IntPtr = 0;
1030   if (std::error_code EC =
1031           OwningObject->getRvaPtr(ExportTable->NameRVA, IntPtr))
1032     return EC;
1033   Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1034   return object_error::success;
1035 }
1036
1037 // Returns the starting ordinal number.
1038 std::error_code
1039 ExportDirectoryEntryRef::getOrdinalBase(uint32_t &Result) const {
1040   Result = ExportTable->OrdinalBase;
1041   return object_error::success;
1042 }
1043
1044 // Returns the export ordinal of the current export symbol.
1045 std::error_code ExportDirectoryEntryRef::getOrdinal(uint32_t &Result) const {
1046   Result = ExportTable->OrdinalBase + Index;
1047   return object_error::success;
1048 }
1049
1050 // Returns the address of the current export symbol.
1051 std::error_code ExportDirectoryEntryRef::getExportRVA(uint32_t &Result) const {
1052   uintptr_t IntPtr = 0;
1053   if (std::error_code EC =
1054           OwningObject->getRvaPtr(ExportTable->ExportAddressTableRVA, IntPtr))
1055     return EC;
1056   const export_address_table_entry *entry =
1057       reinterpret_cast<const export_address_table_entry *>(IntPtr);
1058   Result = entry[Index].ExportRVA;
1059   return object_error::success;
1060 }
1061
1062 // Returns the name of the current export symbol. If the symbol is exported only
1063 // by ordinal, the empty string is set as a result.
1064 std::error_code
1065 ExportDirectoryEntryRef::getSymbolName(StringRef &Result) const {
1066   uintptr_t IntPtr = 0;
1067   if (std::error_code EC =
1068           OwningObject->getRvaPtr(ExportTable->OrdinalTableRVA, IntPtr))
1069     return EC;
1070   const ulittle16_t *Start = reinterpret_cast<const ulittle16_t *>(IntPtr);
1071
1072   uint32_t NumEntries = ExportTable->NumberOfNamePointers;
1073   int Offset = 0;
1074   for (const ulittle16_t *I = Start, *E = Start + NumEntries;
1075        I < E; ++I, ++Offset) {
1076     if (*I != Index)
1077       continue;
1078     if (std::error_code EC =
1079             OwningObject->getRvaPtr(ExportTable->NamePointerRVA, IntPtr))
1080       return EC;
1081     const ulittle32_t *NamePtr = reinterpret_cast<const ulittle32_t *>(IntPtr);
1082     if (std::error_code EC = OwningObject->getRvaPtr(NamePtr[Offset], IntPtr))
1083       return EC;
1084     Result = StringRef(reinterpret_cast<const char *>(IntPtr));
1085     return object_error::success;
1086   }
1087   Result = "";
1088   return object_error::success;
1089 }
1090
1091 ErrorOr<std::unique_ptr<COFFObjectFile>>
1092 ObjectFile::createCOFFObjectFile(MemoryBufferRef Object) {
1093   std::error_code EC;
1094   std::unique_ptr<COFFObjectFile> Ret(new COFFObjectFile(Object, EC));
1095   if (EC)
1096     return EC;
1097   return std::move(Ret);
1098 }