• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
20 #include <ctype.h>
21 
22 using namespace llvm;
23 using namespace object;
24 
25 namespace {
26 using support::ulittle8_t;
27 using support::ulittle16_t;
28 using support::ulittle32_t;
29 using support::little16_t;
30 }
31 
32 namespace {
33 // Returns false if size is greater than the buffer size. And sets ec.
checkSize(const MemoryBuffer * m,error_code & ec,uint64_t size)34 bool checkSize(const MemoryBuffer *m, 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 // Returns false if any bytes in [addr, addr + size) fall outsize of m.
checkAddr(const MemoryBuffer * m,error_code & ec,uintptr_t addr,uint64_t size)43 bool checkAddr(const MemoryBuffer *m,
44                error_code &ec,
45                uintptr_t addr,
46                uint64_t size) {
47   if (addr + size < addr ||
48       addr + size < size ||
49       addr + size > uintptr_t(m->getBufferEnd())) {
50     ec = object_error::unexpected_eof;
51     return false;
52   }
53   return true;
54 }
55 }
56 
toSymb(DataRefImpl Symb) const57 const coff_symbol *COFFObjectFile::toSymb(DataRefImpl Symb) const {
58   const coff_symbol *addr = reinterpret_cast<const coff_symbol*>(Symb.p);
59 
60 # ifndef NDEBUG
61   // Verify that the symbol points to a valid entry in the symbol table.
62   uintptr_t offset = uintptr_t(addr) - uintptr_t(base());
63   if (offset < Header->PointerToSymbolTable
64       || offset >= Header->PointerToSymbolTable
65          + (Header->NumberOfSymbols * sizeof(coff_symbol)))
66     report_fatal_error("Symbol was outside of symbol table.");
67 
68   assert((offset - Header->PointerToSymbolTable) % sizeof(coff_symbol)
69          == 0 && "Symbol did not point to the beginning of a symbol");
70 # endif
71 
72   return addr;
73 }
74 
toSec(DataRefImpl Sec) const75 const coff_section *COFFObjectFile::toSec(DataRefImpl Sec) const {
76   const coff_section *addr = reinterpret_cast<const coff_section*>(Sec.p);
77 
78 # ifndef NDEBUG
79   // Verify that the section points to a valid entry in the section table.
80   if (addr < SectionTable
81       || addr >= (SectionTable + Header->NumberOfSections))
82     report_fatal_error("Section was outside of section table.");
83 
84   uintptr_t offset = uintptr_t(addr) - uintptr_t(SectionTable);
85   assert(offset % sizeof(coff_section) == 0 &&
86          "Section did not point to the beginning of a section");
87 # endif
88 
89   return addr;
90 }
91 
getSymbolNext(DataRefImpl Symb,SymbolRef & Result) const92 error_code COFFObjectFile::getSymbolNext(DataRefImpl Symb,
93                                          SymbolRef &Result) const {
94   const coff_symbol *symb = toSymb(Symb);
95   symb += 1 + symb->NumberOfAuxSymbols;
96   Symb.p = reinterpret_cast<uintptr_t>(symb);
97   Result = SymbolRef(Symb, this);
98   return object_error::success;
99 }
100 
getSymbolName(DataRefImpl Symb,StringRef & Result) const101  error_code COFFObjectFile::getSymbolName(DataRefImpl Symb,
102                                           StringRef &Result) const {
103   const coff_symbol *symb = toSymb(Symb);
104   return getSymbolName(symb, Result);
105 }
106 
getSymbolFileOffset(DataRefImpl Symb,uint64_t & Result) const107 error_code COFFObjectFile::getSymbolFileOffset(DataRefImpl Symb,
108                                             uint64_t &Result) const {
109   const coff_symbol *symb = toSymb(Symb);
110   const coff_section *Section = NULL;
111   if (error_code ec = getSection(symb->SectionNumber, Section))
112     return ec;
113   char Type;
114   if (error_code ec = getSymbolNMTypeChar(Symb, Type))
115     return ec;
116   if (Type == 'U' || Type == 'w')
117     Result = UnknownAddressOrSize;
118   else if (Section)
119     Result = Section->PointerToRawData + symb->Value;
120   else
121     Result = symb->Value;
122   return object_error::success;
123 }
124 
getSymbolAddress(DataRefImpl Symb,uint64_t & Result) const125 error_code COFFObjectFile::getSymbolAddress(DataRefImpl Symb,
126                                             uint64_t &Result) const {
127   const coff_symbol *symb = toSymb(Symb);
128   const coff_section *Section = NULL;
129   if (error_code ec = getSection(symb->SectionNumber, Section))
130     return ec;
131   char Type;
132   if (error_code ec = getSymbolNMTypeChar(Symb, Type))
133     return ec;
134   if (Type == 'U' || Type == 'w')
135     Result = UnknownAddressOrSize;
136   else if (Section)
137     Result = Section->VirtualAddress + symb->Value;
138   else
139     Result = symb->Value;
140   return object_error::success;
141 }
142 
getSymbolType(DataRefImpl Symb,SymbolRef::Type & Result) const143 error_code COFFObjectFile::getSymbolType(DataRefImpl Symb,
144                                          SymbolRef::Type &Result) const {
145   const coff_symbol *symb = toSymb(Symb);
146   Result = SymbolRef::ST_Other;
147   if (symb->StorageClass == COFF::IMAGE_SYM_CLASS_EXTERNAL &&
148       symb->SectionNumber == COFF::IMAGE_SYM_UNDEFINED) {
149     Result = SymbolRef::ST_Unknown;
150   } else {
151     if (symb->getComplexType() == COFF::IMAGE_SYM_DTYPE_FUNCTION) {
152       Result = SymbolRef::ST_Function;
153     } else {
154       char Type;
155       if (error_code ec = getSymbolNMTypeChar(Symb, Type))
156         return ec;
157       if (Type == 'r' || Type == 'R') {
158         Result = SymbolRef::ST_Data;
159       }
160     }
161   }
162   return object_error::success;
163 }
164 
getSymbolFlags(DataRefImpl Symb,uint32_t & Result) const165 error_code COFFObjectFile::getSymbolFlags(DataRefImpl Symb,
166                                           uint32_t &Result) const {
167   const coff_symbol *symb = toSymb(Symb);
168   Result = SymbolRef::SF_None;
169 
170   // TODO: Correctly set SF_FormatSpecific, SF_ThreadLocal, SF_Common
171 
172   if (symb->StorageClass == COFF::IMAGE_SYM_CLASS_EXTERNAL &&
173       symb->SectionNumber == COFF::IMAGE_SYM_UNDEFINED)
174     Result |= SymbolRef::SF_Undefined;
175 
176   // TODO: This are certainly too restrictive.
177   if (symb->StorageClass == COFF::IMAGE_SYM_CLASS_EXTERNAL)
178     Result |= SymbolRef::SF_Global;
179 
180   if (symb->StorageClass == COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL)
181     Result |= SymbolRef::SF_Weak;
182 
183   if (symb->SectionNumber == COFF::IMAGE_SYM_ABSOLUTE)
184     Result |= SymbolRef::SF_Absolute;
185 
186   return object_error::success;
187 }
188 
getSymbolSize(DataRefImpl Symb,uint64_t & Result) const189 error_code COFFObjectFile::getSymbolSize(DataRefImpl Symb,
190                                          uint64_t &Result) const {
191   // FIXME: Return the correct size. This requires looking at all the symbols
192   //        in the same section as this symbol, and looking for either the next
193   //        symbol, or the end of the section.
194   const coff_symbol *symb = toSymb(Symb);
195   const coff_section *Section = NULL;
196   if (error_code ec = getSection(symb->SectionNumber, Section))
197     return ec;
198   char Type;
199   if (error_code ec = getSymbolNMTypeChar(Symb, Type))
200     return ec;
201   if (Type == 'U' || Type == 'w')
202     Result = UnknownAddressOrSize;
203   else if (Section)
204     Result = Section->SizeOfRawData - symb->Value;
205   else
206     Result = 0;
207   return object_error::success;
208 }
209 
getSymbolNMTypeChar(DataRefImpl Symb,char & Result) const210 error_code COFFObjectFile::getSymbolNMTypeChar(DataRefImpl Symb,
211                                                char &Result) const {
212   const coff_symbol *symb = toSymb(Symb);
213   StringRef name;
214   if (error_code ec = getSymbolName(Symb, name))
215     return ec;
216   char ret = StringSwitch<char>(name)
217     .StartsWith(".debug", 'N')
218     .StartsWith(".sxdata", 'N')
219     .Default('?');
220 
221   if (ret != '?') {
222     Result = ret;
223     return object_error::success;
224   }
225 
226   uint32_t Characteristics = 0;
227   if (symb->SectionNumber > 0) {
228     const coff_section *Section = NULL;
229     if (error_code ec = getSection(symb->SectionNumber, Section))
230       return ec;
231     Characteristics = Section->Characteristics;
232   }
233 
234   switch (symb->SectionNumber) {
235   case COFF::IMAGE_SYM_UNDEFINED:
236     // Check storage classes.
237     if (symb->StorageClass == COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL) {
238       Result = 'w';
239       return object_error::success; // Don't do ::toupper.
240     } else if (symb->Value != 0) // Check for common symbols.
241       ret = 'c';
242     else
243       ret = 'u';
244     break;
245   case COFF::IMAGE_SYM_ABSOLUTE:
246     ret = 'a';
247     break;
248   case COFF::IMAGE_SYM_DEBUG:
249     ret = 'n';
250     break;
251   default:
252     // Check section type.
253     if (Characteristics & COFF::IMAGE_SCN_CNT_CODE)
254       ret = 't';
255     else if (  Characteristics & COFF::IMAGE_SCN_MEM_READ
256             && ~Characteristics & COFF::IMAGE_SCN_MEM_WRITE) // Read only.
257       ret = 'r';
258     else if (Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA)
259       ret = 'd';
260     else if (Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA)
261       ret = 'b';
262     else if (Characteristics & COFF::IMAGE_SCN_LNK_INFO)
263       ret = 'i';
264 
265     // Check for section symbol.
266     else if (  symb->StorageClass == COFF::IMAGE_SYM_CLASS_STATIC
267             && symb->Value == 0)
268        ret = 's';
269   }
270 
271   if (symb->StorageClass == COFF::IMAGE_SYM_CLASS_EXTERNAL)
272     ret = ::toupper(ret);
273 
274   Result = ret;
275   return object_error::success;
276 }
277 
getSymbolSection(DataRefImpl Symb,section_iterator & Result) const278 error_code COFFObjectFile::getSymbolSection(DataRefImpl Symb,
279                                             section_iterator &Result) const {
280   const coff_symbol *symb = toSymb(Symb);
281   if (symb->SectionNumber <= COFF::IMAGE_SYM_UNDEFINED)
282     Result = end_sections();
283   else {
284     const coff_section *sec = 0;
285     if (error_code ec = getSection(symb->SectionNumber, sec)) return ec;
286     DataRefImpl Sec;
287     Sec.p = reinterpret_cast<uintptr_t>(sec);
288     Result = section_iterator(SectionRef(Sec, this));
289   }
290   return object_error::success;
291 }
292 
getSectionNext(DataRefImpl Sec,SectionRef & Result) const293 error_code COFFObjectFile::getSectionNext(DataRefImpl Sec,
294                                           SectionRef &Result) const {
295   const coff_section *sec = toSec(Sec);
296   sec += 1;
297   Sec.p = reinterpret_cast<uintptr_t>(sec);
298   Result = SectionRef(Sec, this);
299   return object_error::success;
300 }
301 
getSectionName(DataRefImpl Sec,StringRef & Result) const302 error_code COFFObjectFile::getSectionName(DataRefImpl Sec,
303                                           StringRef &Result) const {
304   const coff_section *sec = toSec(Sec);
305   return getSectionName(sec, Result);
306 }
307 
getSectionAddress(DataRefImpl Sec,uint64_t & Result) const308 error_code COFFObjectFile::getSectionAddress(DataRefImpl Sec,
309                                              uint64_t &Result) const {
310   const coff_section *sec = toSec(Sec);
311   Result = sec->VirtualAddress;
312   return object_error::success;
313 }
314 
getSectionSize(DataRefImpl Sec,uint64_t & Result) const315 error_code COFFObjectFile::getSectionSize(DataRefImpl Sec,
316                                           uint64_t &Result) const {
317   const coff_section *sec = toSec(Sec);
318   Result = sec->SizeOfRawData;
319   return object_error::success;
320 }
321 
getSectionContents(DataRefImpl Sec,StringRef & Result) const322 error_code COFFObjectFile::getSectionContents(DataRefImpl Sec,
323                                               StringRef &Result) const {
324   const coff_section *sec = toSec(Sec);
325   ArrayRef<uint8_t> Res;
326   error_code EC = getSectionContents(sec, Res);
327   Result = StringRef(reinterpret_cast<const char*>(Res.data()), Res.size());
328   return EC;
329 }
330 
getSectionAlignment(DataRefImpl Sec,uint64_t & Res) const331 error_code COFFObjectFile::getSectionAlignment(DataRefImpl Sec,
332                                                uint64_t &Res) const {
333   const coff_section *sec = toSec(Sec);
334   if (!sec)
335     return object_error::parse_failed;
336   Res = uint64_t(1) << (((sec->Characteristics & 0x00F00000) >> 20) - 1);
337   return object_error::success;
338 }
339 
isSectionText(DataRefImpl Sec,bool & Result) const340 error_code COFFObjectFile::isSectionText(DataRefImpl Sec,
341                                          bool &Result) const {
342   const coff_section *sec = toSec(Sec);
343   Result = sec->Characteristics & COFF::IMAGE_SCN_CNT_CODE;
344   return object_error::success;
345 }
346 
isSectionData(DataRefImpl Sec,bool & Result) const347 error_code COFFObjectFile::isSectionData(DataRefImpl Sec,
348                                          bool &Result) const {
349   const coff_section *sec = toSec(Sec);
350   Result = sec->Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA;
351   return object_error::success;
352 }
353 
isSectionBSS(DataRefImpl Sec,bool & Result) const354 error_code COFFObjectFile::isSectionBSS(DataRefImpl Sec,
355                                         bool &Result) const {
356   const coff_section *sec = toSec(Sec);
357   Result = sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA;
358   return object_error::success;
359 }
360 
isSectionRequiredForExecution(DataRefImpl Sec,bool & Result) const361 error_code COFFObjectFile::isSectionRequiredForExecution(DataRefImpl Sec,
362                                                          bool &Result) const {
363   // FIXME: Unimplemented
364   Result = true;
365   return object_error::success;
366 }
367 
isSectionVirtual(DataRefImpl Sec,bool & Result) const368 error_code COFFObjectFile::isSectionVirtual(DataRefImpl Sec,
369                                            bool &Result) const {
370   const coff_section *sec = toSec(Sec);
371   Result = sec->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA;
372   return object_error::success;
373 }
374 
isSectionZeroInit(DataRefImpl Sec,bool & Result) const375 error_code COFFObjectFile::isSectionZeroInit(DataRefImpl Sec,
376                                              bool &Result) const {
377   // FIXME: Unimplemented
378   Result = false;
379   return object_error::success;
380 }
381 
sectionContainsSymbol(DataRefImpl Sec,DataRefImpl Symb,bool & Result) const382 error_code COFFObjectFile::sectionContainsSymbol(DataRefImpl Sec,
383                                                  DataRefImpl Symb,
384                                                  bool &Result) const {
385   const coff_section *sec = toSec(Sec);
386   const coff_symbol *symb = toSymb(Symb);
387   const coff_section *symb_sec = 0;
388   if (error_code ec = getSection(symb->SectionNumber, symb_sec)) return ec;
389   if (symb_sec == sec)
390     Result = true;
391   else
392     Result = false;
393   return object_error::success;
394 }
395 
getSectionRelBegin(DataRefImpl Sec) const396 relocation_iterator COFFObjectFile::getSectionRelBegin(DataRefImpl Sec) const {
397   const coff_section *sec = toSec(Sec);
398   DataRefImpl ret;
399   if (sec->NumberOfRelocations == 0)
400     ret.p = 0;
401   else
402     ret.p = reinterpret_cast<uintptr_t>(base() + sec->PointerToRelocations);
403 
404   return relocation_iterator(RelocationRef(ret, this));
405 }
406 
getSectionRelEnd(DataRefImpl Sec) const407 relocation_iterator COFFObjectFile::getSectionRelEnd(DataRefImpl Sec) const {
408   const coff_section *sec = toSec(Sec);
409   DataRefImpl ret;
410   if (sec->NumberOfRelocations == 0)
411     ret.p = 0;
412   else
413     ret.p = reinterpret_cast<uintptr_t>(
414               reinterpret_cast<const coff_relocation*>(
415                 base() + sec->PointerToRelocations)
416               + sec->NumberOfRelocations);
417 
418   return relocation_iterator(RelocationRef(ret, this));
419 }
420 
COFFObjectFile(MemoryBuffer * Object,error_code & ec)421 COFFObjectFile::COFFObjectFile(MemoryBuffer *Object, error_code &ec)
422   : ObjectFile(Binary::ID_COFF, Object, ec)
423   , Header(0)
424   , SectionTable(0)
425   , SymbolTable(0)
426   , StringTable(0)
427   , StringTableSize(0) {
428   // Check that we at least have enough room for a header.
429   if (!checkSize(Data, ec, sizeof(coff_file_header))) return;
430 
431   // The actual starting location of the COFF header in the file. This can be
432   // non-zero in PE/COFF files.
433   uint64_t HeaderStart = 0;
434 
435   // Check if this is a PE/COFF file.
436   if (base()[0] == 0x4d && base()[1] == 0x5a) {
437     // PE/COFF, seek through MS-DOS compatibility stub and 4-byte
438     // PE signature to find 'normal' COFF header.
439     if (!checkSize(Data, ec, 0x3c + 8)) return;
440     HeaderStart = *reinterpret_cast<const ulittle16_t *>(base() + 0x3c);
441     // Check the PE header. ("PE\0\0")
442     if (std::memcmp(base() + HeaderStart, "PE\0\0", 4) != 0) {
443       ec = object_error::parse_failed;
444       return;
445     }
446     HeaderStart += 4; // Skip the PE Header.
447   }
448 
449   Header = reinterpret_cast<const coff_file_header *>(base() + HeaderStart);
450   if (!checkAddr(Data, ec, uintptr_t(Header), sizeof(coff_file_header)))
451     return;
452 
453   SectionTable =
454     reinterpret_cast<const coff_section *>( base()
455                                           + HeaderStart
456                                           + sizeof(coff_file_header)
457                                           + Header->SizeOfOptionalHeader);
458   if (!checkAddr(Data, ec, uintptr_t(SectionTable),
459                  Header->NumberOfSections * sizeof(coff_section)))
460     return;
461 
462   if (Header->PointerToSymbolTable != 0) {
463     SymbolTable =
464       reinterpret_cast<const coff_symbol *>(base()
465                                             + Header->PointerToSymbolTable);
466     if (!checkAddr(Data, ec, uintptr_t(SymbolTable),
467                    Header->NumberOfSymbols * sizeof(coff_symbol)))
468       return;
469 
470     // Find string table.
471     StringTable = reinterpret_cast<const char *>(base())
472                   + Header->PointerToSymbolTable
473                   + Header->NumberOfSymbols * sizeof(coff_symbol);
474     if (!checkAddr(Data, ec, uintptr_t(StringTable), sizeof(ulittle32_t)))
475       return;
476 
477     StringTableSize = *reinterpret_cast<const ulittle32_t *>(StringTable);
478     if (!checkAddr(Data, ec, uintptr_t(StringTable), StringTableSize))
479       return;
480     // Check that the string table is null terminated if has any in it.
481     if (StringTableSize < 4
482         || (StringTableSize > 4 && StringTable[StringTableSize - 1] != 0)) {
483       ec = object_error::parse_failed;
484       return;
485     }
486   }
487 
488   ec = object_error::success;
489 }
490 
begin_symbols() const491 symbol_iterator COFFObjectFile::begin_symbols() const {
492   DataRefImpl ret;
493   ret.p = reinterpret_cast<intptr_t>(SymbolTable);
494   return symbol_iterator(SymbolRef(ret, this));
495 }
496 
end_symbols() const497 symbol_iterator COFFObjectFile::end_symbols() const {
498   // The symbol table ends where the string table begins.
499   DataRefImpl ret;
500   ret.p = reinterpret_cast<intptr_t>(StringTable);
501   return symbol_iterator(SymbolRef(ret, this));
502 }
503 
begin_dynamic_symbols() const504 symbol_iterator COFFObjectFile::begin_dynamic_symbols() const {
505   // TODO: implement
506   report_fatal_error("Dynamic symbols unimplemented in COFFObjectFile");
507 }
508 
end_dynamic_symbols() const509 symbol_iterator COFFObjectFile::end_dynamic_symbols() const {
510   // TODO: implement
511   report_fatal_error("Dynamic symbols unimplemented in COFFObjectFile");
512 }
513 
begin_libraries_needed() const514 library_iterator COFFObjectFile::begin_libraries_needed() const {
515   // TODO: implement
516   report_fatal_error("Libraries needed unimplemented in COFFObjectFile");
517 }
518 
end_libraries_needed() const519 library_iterator COFFObjectFile::end_libraries_needed() const {
520   // TODO: implement
521   report_fatal_error("Libraries needed unimplemented in COFFObjectFile");
522 }
523 
getLoadName() const524 StringRef COFFObjectFile::getLoadName() const {
525   // COFF does not have this field.
526   return "";
527 }
528 
529 
begin_sections() const530 section_iterator COFFObjectFile::begin_sections() const {
531   DataRefImpl ret;
532   ret.p = reinterpret_cast<intptr_t>(SectionTable);
533   return section_iterator(SectionRef(ret, this));
534 }
535 
end_sections() const536 section_iterator COFFObjectFile::end_sections() const {
537   DataRefImpl ret;
538   ret.p = reinterpret_cast<intptr_t>(SectionTable + Header->NumberOfSections);
539   return section_iterator(SectionRef(ret, this));
540 }
541 
getBytesInAddress() const542 uint8_t COFFObjectFile::getBytesInAddress() const {
543   return getArch() == Triple::x86_64 ? 8 : 4;
544 }
545 
getFileFormatName() const546 StringRef COFFObjectFile::getFileFormatName() const {
547   switch(Header->Machine) {
548   case COFF::IMAGE_FILE_MACHINE_I386:
549     return "COFF-i386";
550   case COFF::IMAGE_FILE_MACHINE_AMD64:
551     return "COFF-x86-64";
552   default:
553     return "COFF-<unknown arch>";
554   }
555 }
556 
getArch() const557 unsigned COFFObjectFile::getArch() const {
558   switch(Header->Machine) {
559   case COFF::IMAGE_FILE_MACHINE_I386:
560     return Triple::x86;
561   case COFF::IMAGE_FILE_MACHINE_AMD64:
562     return Triple::x86_64;
563   default:
564     return Triple::UnknownArch;
565   }
566 }
567 
getHeader(const coff_file_header * & Res) const568 error_code COFFObjectFile::getHeader(const coff_file_header *&Res) const {
569   Res = Header;
570   return object_error::success;
571 }
572 
getSection(int32_t index,const coff_section * & Result) const573 error_code COFFObjectFile::getSection(int32_t index,
574                                       const coff_section *&Result) const {
575   // Check for special index values.
576   if (index == COFF::IMAGE_SYM_UNDEFINED ||
577       index == COFF::IMAGE_SYM_ABSOLUTE ||
578       index == COFF::IMAGE_SYM_DEBUG)
579     Result = NULL;
580   else if (index > 0 && index <= Header->NumberOfSections)
581     // We already verified the section table data, so no need to check again.
582     Result = SectionTable + (index - 1);
583   else
584     return object_error::parse_failed;
585   return object_error::success;
586 }
587 
getString(uint32_t offset,StringRef & Result) const588 error_code COFFObjectFile::getString(uint32_t offset,
589                                      StringRef &Result) const {
590   if (StringTableSize <= 4)
591     // Tried to get a string from an empty string table.
592     return object_error::parse_failed;
593   if (offset >= StringTableSize)
594     return object_error::unexpected_eof;
595   Result = StringRef(StringTable + offset);
596   return object_error::success;
597 }
598 
getSymbol(uint32_t index,const coff_symbol * & Result) const599 error_code COFFObjectFile::getSymbol(uint32_t index,
600                                      const coff_symbol *&Result) const {
601   if (index < Header->NumberOfSymbols)
602     Result = SymbolTable + index;
603   else
604     return object_error::parse_failed;
605   return object_error::success;
606 }
607 
getSymbolName(const coff_symbol * symbol,StringRef & Res) const608 error_code COFFObjectFile::getSymbolName(const coff_symbol *symbol,
609                                          StringRef &Res) const {
610   // Check for string table entry. First 4 bytes are 0.
611   if (symbol->Name.Offset.Zeroes == 0) {
612     uint32_t Offset = symbol->Name.Offset.Offset;
613     if (error_code ec = getString(Offset, Res))
614       return ec;
615     return object_error::success;
616   }
617 
618   if (symbol->Name.ShortName[7] == 0)
619     // Null terminated, let ::strlen figure out the length.
620     Res = StringRef(symbol->Name.ShortName);
621   else
622     // Not null terminated, use all 8 bytes.
623     Res = StringRef(symbol->Name.ShortName, 8);
624   return object_error::success;
625 }
626 
getSymbolAuxData(const coff_symbol * symbol) const627 ArrayRef<uint8_t> COFFObjectFile::getSymbolAuxData(
628                                   const coff_symbol *symbol) const {
629   const uint8_t *aux = NULL;
630 
631   if ( symbol->NumberOfAuxSymbols > 0 ) {
632   // AUX data comes immediately after the symbol in COFF
633     aux = reinterpret_cast<const uint8_t *>(symbol + 1);
634 # ifndef NDEBUG
635     // Verify that the aux symbol points to a valid entry in the symbol table.
636     uintptr_t offset = uintptr_t(aux) - uintptr_t(base());
637     if (offset < Header->PointerToSymbolTable
638         || offset >= Header->PointerToSymbolTable
639            + (Header->NumberOfSymbols * sizeof(coff_symbol)))
640       report_fatal_error("Aux Symbol data was outside of symbol table.");
641 
642     assert((offset - Header->PointerToSymbolTable) % sizeof(coff_symbol)
643          == 0 && "Aux Symbol data did not point to the beginning of a symbol");
644 # endif
645   }
646   return ArrayRef<uint8_t>(aux, symbol->NumberOfAuxSymbols * sizeof(coff_symbol));
647 }
648 
getSectionName(const coff_section * Sec,StringRef & Res) const649 error_code COFFObjectFile::getSectionName(const coff_section *Sec,
650                                           StringRef &Res) const {
651   StringRef Name;
652   if (Sec->Name[7] == 0)
653     // Null terminated, let ::strlen figure out the length.
654     Name = Sec->Name;
655   else
656     // Not null terminated, use all 8 bytes.
657     Name = StringRef(Sec->Name, 8);
658 
659   // Check for string table entry. First byte is '/'.
660   if (Name[0] == '/') {
661     uint32_t Offset;
662     if (Name.substr(1).getAsInteger(10, Offset))
663       return object_error::parse_failed;
664     if (error_code ec = getString(Offset, Name))
665       return ec;
666   }
667 
668   Res = Name;
669   return object_error::success;
670 }
671 
getSectionContents(const coff_section * Sec,ArrayRef<uint8_t> & Res) const672 error_code COFFObjectFile::getSectionContents(const coff_section *Sec,
673                                               ArrayRef<uint8_t> &Res) const {
674   // The only thing that we need to verify is that the contents is contained
675   // within the file bounds. We don't need to make sure it doesn't cover other
676   // data, as there's nothing that says that is not allowed.
677   uintptr_t ConStart = uintptr_t(base()) + Sec->PointerToRawData;
678   uintptr_t ConEnd = ConStart + Sec->SizeOfRawData;
679   if (ConEnd > uintptr_t(Data->getBufferEnd()))
680     return object_error::parse_failed;
681   Res = ArrayRef<uint8_t>(reinterpret_cast<const unsigned char*>(ConStart),
682                           Sec->SizeOfRawData);
683   return object_error::success;
684 }
685 
toRel(DataRefImpl Rel) const686 const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const {
687   return reinterpret_cast<const coff_relocation*>(Rel.p);
688 }
getRelocationNext(DataRefImpl Rel,RelocationRef & Res) const689 error_code COFFObjectFile::getRelocationNext(DataRefImpl Rel,
690                                              RelocationRef &Res) const {
691   Rel.p = reinterpret_cast<uintptr_t>(
692             reinterpret_cast<const coff_relocation*>(Rel.p) + 1);
693   Res = RelocationRef(Rel, this);
694   return object_error::success;
695 }
getRelocationAddress(DataRefImpl Rel,uint64_t & Res) const696 error_code COFFObjectFile::getRelocationAddress(DataRefImpl Rel,
697                                                 uint64_t &Res) const {
698   Res = toRel(Rel)->VirtualAddress;
699   return object_error::success;
700 }
getRelocationOffset(DataRefImpl Rel,uint64_t & Res) const701 error_code COFFObjectFile::getRelocationOffset(DataRefImpl Rel,
702                                                uint64_t &Res) const {
703   Res = toRel(Rel)->VirtualAddress;
704   return object_error::success;
705 }
getRelocationSymbol(DataRefImpl Rel,SymbolRef & Res) const706 error_code COFFObjectFile::getRelocationSymbol(DataRefImpl Rel,
707                                                SymbolRef &Res) const {
708   const coff_relocation* R = toRel(Rel);
709   DataRefImpl Symb;
710   Symb.p = reinterpret_cast<uintptr_t>(SymbolTable + R->SymbolTableIndex);
711   Res = SymbolRef(Symb, this);
712   return object_error::success;
713 }
getRelocationType(DataRefImpl Rel,uint64_t & Res) const714 error_code COFFObjectFile::getRelocationType(DataRefImpl Rel,
715                                              uint64_t &Res) const {
716   const coff_relocation* R = toRel(Rel);
717   Res = R->Type;
718   return object_error::success;
719 }
720 
getCOFFSection(section_iterator & It) const721 const coff_section *COFFObjectFile::getCOFFSection(section_iterator &It) const {
722   return toSec(It->getRawDataRefImpl());
723 }
724 
getCOFFSymbol(symbol_iterator & It) const725 const coff_symbol *COFFObjectFile::getCOFFSymbol(symbol_iterator &It) const {
726   return toSymb(It->getRawDataRefImpl());
727 }
728 
getCOFFRelocation(relocation_iterator & It) const729 const coff_relocation *COFFObjectFile::getCOFFRelocation(
730                                              relocation_iterator &It) const {
731   return toRel(It->getRawDataRefImpl());
732 }
733 
734 
735 #define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(enum) \
736   case COFF::enum: res = #enum; break;
737 
getRelocationTypeName(DataRefImpl Rel,SmallVectorImpl<char> & Result) const738 error_code COFFObjectFile::getRelocationTypeName(DataRefImpl Rel,
739                                           SmallVectorImpl<char> &Result) const {
740   const coff_relocation *reloc = toRel(Rel);
741   StringRef res;
742   switch (Header->Machine) {
743   case COFF::IMAGE_FILE_MACHINE_AMD64:
744     switch (reloc->Type) {
745     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ABSOLUTE);
746     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR64);
747     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32);
748     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32NB);
749     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32);
750     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_1);
751     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_2);
752     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_3);
753     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_4);
754     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_5);
755     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECTION);
756     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL);
757     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL7);
758     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_TOKEN);
759     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SREL32);
760     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_PAIR);
761     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SSPAN32);
762     default:
763       res = "Unknown";
764     }
765     break;
766   case COFF::IMAGE_FILE_MACHINE_I386:
767     switch (reloc->Type) {
768     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_ABSOLUTE);
769     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR16);
770     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL16);
771     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32);
772     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32NB);
773     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SEG12);
774     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECTION);
775     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL);
776     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_TOKEN);
777     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL7);
778     LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL32);
779     default:
780       res = "Unknown";
781     }
782     break;
783   default:
784     res = "Unknown";
785   }
786   Result.append(res.begin(), res.end());
787   return object_error::success;
788 }
789 
790 #undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME
791 
getRelocationAdditionalInfo(DataRefImpl Rel,int64_t & Res) const792 error_code COFFObjectFile::getRelocationAdditionalInfo(DataRefImpl Rel,
793                                                        int64_t &Res) const {
794   Res = 0;
795   return object_error::success;
796 }
getRelocationValueString(DataRefImpl Rel,SmallVectorImpl<char> & Result) const797 error_code COFFObjectFile::getRelocationValueString(DataRefImpl Rel,
798                                           SmallVectorImpl<char> &Result) const {
799   const coff_relocation *reloc = toRel(Rel);
800   const coff_symbol *symb = 0;
801   if (error_code ec = getSymbol(reloc->SymbolTableIndex, symb)) return ec;
802   DataRefImpl sym;
803   sym.p = reinterpret_cast<uintptr_t>(symb);
804   StringRef symname;
805   if (error_code ec = getSymbolName(sym, symname)) return ec;
806   Result.append(symname.begin(), symname.end());
807   return object_error::success;
808 }
809 
getLibraryNext(DataRefImpl LibData,LibraryRef & Result) const810 error_code COFFObjectFile::getLibraryNext(DataRefImpl LibData,
811                                           LibraryRef &Result) const {
812   report_fatal_error("getLibraryNext not implemented in COFFObjectFile");
813 }
814 
getLibraryPath(DataRefImpl LibData,StringRef & Result) const815 error_code COFFObjectFile::getLibraryPath(DataRefImpl LibData,
816                                           StringRef &Result) const {
817   report_fatal_error("getLibraryPath not implemented in COFFObjectFile");
818 }
819 
820 namespace llvm {
821 
createCOFFObjectFile(MemoryBuffer * Object)822   ObjectFile *ObjectFile::createCOFFObjectFile(MemoryBuffer *Object) {
823     error_code ec;
824     return new COFFObjectFile(Object, ec);
825   }
826 
827 } // end namespace llvm
828