COFFObjectFile.cpp 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891
  1. //===- COFFObjectFile.cpp - COFF object file implementation ---------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file declares the COFFObjectFile class.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/ADT/ArrayRef.h"
  13. #include "llvm/ADT/StringRef.h"
  14. #include "llvm/ADT/StringSwitch.h"
  15. #include "llvm/ADT/Triple.h"
  16. #include "llvm/ADT/iterator_range.h"
  17. #include "llvm/BinaryFormat/COFF.h"
  18. #include "llvm/Object/Binary.h"
  19. #include "llvm/Object/COFF.h"
  20. #include "llvm/Object/Error.h"
  21. #include "llvm/Object/ObjectFile.h"
  22. #include "llvm/Support/BinaryStreamReader.h"
  23. #include "llvm/Support/Endian.h"
  24. #include "llvm/Support/Error.h"
  25. #include "llvm/Support/ErrorHandling.h"
  26. #include "llvm/Support/MathExtras.h"
  27. #include "llvm/Support/MemoryBuffer.h"
  28. #include <algorithm>
  29. #include <cassert>
  30. #include <cinttypes>
  31. #include <cstddef>
  32. #include <cstring>
  33. #include <limits>
  34. #include <memory>
  35. #include <system_error>
  36. using namespace llvm;
  37. using namespace object;
  38. using support::ulittle16_t;
  39. using support::ulittle32_t;
  40. using support::ulittle64_t;
  41. using support::little16_t;
  42. // Returns false if size is greater than the buffer size. And sets ec.
  43. static bool checkSize(MemoryBufferRef M, std::error_code &EC, uint64_t Size) {
  44. if (M.getBufferSize() < Size) {
  45. EC = object_error::unexpected_eof;
  46. return false;
  47. }
  48. return true;
  49. }
  50. // Sets Obj unless any bytes in [addr, addr + size) fall outsize of m.
  51. // Returns unexpected_eof if error.
  52. template <typename T>
  53. static Error getObject(const T *&Obj, MemoryBufferRef M, const void *Ptr,
  54. const uint64_t Size = sizeof(T)) {
  55. uintptr_t Addr = reinterpret_cast<uintptr_t>(Ptr);
  56. if (Error E = Binary::checkOffset(M, Addr, Size))
  57. return E;
  58. Obj = reinterpret_cast<const T *>(Addr);
  59. return Error::success();
  60. }
  61. // Decode a string table entry in base 64 (//AAAAAA). Expects \arg Str without
  62. // prefixed slashes.
  63. static bool decodeBase64StringEntry(StringRef Str, uint32_t &Result) {
  64. assert(Str.size() <= 6 && "String too long, possible overflow.");
  65. if (Str.size() > 6)
  66. return true;
  67. uint64_t Value = 0;
  68. while (!Str.empty()) {
  69. unsigned CharVal;
  70. if (Str[0] >= 'A' && Str[0] <= 'Z') // 0..25
  71. CharVal = Str[0] - 'A';
  72. else if (Str[0] >= 'a' && Str[0] <= 'z') // 26..51
  73. CharVal = Str[0] - 'a' + 26;
  74. else if (Str[0] >= '0' && Str[0] <= '9') // 52..61
  75. CharVal = Str[0] - '0' + 52;
  76. else if (Str[0] == '+') // 62
  77. CharVal = 62;
  78. else if (Str[0] == '/') // 63
  79. CharVal = 63;
  80. else
  81. return true;
  82. Value = (Value * 64) + CharVal;
  83. Str = Str.substr(1);
  84. }
  85. if (Value > std::numeric_limits<uint32_t>::max())
  86. return true;
  87. Result = static_cast<uint32_t>(Value);
  88. return false;
  89. }
  90. template <typename coff_symbol_type>
  91. const coff_symbol_type *COFFObjectFile::toSymb(DataRefImpl Ref) const {
  92. const coff_symbol_type *Addr =
  93. reinterpret_cast<const coff_symbol_type *>(Ref.p);
  94. assert(!checkOffset(Data, reinterpret_cast<uintptr_t>(Addr), sizeof(*Addr)));
  95. #ifndef NDEBUG
  96. // Verify that the symbol points to a valid entry in the symbol table.
  97. uintptr_t Offset =
  98. reinterpret_cast<uintptr_t>(Addr) - reinterpret_cast<uintptr_t>(base());
  99. assert((Offset - getPointerToSymbolTable()) % sizeof(coff_symbol_type) == 0 &&
  100. "Symbol did not point to the beginning of a symbol");
  101. #endif
  102. return Addr;
  103. }
  104. const coff_section *COFFObjectFile::toSec(DataRefImpl Ref) const {
  105. const coff_section *Addr = reinterpret_cast<const coff_section*>(Ref.p);
  106. #ifndef NDEBUG
  107. // Verify that the section points to a valid entry in the section table.
  108. if (Addr < SectionTable || Addr >= (SectionTable + getNumberOfSections()))
  109. report_fatal_error("Section was outside of section table.");
  110. uintptr_t Offset = reinterpret_cast<uintptr_t>(Addr) -
  111. reinterpret_cast<uintptr_t>(SectionTable);
  112. assert(Offset % sizeof(coff_section) == 0 &&
  113. "Section did not point to the beginning of a section");
  114. #endif
  115. return Addr;
  116. }
  117. void COFFObjectFile::moveSymbolNext(DataRefImpl &Ref) const {
  118. auto End = reinterpret_cast<uintptr_t>(StringTable);
  119. if (SymbolTable16) {
  120. const coff_symbol16 *Symb = toSymb<coff_symbol16>(Ref);
  121. Symb += 1 + Symb->NumberOfAuxSymbols;
  122. Ref.p = std::min(reinterpret_cast<uintptr_t>(Symb), End);
  123. } else if (SymbolTable32) {
  124. const coff_symbol32 *Symb = toSymb<coff_symbol32>(Ref);
  125. Symb += 1 + Symb->NumberOfAuxSymbols;
  126. Ref.p = std::min(reinterpret_cast<uintptr_t>(Symb), End);
  127. } else {
  128. llvm_unreachable("no symbol table pointer!");
  129. }
  130. }
  131. Expected<StringRef> COFFObjectFile::getSymbolName(DataRefImpl Ref) const {
  132. return getSymbolName(getCOFFSymbol(Ref));
  133. }
  134. uint64_t COFFObjectFile::getSymbolValueImpl(DataRefImpl Ref) const {
  135. return getCOFFSymbol(Ref).getValue();
  136. }
  137. uint32_t COFFObjectFile::getSymbolAlignment(DataRefImpl Ref) const {
  138. // MSVC/link.exe seems to align symbols to the next-power-of-2
  139. // up to 32 bytes.
  140. COFFSymbolRef Symb = getCOFFSymbol(Ref);
  141. return std::min(uint64_t(32), PowerOf2Ceil(Symb.getValue()));
  142. }
  143. Expected<uint64_t> COFFObjectFile::getSymbolAddress(DataRefImpl Ref) const {
  144. uint64_t Result = cantFail(getSymbolValue(Ref));
  145. COFFSymbolRef Symb = getCOFFSymbol(Ref);
  146. int32_t SectionNumber = Symb.getSectionNumber();
  147. if (Symb.isAnyUndefined() || Symb.isCommon() ||
  148. COFF::isReservedSectionNumber(SectionNumber))
  149. return Result;
  150. Expected<const coff_section *> Section = getSection(SectionNumber);
  151. if (!Section)
  152. return Section.takeError();
  153. Result += (*Section)->VirtualAddress;
  154. // The section VirtualAddress does not include ImageBase, and we want to
  155. // return virtual addresses.
  156. Result += getImageBase();
  157. return Result;
  158. }
  159. Expected<SymbolRef::Type> COFFObjectFile::getSymbolType(DataRefImpl Ref) const {
  160. COFFSymbolRef Symb = getCOFFSymbol(Ref);
  161. int32_t SectionNumber = Symb.getSectionNumber();
  162. if (Symb.getComplexType() == COFF::IMAGE_SYM_DTYPE_FUNCTION)
  163. return SymbolRef::ST_Function;
  164. if (Symb.isAnyUndefined())
  165. return SymbolRef::ST_Unknown;
  166. if (Symb.isCommon())
  167. return SymbolRef::ST_Data;
  168. if (Symb.isFileRecord())
  169. return SymbolRef::ST_File;
  170. // TODO: perhaps we need a new symbol type ST_Section.
  171. if (SectionNumber == COFF::IMAGE_SYM_DEBUG || Symb.isSectionDefinition())
  172. return SymbolRef::ST_Debug;
  173. if (!COFF::isReservedSectionNumber(SectionNumber))
  174. return SymbolRef::ST_Data;
  175. return SymbolRef::ST_Other;
  176. }
  177. Expected<uint32_t> COFFObjectFile::getSymbolFlags(DataRefImpl Ref) const {
  178. COFFSymbolRef Symb = getCOFFSymbol(Ref);
  179. uint32_t Result = SymbolRef::SF_None;
  180. if (Symb.isExternal() || Symb.isWeakExternal())
  181. Result |= SymbolRef::SF_Global;
  182. if (const coff_aux_weak_external *AWE = Symb.getWeakExternal()) {
  183. Result |= SymbolRef::SF_Weak;
  184. if (AWE->Characteristics != COFF::IMAGE_WEAK_EXTERN_SEARCH_ALIAS)
  185. Result |= SymbolRef::SF_Undefined;
  186. }
  187. if (Symb.getSectionNumber() == COFF::IMAGE_SYM_ABSOLUTE)
  188. Result |= SymbolRef::SF_Absolute;
  189. if (Symb.isFileRecord())
  190. Result |= SymbolRef::SF_FormatSpecific;
  191. if (Symb.isSectionDefinition())
  192. Result |= SymbolRef::SF_FormatSpecific;
  193. if (Symb.isCommon())
  194. Result |= SymbolRef::SF_Common;
  195. if (Symb.isUndefined())
  196. Result |= SymbolRef::SF_Undefined;
  197. return Result;
  198. }
  199. uint64_t COFFObjectFile::getCommonSymbolSizeImpl(DataRefImpl Ref) const {
  200. COFFSymbolRef Symb = getCOFFSymbol(Ref);
  201. return Symb.getValue();
  202. }
  203. Expected<section_iterator>
  204. COFFObjectFile::getSymbolSection(DataRefImpl Ref) const {
  205. COFFSymbolRef Symb = getCOFFSymbol(Ref);
  206. if (COFF::isReservedSectionNumber(Symb.getSectionNumber()))
  207. return section_end();
  208. Expected<const coff_section *> Sec = getSection(Symb.getSectionNumber());
  209. if (!Sec)
  210. return Sec.takeError();
  211. DataRefImpl Ret;
  212. Ret.p = reinterpret_cast<uintptr_t>(*Sec);
  213. return section_iterator(SectionRef(Ret, this));
  214. }
  215. unsigned COFFObjectFile::getSymbolSectionID(SymbolRef Sym) const {
  216. COFFSymbolRef Symb = getCOFFSymbol(Sym.getRawDataRefImpl());
  217. return Symb.getSectionNumber();
  218. }
  219. void COFFObjectFile::moveSectionNext(DataRefImpl &Ref) const {
  220. const coff_section *Sec = toSec(Ref);
  221. Sec += 1;
  222. Ref.p = reinterpret_cast<uintptr_t>(Sec);
  223. }
  224. Expected<StringRef> COFFObjectFile::getSectionName(DataRefImpl Ref) const {
  225. const coff_section *Sec = toSec(Ref);
  226. return getSectionName(Sec);
  227. }
  228. uint64_t COFFObjectFile::getSectionAddress(DataRefImpl Ref) const {
  229. const coff_section *Sec = toSec(Ref);
  230. uint64_t Result = Sec->VirtualAddress;
  231. // The section VirtualAddress does not include ImageBase, and we want to
  232. // return virtual addresses.
  233. Result += getImageBase();
  234. return Result;
  235. }
  236. uint64_t COFFObjectFile::getSectionIndex(DataRefImpl Sec) const {
  237. return toSec(Sec) - SectionTable;
  238. }
  239. uint64_t COFFObjectFile::getSectionSize(DataRefImpl Ref) const {
  240. return getSectionSize(toSec(Ref));
  241. }
  242. Expected<ArrayRef<uint8_t>>
  243. COFFObjectFile::getSectionContents(DataRefImpl Ref) const {
  244. const coff_section *Sec = toSec(Ref);
  245. ArrayRef<uint8_t> Res;
  246. if (Error E = getSectionContents(Sec, Res))
  247. return std::move(E);
  248. return Res;
  249. }
  250. uint64_t COFFObjectFile::getSectionAlignment(DataRefImpl Ref) const {
  251. const coff_section *Sec = toSec(Ref);
  252. return Sec->getAlignment();
  253. }
  254. bool COFFObjectFile::isSectionCompressed(DataRefImpl Sec) const {
  255. return false;
  256. }
  257. bool COFFObjectFile::isSectionText(DataRefImpl Ref) const {
  258. const coff_section *Sec = toSec(Ref);
  259. return Sec->Characteristics & COFF::IMAGE_SCN_CNT_CODE;
  260. }
  261. bool COFFObjectFile::isSectionData(DataRefImpl Ref) const {
  262. const coff_section *Sec = toSec(Ref);
  263. return Sec->Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA;
  264. }
  265. bool COFFObjectFile::isSectionBSS(DataRefImpl Ref) const {
  266. const coff_section *Sec = toSec(Ref);
  267. const uint32_t BssFlags = COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA |
  268. COFF::IMAGE_SCN_MEM_READ |
  269. COFF::IMAGE_SCN_MEM_WRITE;
  270. return (Sec->Characteristics & BssFlags) == BssFlags;
  271. }
  272. // The .debug sections are the only debug sections for COFF
  273. // (\see MCObjectFileInfo.cpp).
  274. bool COFFObjectFile::isDebugSection(DataRefImpl Ref) const {
  275. Expected<StringRef> SectionNameOrErr = getSectionName(Ref);
  276. if (!SectionNameOrErr) {
  277. // TODO: Report the error message properly.
  278. consumeError(SectionNameOrErr.takeError());
  279. return false;
  280. }
  281. StringRef SectionName = SectionNameOrErr.get();
  282. return SectionName.startswith(".debug");
  283. }
  284. unsigned COFFObjectFile::getSectionID(SectionRef Sec) const {
  285. uintptr_t Offset =
  286. Sec.getRawDataRefImpl().p - reinterpret_cast<uintptr_t>(SectionTable);
  287. assert((Offset % sizeof(coff_section)) == 0);
  288. return (Offset / sizeof(coff_section)) + 1;
  289. }
  290. bool COFFObjectFile::isSectionVirtual(DataRefImpl Ref) const {
  291. const coff_section *Sec = toSec(Ref);
  292. // In COFF, a virtual section won't have any in-file
  293. // content, so the file pointer to the content will be zero.
  294. return Sec->PointerToRawData == 0;
  295. }
  296. static uint32_t getNumberOfRelocations(const coff_section *Sec,
  297. MemoryBufferRef M, const uint8_t *base) {
  298. // The field for the number of relocations in COFF section table is only
  299. // 16-bit wide. If a section has more than 65535 relocations, 0xFFFF is set to
  300. // NumberOfRelocations field, and the actual relocation count is stored in the
  301. // VirtualAddress field in the first relocation entry.
  302. if (Sec->hasExtendedRelocations()) {
  303. const coff_relocation *FirstReloc;
  304. if (Error E = getObject(FirstReloc, M,
  305. reinterpret_cast<const coff_relocation *>(
  306. base + Sec->PointerToRelocations))) {
  307. consumeError(std::move(E));
  308. return 0;
  309. }
  310. // -1 to exclude this first relocation entry.
  311. return FirstReloc->VirtualAddress - 1;
  312. }
  313. return Sec->NumberOfRelocations;
  314. }
  315. static const coff_relocation *
  316. getFirstReloc(const coff_section *Sec, MemoryBufferRef M, const uint8_t *Base) {
  317. uint64_t NumRelocs = getNumberOfRelocations(Sec, M, Base);
  318. if (!NumRelocs)
  319. return nullptr;
  320. auto begin = reinterpret_cast<const coff_relocation *>(
  321. Base + Sec->PointerToRelocations);
  322. if (Sec->hasExtendedRelocations()) {
  323. // Skip the first relocation entry repurposed to store the number of
  324. // relocations.
  325. begin++;
  326. }
  327. if (auto E = Binary::checkOffset(M, reinterpret_cast<uintptr_t>(begin),
  328. sizeof(coff_relocation) * NumRelocs)) {
  329. consumeError(std::move(E));
  330. return nullptr;
  331. }
  332. return begin;
  333. }
  334. relocation_iterator COFFObjectFile::section_rel_begin(DataRefImpl Ref) const {
  335. const coff_section *Sec = toSec(Ref);
  336. const coff_relocation *begin = getFirstReloc(Sec, Data, base());
  337. if (begin && Sec->VirtualAddress != 0)
  338. report_fatal_error("Sections with relocations should have an address of 0");
  339. DataRefImpl Ret;
  340. Ret.p = reinterpret_cast<uintptr_t>(begin);
  341. return relocation_iterator(RelocationRef(Ret, this));
  342. }
  343. relocation_iterator COFFObjectFile::section_rel_end(DataRefImpl Ref) const {
  344. const coff_section *Sec = toSec(Ref);
  345. const coff_relocation *I = getFirstReloc(Sec, Data, base());
  346. if (I)
  347. I += getNumberOfRelocations(Sec, Data, base());
  348. DataRefImpl Ret;
  349. Ret.p = reinterpret_cast<uintptr_t>(I);
  350. return relocation_iterator(RelocationRef(Ret, this));
  351. }
  352. // Initialize the pointer to the symbol table.
  353. Error COFFObjectFile::initSymbolTablePtr() {
  354. if (COFFHeader)
  355. if (Error E = getObject(
  356. SymbolTable16, Data, base() + getPointerToSymbolTable(),
  357. (uint64_t)getNumberOfSymbols() * getSymbolTableEntrySize()))
  358. return E;
  359. if (COFFBigObjHeader)
  360. if (Error E = getObject(
  361. SymbolTable32, Data, base() + getPointerToSymbolTable(),
  362. (uint64_t)getNumberOfSymbols() * getSymbolTableEntrySize()))
  363. return E;
  364. // Find string table. The first four byte of the string table contains the
  365. // total size of the string table, including the size field itself. If the
  366. // string table is empty, the value of the first four byte would be 4.
  367. uint32_t StringTableOffset = getPointerToSymbolTable() +
  368. getNumberOfSymbols() * getSymbolTableEntrySize();
  369. const uint8_t *StringTableAddr = base() + StringTableOffset;
  370. const ulittle32_t *StringTableSizePtr;
  371. if (Error E = getObject(StringTableSizePtr, Data, StringTableAddr))
  372. return E;
  373. StringTableSize = *StringTableSizePtr;
  374. if (Error E = getObject(StringTable, Data, StringTableAddr, StringTableSize))
  375. return E;
  376. // Treat table sizes < 4 as empty because contrary to the PECOFF spec, some
  377. // tools like cvtres write a size of 0 for an empty table instead of 4.
  378. if (StringTableSize < 4)
  379. StringTableSize = 4;
  380. // Check that the string table is null terminated if has any in it.
  381. if (StringTableSize > 4 && StringTable[StringTableSize - 1] != 0)
  382. return errorCodeToError(object_error::parse_failed);
  383. return Error::success();
  384. }
  385. uint64_t COFFObjectFile::getImageBase() const {
  386. if (PE32Header)
  387. return PE32Header->ImageBase;
  388. else if (PE32PlusHeader)
  389. return PE32PlusHeader->ImageBase;
  390. // This actually comes up in practice.
  391. return 0;
  392. }
  393. // Returns the file offset for the given VA.
  394. Error COFFObjectFile::getVaPtr(uint64_t Addr, uintptr_t &Res) const {
  395. uint64_t ImageBase = getImageBase();
  396. uint64_t Rva = Addr - ImageBase;
  397. assert(Rva <= UINT32_MAX);
  398. return getRvaPtr((uint32_t)Rva, Res);
  399. }
  400. // Returns the file offset for the given RVA.
  401. Error COFFObjectFile::getRvaPtr(uint32_t Addr, uintptr_t &Res) const {
  402. for (const SectionRef &S : sections()) {
  403. const coff_section *Section = getCOFFSection(S);
  404. uint32_t SectionStart = Section->VirtualAddress;
  405. uint32_t SectionEnd = Section->VirtualAddress + Section->VirtualSize;
  406. if (SectionStart <= Addr && Addr < SectionEnd) {
  407. uint32_t Offset = Addr - SectionStart;
  408. Res = reinterpret_cast<uintptr_t>(base()) + Section->PointerToRawData +
  409. Offset;
  410. return Error::success();
  411. }
  412. }
  413. return errorCodeToError(object_error::parse_failed);
  414. }
  415. Error COFFObjectFile::getRvaAndSizeAsBytes(uint32_t RVA, uint32_t Size,
  416. ArrayRef<uint8_t> &Contents) const {
  417. for (const SectionRef &S : sections()) {
  418. const coff_section *Section = getCOFFSection(S);
  419. uint32_t SectionStart = Section->VirtualAddress;
  420. // Check if this RVA is within the section bounds. Be careful about integer
  421. // overflow.
  422. uint32_t OffsetIntoSection = RVA - SectionStart;
  423. if (SectionStart <= RVA && OffsetIntoSection < Section->VirtualSize &&
  424. Size <= Section->VirtualSize - OffsetIntoSection) {
  425. uintptr_t Begin = reinterpret_cast<uintptr_t>(base()) +
  426. Section->PointerToRawData + OffsetIntoSection;
  427. Contents =
  428. ArrayRef<uint8_t>(reinterpret_cast<const uint8_t *>(Begin), Size);
  429. return Error::success();
  430. }
  431. }
  432. return errorCodeToError(object_error::parse_failed);
  433. }
  434. // Returns hint and name fields, assuming \p Rva is pointing to a Hint/Name
  435. // table entry.
  436. Error COFFObjectFile::getHintName(uint32_t Rva, uint16_t &Hint,
  437. StringRef &Name) const {
  438. uintptr_t IntPtr = 0;
  439. if (Error E = getRvaPtr(Rva, IntPtr))
  440. return E;
  441. const uint8_t *Ptr = reinterpret_cast<const uint8_t *>(IntPtr);
  442. Hint = *reinterpret_cast<const ulittle16_t *>(Ptr);
  443. Name = StringRef(reinterpret_cast<const char *>(Ptr + 2));
  444. return Error::success();
  445. }
  446. Error COFFObjectFile::getDebugPDBInfo(const debug_directory *DebugDir,
  447. const codeview::DebugInfo *&PDBInfo,
  448. StringRef &PDBFileName) const {
  449. ArrayRef<uint8_t> InfoBytes;
  450. if (Error E = getRvaAndSizeAsBytes(
  451. DebugDir->AddressOfRawData, DebugDir->SizeOfData, InfoBytes))
  452. return E;
  453. if (InfoBytes.size() < sizeof(*PDBInfo) + 1)
  454. return errorCodeToError(object_error::parse_failed);
  455. PDBInfo = reinterpret_cast<const codeview::DebugInfo *>(InfoBytes.data());
  456. InfoBytes = InfoBytes.drop_front(sizeof(*PDBInfo));
  457. PDBFileName = StringRef(reinterpret_cast<const char *>(InfoBytes.data()),
  458. InfoBytes.size());
  459. // Truncate the name at the first null byte. Ignore any padding.
  460. PDBFileName = PDBFileName.split('\0').first;
  461. return Error::success();
  462. }
  463. Error COFFObjectFile::getDebugPDBInfo(const codeview::DebugInfo *&PDBInfo,
  464. StringRef &PDBFileName) const {
  465. for (const debug_directory &D : debug_directories())
  466. if (D.Type == COFF::IMAGE_DEBUG_TYPE_CODEVIEW)
  467. return getDebugPDBInfo(&D, PDBInfo, PDBFileName);
  468. // If we get here, there is no PDB info to return.
  469. PDBInfo = nullptr;
  470. PDBFileName = StringRef();
  471. return Error::success();
  472. }
  473. // Find the import table.
  474. Error COFFObjectFile::initImportTablePtr() {
  475. // First, we get the RVA of the import table. If the file lacks a pointer to
  476. // the import table, do nothing.
  477. const data_directory *DataEntry = getDataDirectory(COFF::IMPORT_TABLE);
  478. if (!DataEntry)
  479. return Error::success();
  480. // Do nothing if the pointer to import table is NULL.
  481. if (DataEntry->RelativeVirtualAddress == 0)
  482. return Error::success();
  483. uint32_t ImportTableRva = DataEntry->RelativeVirtualAddress;
  484. // Find the section that contains the RVA. This is needed because the RVA is
  485. // the import table's memory address which is different from its file offset.
  486. uintptr_t IntPtr = 0;
  487. if (Error E = getRvaPtr(ImportTableRva, IntPtr))
  488. return E;
  489. if (Error E = checkOffset(Data, IntPtr, DataEntry->Size))
  490. return E;
  491. ImportDirectory = reinterpret_cast<
  492. const coff_import_directory_table_entry *>(IntPtr);
  493. return Error::success();
  494. }
  495. // Initializes DelayImportDirectory and NumberOfDelayImportDirectory.
  496. Error COFFObjectFile::initDelayImportTablePtr() {
  497. const data_directory *DataEntry =
  498. getDataDirectory(COFF::DELAY_IMPORT_DESCRIPTOR);
  499. if (!DataEntry)
  500. return Error::success();
  501. if (DataEntry->RelativeVirtualAddress == 0)
  502. return Error::success();
  503. uint32_t RVA = DataEntry->RelativeVirtualAddress;
  504. NumberOfDelayImportDirectory = DataEntry->Size /
  505. sizeof(delay_import_directory_table_entry) - 1;
  506. uintptr_t IntPtr = 0;
  507. if (Error E = getRvaPtr(RVA, IntPtr))
  508. return E;
  509. DelayImportDirectory = reinterpret_cast<
  510. const delay_import_directory_table_entry *>(IntPtr);
  511. return Error::success();
  512. }
  513. // Find the export table.
  514. Error COFFObjectFile::initExportTablePtr() {
  515. // First, we get the RVA of the export table. If the file lacks a pointer to
  516. // the export table, do nothing.
  517. const data_directory *DataEntry = getDataDirectory(COFF::EXPORT_TABLE);
  518. if (!DataEntry)
  519. return Error::success();
  520. // Do nothing if the pointer to export table is NULL.
  521. if (DataEntry->RelativeVirtualAddress == 0)
  522. return Error::success();
  523. uint32_t ExportTableRva = DataEntry->RelativeVirtualAddress;
  524. uintptr_t IntPtr = 0;
  525. if (Error E = getRvaPtr(ExportTableRva, IntPtr))
  526. return E;
  527. ExportDirectory =
  528. reinterpret_cast<const export_directory_table_entry *>(IntPtr);
  529. return Error::success();
  530. }
  531. Error COFFObjectFile::initBaseRelocPtr() {
  532. const data_directory *DataEntry =
  533. getDataDirectory(COFF::BASE_RELOCATION_TABLE);
  534. if (!DataEntry)
  535. return Error::success();
  536. if (DataEntry->RelativeVirtualAddress == 0)
  537. return Error::success();
  538. uintptr_t IntPtr = 0;
  539. if (Error E = getRvaPtr(DataEntry->RelativeVirtualAddress, IntPtr))
  540. return E;
  541. BaseRelocHeader = reinterpret_cast<const coff_base_reloc_block_header *>(
  542. IntPtr);
  543. BaseRelocEnd = reinterpret_cast<coff_base_reloc_block_header *>(
  544. IntPtr + DataEntry->Size);
  545. // FIXME: Verify the section containing BaseRelocHeader has at least
  546. // DataEntry->Size bytes after DataEntry->RelativeVirtualAddress.
  547. return Error::success();
  548. }
  549. Error COFFObjectFile::initDebugDirectoryPtr() {
  550. // Get the RVA of the debug directory. Do nothing if it does not exist.
  551. const data_directory *DataEntry = getDataDirectory(COFF::DEBUG_DIRECTORY);
  552. if (!DataEntry)
  553. return Error::success();
  554. // Do nothing if the RVA is NULL.
  555. if (DataEntry->RelativeVirtualAddress == 0)
  556. return Error::success();
  557. // Check that the size is a multiple of the entry size.
  558. if (DataEntry->Size % sizeof(debug_directory) != 0)
  559. return errorCodeToError(object_error::parse_failed);
  560. uintptr_t IntPtr = 0;
  561. if (Error E = getRvaPtr(DataEntry->RelativeVirtualAddress, IntPtr))
  562. return E;
  563. DebugDirectoryBegin = reinterpret_cast<const debug_directory *>(IntPtr);
  564. DebugDirectoryEnd = reinterpret_cast<const debug_directory *>(
  565. IntPtr + DataEntry->Size);
  566. // FIXME: Verify the section containing DebugDirectoryBegin has at least
  567. // DataEntry->Size bytes after DataEntry->RelativeVirtualAddress.
  568. return Error::success();
  569. }
  570. Error COFFObjectFile::initTLSDirectoryPtr() {
  571. // Get the RVA of the TLS directory. Do nothing if it does not exist.
  572. const data_directory *DataEntry = getDataDirectory(COFF::TLS_TABLE);
  573. if (!DataEntry)
  574. return Error::success();
  575. // Do nothing if the RVA is NULL.
  576. if (DataEntry->RelativeVirtualAddress == 0)
  577. return Error::success();
  578. uint64_t DirSize =
  579. is64() ? sizeof(coff_tls_directory64) : sizeof(coff_tls_directory32);
  580. // Check that the size is correct.
  581. if (DataEntry->Size != DirSize)
  582. return createStringError(
  583. object_error::parse_failed,
  584. "TLS Directory size (%u) is not the expected size (%" PRIu64 ").",
  585. static_cast<uint32_t>(DataEntry->Size), DirSize);
  586. uintptr_t IntPtr = 0;
  587. if (Error E = getRvaPtr(DataEntry->RelativeVirtualAddress, IntPtr))
  588. return E;
  589. if (is64())
  590. TLSDirectory64 = reinterpret_cast<const coff_tls_directory64 *>(IntPtr);
  591. else
  592. TLSDirectory32 = reinterpret_cast<const coff_tls_directory32 *>(IntPtr);
  593. return Error::success();
  594. }
  595. Error COFFObjectFile::initLoadConfigPtr() {
  596. // Get the RVA of the debug directory. Do nothing if it does not exist.
  597. const data_directory *DataEntry = getDataDirectory(COFF::LOAD_CONFIG_TABLE);
  598. if (!DataEntry)
  599. return Error::success();
  600. // Do nothing if the RVA is NULL.
  601. if (DataEntry->RelativeVirtualAddress == 0)
  602. return Error::success();
  603. uintptr_t IntPtr = 0;
  604. if (Error E = getRvaPtr(DataEntry->RelativeVirtualAddress, IntPtr))
  605. return E;
  606. LoadConfig = (const void *)IntPtr;
  607. return Error::success();
  608. }
  609. Expected<std::unique_ptr<COFFObjectFile>>
  610. COFFObjectFile::create(MemoryBufferRef Object) {
  611. std::unique_ptr<COFFObjectFile> Obj(new COFFObjectFile(std::move(Object)));
  612. if (Error E = Obj->initialize())
  613. return std::move(E);
  614. return std::move(Obj);
  615. }
  616. COFFObjectFile::COFFObjectFile(MemoryBufferRef Object)
  617. : ObjectFile(Binary::ID_COFF, Object), COFFHeader(nullptr),
  618. COFFBigObjHeader(nullptr), PE32Header(nullptr), PE32PlusHeader(nullptr),
  619. DataDirectory(nullptr), SectionTable(nullptr), SymbolTable16(nullptr),
  620. SymbolTable32(nullptr), StringTable(nullptr), StringTableSize(0),
  621. ImportDirectory(nullptr), DelayImportDirectory(nullptr),
  622. NumberOfDelayImportDirectory(0), ExportDirectory(nullptr),
  623. BaseRelocHeader(nullptr), BaseRelocEnd(nullptr),
  624. DebugDirectoryBegin(nullptr), DebugDirectoryEnd(nullptr),
  625. TLSDirectory32(nullptr), TLSDirectory64(nullptr) {}
  626. Error COFFObjectFile::initialize() {
  627. // Check that we at least have enough room for a header.
  628. std::error_code EC;
  629. if (!checkSize(Data, EC, sizeof(coff_file_header)))
  630. return errorCodeToError(EC);
  631. // The current location in the file where we are looking at.
  632. uint64_t CurPtr = 0;
  633. // PE header is optional and is present only in executables. If it exists,
  634. // it is placed right after COFF header.
  635. bool HasPEHeader = false;
  636. // Check if this is a PE/COFF file.
  637. if (checkSize(Data, EC, sizeof(dos_header) + sizeof(COFF::PEMagic))) {
  638. // PE/COFF, seek through MS-DOS compatibility stub and 4-byte
  639. // PE signature to find 'normal' COFF header.
  640. const auto *DH = reinterpret_cast<const dos_header *>(base());
  641. if (DH->Magic[0] == 'M' && DH->Magic[1] == 'Z') {
  642. CurPtr = DH->AddressOfNewExeHeader;
  643. // Check the PE magic bytes. ("PE\0\0")
  644. if (memcmp(base() + CurPtr, COFF::PEMagic, sizeof(COFF::PEMagic)) != 0) {
  645. return errorCodeToError(object_error::parse_failed);
  646. }
  647. CurPtr += sizeof(COFF::PEMagic); // Skip the PE magic bytes.
  648. HasPEHeader = true;
  649. }
  650. }
  651. if (Error E = getObject(COFFHeader, Data, base() + CurPtr))
  652. return E;
  653. // It might be a bigobj file, let's check. Note that COFF bigobj and COFF
  654. // import libraries share a common prefix but bigobj is more restrictive.
  655. if (!HasPEHeader && COFFHeader->Machine == COFF::IMAGE_FILE_MACHINE_UNKNOWN &&
  656. COFFHeader->NumberOfSections == uint16_t(0xffff) &&
  657. checkSize(Data, EC, sizeof(coff_bigobj_file_header))) {
  658. if (Error E = getObject(COFFBigObjHeader, Data, base() + CurPtr))
  659. return E;
  660. // Verify that we are dealing with bigobj.
  661. if (COFFBigObjHeader->Version >= COFF::BigObjHeader::MinBigObjectVersion &&
  662. std::memcmp(COFFBigObjHeader->UUID, COFF::BigObjMagic,
  663. sizeof(COFF::BigObjMagic)) == 0) {
  664. COFFHeader = nullptr;
  665. CurPtr += sizeof(coff_bigobj_file_header);
  666. } else {
  667. // It's not a bigobj.
  668. COFFBigObjHeader = nullptr;
  669. }
  670. }
  671. if (COFFHeader) {
  672. // The prior checkSize call may have failed. This isn't a hard error
  673. // because we were just trying to sniff out bigobj.
  674. EC = std::error_code();
  675. CurPtr += sizeof(coff_file_header);
  676. if (COFFHeader->isImportLibrary())
  677. return errorCodeToError(EC);
  678. }
  679. if (HasPEHeader) {
  680. const pe32_header *Header;
  681. if (Error E = getObject(Header, Data, base() + CurPtr))
  682. return E;
  683. const uint8_t *DataDirAddr;
  684. uint64_t DataDirSize;
  685. if (Header->Magic == COFF::PE32Header::PE32) {
  686. PE32Header = Header;
  687. DataDirAddr = base() + CurPtr + sizeof(pe32_header);
  688. DataDirSize = sizeof(data_directory) * PE32Header->NumberOfRvaAndSize;
  689. } else if (Header->Magic == COFF::PE32Header::PE32_PLUS) {
  690. PE32PlusHeader = reinterpret_cast<const pe32plus_header *>(Header);
  691. DataDirAddr = base() + CurPtr + sizeof(pe32plus_header);
  692. DataDirSize = sizeof(data_directory) * PE32PlusHeader->NumberOfRvaAndSize;
  693. } else {
  694. // It's neither PE32 nor PE32+.
  695. return errorCodeToError(object_error::parse_failed);
  696. }
  697. if (Error E = getObject(DataDirectory, Data, DataDirAddr, DataDirSize))
  698. return E;
  699. }
  700. if (COFFHeader)
  701. CurPtr += COFFHeader->SizeOfOptionalHeader;
  702. assert(COFFHeader || COFFBigObjHeader);
  703. if (Error E =
  704. getObject(SectionTable, Data, base() + CurPtr,
  705. (uint64_t)getNumberOfSections() * sizeof(coff_section)))
  706. return E;
  707. // Initialize the pointer to the symbol table.
  708. if (getPointerToSymbolTable() != 0) {
  709. if (Error E = initSymbolTablePtr()) {
  710. // Recover from errors reading the symbol table.
  711. consumeError(std::move(E));
  712. SymbolTable16 = nullptr;
  713. SymbolTable32 = nullptr;
  714. StringTable = nullptr;
  715. StringTableSize = 0;
  716. }
  717. } else {
  718. // We had better not have any symbols if we don't have a symbol table.
  719. if (getNumberOfSymbols() != 0) {
  720. return errorCodeToError(object_error::parse_failed);
  721. }
  722. }
  723. // Initialize the pointer to the beginning of the import table.
  724. if (Error E = initImportTablePtr())
  725. return E;
  726. if (Error E = initDelayImportTablePtr())
  727. return E;
  728. // Initialize the pointer to the export table.
  729. if (Error E = initExportTablePtr())
  730. return E;
  731. // Initialize the pointer to the base relocation table.
  732. if (Error E = initBaseRelocPtr())
  733. return E;
  734. // Initialize the pointer to the debug directory.
  735. if (Error E = initDebugDirectoryPtr())
  736. return E;
  737. // Initialize the pointer to the TLS directory.
  738. if (Error E = initTLSDirectoryPtr())
  739. return E;
  740. if (Error E = initLoadConfigPtr())
  741. return E;
  742. return Error::success();
  743. }
  744. basic_symbol_iterator COFFObjectFile::symbol_begin() const {
  745. DataRefImpl Ret;
  746. Ret.p = getSymbolTable();
  747. return basic_symbol_iterator(SymbolRef(Ret, this));
  748. }
  749. basic_symbol_iterator COFFObjectFile::symbol_end() const {
  750. // The symbol table ends where the string table begins.
  751. DataRefImpl Ret;
  752. Ret.p = reinterpret_cast<uintptr_t>(StringTable);
  753. return basic_symbol_iterator(SymbolRef(Ret, this));
  754. }
  755. import_directory_iterator COFFObjectFile::import_directory_begin() const {
  756. if (!ImportDirectory)
  757. return import_directory_end();
  758. if (ImportDirectory->isNull())
  759. return import_directory_end();
  760. return import_directory_iterator(
  761. ImportDirectoryEntryRef(ImportDirectory, 0, this));
  762. }
  763. import_directory_iterator COFFObjectFile::import_directory_end() const {
  764. return import_directory_iterator(
  765. ImportDirectoryEntryRef(nullptr, -1, this));
  766. }
  767. delay_import_directory_iterator
  768. COFFObjectFile::delay_import_directory_begin() const {
  769. return delay_import_directory_iterator(
  770. DelayImportDirectoryEntryRef(DelayImportDirectory, 0, this));
  771. }
  772. delay_import_directory_iterator
  773. COFFObjectFile::delay_import_directory_end() const {
  774. return delay_import_directory_iterator(
  775. DelayImportDirectoryEntryRef(
  776. DelayImportDirectory, NumberOfDelayImportDirectory, this));
  777. }
  778. export_directory_iterator COFFObjectFile::export_directory_begin() const {
  779. return export_directory_iterator(
  780. ExportDirectoryEntryRef(ExportDirectory, 0, this));
  781. }
  782. export_directory_iterator COFFObjectFile::export_directory_end() const {
  783. if (!ExportDirectory)
  784. return export_directory_iterator(ExportDirectoryEntryRef(nullptr, 0, this));
  785. ExportDirectoryEntryRef Ref(ExportDirectory,
  786. ExportDirectory->AddressTableEntries, this);
  787. return export_directory_iterator(Ref);
  788. }
  789. section_iterator COFFObjectFile::section_begin() const {
  790. DataRefImpl Ret;
  791. Ret.p = reinterpret_cast<uintptr_t>(SectionTable);
  792. return section_iterator(SectionRef(Ret, this));
  793. }
  794. section_iterator COFFObjectFile::section_end() const {
  795. DataRefImpl Ret;
  796. int NumSections =
  797. COFFHeader && COFFHeader->isImportLibrary() ? 0 : getNumberOfSections();
  798. Ret.p = reinterpret_cast<uintptr_t>(SectionTable + NumSections);
  799. return section_iterator(SectionRef(Ret, this));
  800. }
  801. base_reloc_iterator COFFObjectFile::base_reloc_begin() const {
  802. return base_reloc_iterator(BaseRelocRef(BaseRelocHeader, this));
  803. }
  804. base_reloc_iterator COFFObjectFile::base_reloc_end() const {
  805. return base_reloc_iterator(BaseRelocRef(BaseRelocEnd, this));
  806. }
  807. uint8_t COFFObjectFile::getBytesInAddress() const {
  808. return getArch() == Triple::x86_64 || getArch() == Triple::aarch64 ? 8 : 4;
  809. }
  810. StringRef COFFObjectFile::getFileFormatName() const {
  811. switch(getMachine()) {
  812. case COFF::IMAGE_FILE_MACHINE_I386:
  813. return "COFF-i386";
  814. case COFF::IMAGE_FILE_MACHINE_AMD64:
  815. return "COFF-x86-64";
  816. case COFF::IMAGE_FILE_MACHINE_ARMNT:
  817. return "COFF-ARM";
  818. case COFF::IMAGE_FILE_MACHINE_ARM64:
  819. return "COFF-ARM64";
  820. default:
  821. return "COFF-<unknown arch>";
  822. }
  823. }
  824. Triple::ArchType COFFObjectFile::getArch() const {
  825. switch (getMachine()) {
  826. case COFF::IMAGE_FILE_MACHINE_I386:
  827. return Triple::x86;
  828. case COFF::IMAGE_FILE_MACHINE_AMD64:
  829. return Triple::x86_64;
  830. case COFF::IMAGE_FILE_MACHINE_ARMNT:
  831. return Triple::thumb;
  832. case COFF::IMAGE_FILE_MACHINE_ARM64:
  833. return Triple::aarch64;
  834. default:
  835. return Triple::UnknownArch;
  836. }
  837. }
  838. Expected<uint64_t> COFFObjectFile::getStartAddress() const {
  839. if (PE32Header)
  840. return PE32Header->AddressOfEntryPoint;
  841. return 0;
  842. }
  843. iterator_range<import_directory_iterator>
  844. COFFObjectFile::import_directories() const {
  845. return make_range(import_directory_begin(), import_directory_end());
  846. }
  847. iterator_range<delay_import_directory_iterator>
  848. COFFObjectFile::delay_import_directories() const {
  849. return make_range(delay_import_directory_begin(),
  850. delay_import_directory_end());
  851. }
  852. iterator_range<export_directory_iterator>
  853. COFFObjectFile::export_directories() const {
  854. return make_range(export_directory_begin(), export_directory_end());
  855. }
  856. iterator_range<base_reloc_iterator> COFFObjectFile::base_relocs() const {
  857. return make_range(base_reloc_begin(), base_reloc_end());
  858. }
  859. const data_directory *COFFObjectFile::getDataDirectory(uint32_t Index) const {
  860. if (!DataDirectory)
  861. return nullptr;
  862. assert(PE32Header || PE32PlusHeader);
  863. uint32_t NumEnt = PE32Header ? PE32Header->NumberOfRvaAndSize
  864. : PE32PlusHeader->NumberOfRvaAndSize;
  865. if (Index >= NumEnt)
  866. return nullptr;
  867. return &DataDirectory[Index];
  868. }
  869. Expected<const coff_section *> COFFObjectFile::getSection(int32_t Index) const {
  870. // Perhaps getting the section of a reserved section index should be an error,
  871. // but callers rely on this to return null.
  872. if (COFF::isReservedSectionNumber(Index))
  873. return (const coff_section *)nullptr;
  874. if (static_cast<uint32_t>(Index) <= getNumberOfSections()) {
  875. // We already verified the section table data, so no need to check again.
  876. return SectionTable + (Index - 1);
  877. }
  878. return errorCodeToError(object_error::parse_failed);
  879. }
  880. Expected<StringRef> COFFObjectFile::getString(uint32_t Offset) const {
  881. if (StringTableSize <= 4)
  882. // Tried to get a string from an empty string table.
  883. return errorCodeToError(object_error::parse_failed);
  884. if (Offset >= StringTableSize)
  885. return errorCodeToError(object_error::unexpected_eof);
  886. return StringRef(StringTable + Offset);
  887. }
  888. Expected<StringRef> COFFObjectFile::getSymbolName(COFFSymbolRef Symbol) const {
  889. return getSymbolName(Symbol.getGeneric());
  890. }
  891. Expected<StringRef>
  892. COFFObjectFile::getSymbolName(const coff_symbol_generic *Symbol) const {
  893. // Check for string table entry. First 4 bytes are 0.
  894. if (Symbol->Name.Offset.Zeroes == 0)
  895. return getString(Symbol->Name.Offset.Offset);
  896. // Null terminated, let ::strlen figure out the length.
  897. if (Symbol->Name.ShortName[COFF::NameSize - 1] == 0)
  898. return StringRef(Symbol->Name.ShortName);
  899. // Not null terminated, use all 8 bytes.
  900. return StringRef(Symbol->Name.ShortName, COFF::NameSize);
  901. }
  902. ArrayRef<uint8_t>
  903. COFFObjectFile::getSymbolAuxData(COFFSymbolRef Symbol) const {
  904. const uint8_t *Aux = nullptr;
  905. size_t SymbolSize = getSymbolTableEntrySize();
  906. if (Symbol.getNumberOfAuxSymbols() > 0) {
  907. // AUX data comes immediately after the symbol in COFF
  908. Aux = reinterpret_cast<const uint8_t *>(Symbol.getRawPtr()) + SymbolSize;
  909. #ifndef NDEBUG
  910. // Verify that the Aux symbol points to a valid entry in the symbol table.
  911. uintptr_t Offset = uintptr_t(Aux) - uintptr_t(base());
  912. if (Offset < getPointerToSymbolTable() ||
  913. Offset >=
  914. getPointerToSymbolTable() + (getNumberOfSymbols() * SymbolSize))
  915. report_fatal_error("Aux Symbol data was outside of symbol table.");
  916. assert((Offset - getPointerToSymbolTable()) % SymbolSize == 0 &&
  917. "Aux Symbol data did not point to the beginning of a symbol");
  918. #endif
  919. }
  920. return makeArrayRef(Aux, Symbol.getNumberOfAuxSymbols() * SymbolSize);
  921. }
  922. uint32_t COFFObjectFile::getSymbolIndex(COFFSymbolRef Symbol) const {
  923. uintptr_t Offset =
  924. reinterpret_cast<uintptr_t>(Symbol.getRawPtr()) - getSymbolTable();
  925. assert(Offset % getSymbolTableEntrySize() == 0 &&
  926. "Symbol did not point to the beginning of a symbol");
  927. size_t Index = Offset / getSymbolTableEntrySize();
  928. assert(Index < getNumberOfSymbols());
  929. return Index;
  930. }
  931. Expected<StringRef>
  932. COFFObjectFile::getSectionName(const coff_section *Sec) const {
  933. StringRef Name;
  934. if (Sec->Name[COFF::NameSize - 1] == 0)
  935. // Null terminated, let ::strlen figure out the length.
  936. Name = Sec->Name;
  937. else
  938. // Not null terminated, use all 8 bytes.
  939. Name = StringRef(Sec->Name, COFF::NameSize);
  940. // Check for string table entry. First byte is '/'.
  941. if (Name.startswith("/")) {
  942. uint32_t Offset;
  943. if (Name.startswith("//")) {
  944. if (decodeBase64StringEntry(Name.substr(2), Offset))
  945. return createStringError(object_error::parse_failed,
  946. "invalid section name");
  947. } else {
  948. if (Name.substr(1).getAsInteger(10, Offset))
  949. return createStringError(object_error::parse_failed,
  950. "invalid section name");
  951. }
  952. return getString(Offset);
  953. }
  954. return Name;
  955. }
  956. uint64_t COFFObjectFile::getSectionSize(const coff_section *Sec) const {
  957. // SizeOfRawData and VirtualSize change what they represent depending on
  958. // whether or not we have an executable image.
  959. //
  960. // For object files, SizeOfRawData contains the size of section's data;
  961. // VirtualSize should be zero but isn't due to buggy COFF writers.
  962. //
  963. // For executables, SizeOfRawData *must* be a multiple of FileAlignment; the
  964. // actual section size is in VirtualSize. It is possible for VirtualSize to
  965. // be greater than SizeOfRawData; the contents past that point should be
  966. // considered to be zero.
  967. if (getDOSHeader())
  968. return std::min(Sec->VirtualSize, Sec->SizeOfRawData);
  969. return Sec->SizeOfRawData;
  970. }
  971. Error COFFObjectFile::getSectionContents(const coff_section *Sec,
  972. ArrayRef<uint8_t> &Res) const {
  973. // In COFF, a virtual section won't have any in-file
  974. // content, so the file pointer to the content will be zero.
  975. if (Sec->PointerToRawData == 0)
  976. return Error::success();
  977. // The only thing that we need to verify is that the contents is contained
  978. // within the file bounds. We don't need to make sure it doesn't cover other
  979. // data, as there's nothing that says that is not allowed.
  980. uintptr_t ConStart =
  981. reinterpret_cast<uintptr_t>(base()) + Sec->PointerToRawData;
  982. uint32_t SectionSize = getSectionSize(Sec);
  983. if (Error E = checkOffset(Data, ConStart, SectionSize))
  984. return E;
  985. Res = makeArrayRef(reinterpret_cast<const uint8_t *>(ConStart), SectionSize);
  986. return Error::success();
  987. }
  988. const coff_relocation *COFFObjectFile::toRel(DataRefImpl Rel) const {
  989. return reinterpret_cast<const coff_relocation*>(Rel.p);
  990. }
  991. void COFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
  992. Rel.p = reinterpret_cast<uintptr_t>(
  993. reinterpret_cast<const coff_relocation*>(Rel.p) + 1);
  994. }
  995. uint64_t COFFObjectFile::getRelocationOffset(DataRefImpl Rel) const {
  996. const coff_relocation *R = toRel(Rel);
  997. return R->VirtualAddress;
  998. }
  999. symbol_iterator COFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
  1000. const coff_relocation *R = toRel(Rel);
  1001. DataRefImpl Ref;
  1002. if (R->SymbolTableIndex >= getNumberOfSymbols())
  1003. return symbol_end();
  1004. if (SymbolTable16)
  1005. Ref.p = reinterpret_cast<uintptr_t>(SymbolTable16 + R->SymbolTableIndex);
  1006. else if (SymbolTable32)
  1007. Ref.p = reinterpret_cast<uintptr_t>(SymbolTable32 + R->SymbolTableIndex);
  1008. else
  1009. llvm_unreachable("no symbol table pointer!");
  1010. return symbol_iterator(SymbolRef(Ref, this));
  1011. }
  1012. uint64_t COFFObjectFile::getRelocationType(DataRefImpl Rel) const {
  1013. const coff_relocation* R = toRel(Rel);
  1014. return R->Type;
  1015. }
  1016. const coff_section *
  1017. COFFObjectFile::getCOFFSection(const SectionRef &Section) const {
  1018. return toSec(Section.getRawDataRefImpl());
  1019. }
  1020. COFFSymbolRef COFFObjectFile::getCOFFSymbol(const DataRefImpl &Ref) const {
  1021. if (SymbolTable16)
  1022. return toSymb<coff_symbol16>(Ref);
  1023. if (SymbolTable32)
  1024. return toSymb<coff_symbol32>(Ref);
  1025. llvm_unreachable("no symbol table pointer!");
  1026. }
  1027. COFFSymbolRef COFFObjectFile::getCOFFSymbol(const SymbolRef &Symbol) const {
  1028. return getCOFFSymbol(Symbol.getRawDataRefImpl());
  1029. }
  1030. const coff_relocation *
  1031. COFFObjectFile::getCOFFRelocation(const RelocationRef &Reloc) const {
  1032. return toRel(Reloc.getRawDataRefImpl());
  1033. }
  1034. ArrayRef<coff_relocation>
  1035. COFFObjectFile::getRelocations(const coff_section *Sec) const {
  1036. return {getFirstReloc(Sec, Data, base()),
  1037. getNumberOfRelocations(Sec, Data, base())};
  1038. }
  1039. #define LLVM_COFF_SWITCH_RELOC_TYPE_NAME(reloc_type) \
  1040. case COFF::reloc_type: \
  1041. return #reloc_type;
  1042. StringRef COFFObjectFile::getRelocationTypeName(uint16_t Type) const {
  1043. switch (getMachine()) {
  1044. case COFF::IMAGE_FILE_MACHINE_AMD64:
  1045. switch (Type) {
  1046. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ABSOLUTE);
  1047. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR64);
  1048. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32);
  1049. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_ADDR32NB);
  1050. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32);
  1051. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_1);
  1052. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_2);
  1053. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_3);
  1054. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_4);
  1055. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_REL32_5);
  1056. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECTION);
  1057. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL);
  1058. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SECREL7);
  1059. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_TOKEN);
  1060. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SREL32);
  1061. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_PAIR);
  1062. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_AMD64_SSPAN32);
  1063. default:
  1064. return "Unknown";
  1065. }
  1066. break;
  1067. case COFF::IMAGE_FILE_MACHINE_ARMNT:
  1068. switch (Type) {
  1069. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ABSOLUTE);
  1070. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32);
  1071. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_ADDR32NB);
  1072. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24);
  1073. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH11);
  1074. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_TOKEN);
  1075. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX24);
  1076. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX11);
  1077. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_REL32);
  1078. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECTION);
  1079. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_SECREL);
  1080. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32A);
  1081. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_MOV32T);
  1082. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH20T);
  1083. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BRANCH24T);
  1084. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_BLX23T);
  1085. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM_PAIR);
  1086. default:
  1087. return "Unknown";
  1088. }
  1089. break;
  1090. case COFF::IMAGE_FILE_MACHINE_ARM64:
  1091. switch (Type) {
  1092. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_ABSOLUTE);
  1093. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_ADDR32);
  1094. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_ADDR32NB);
  1095. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_BRANCH26);
  1096. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_PAGEBASE_REL21);
  1097. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_REL21);
  1098. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_PAGEOFFSET_12A);
  1099. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_PAGEOFFSET_12L);
  1100. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_SECREL);
  1101. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_SECREL_LOW12A);
  1102. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_SECREL_HIGH12A);
  1103. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_SECREL_LOW12L);
  1104. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_TOKEN);
  1105. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_SECTION);
  1106. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_ADDR64);
  1107. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_BRANCH19);
  1108. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_BRANCH14);
  1109. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_ARM64_REL32);
  1110. default:
  1111. return "Unknown";
  1112. }
  1113. break;
  1114. case COFF::IMAGE_FILE_MACHINE_I386:
  1115. switch (Type) {
  1116. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_ABSOLUTE);
  1117. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR16);
  1118. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL16);
  1119. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32);
  1120. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_DIR32NB);
  1121. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SEG12);
  1122. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECTION);
  1123. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL);
  1124. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_TOKEN);
  1125. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_SECREL7);
  1126. LLVM_COFF_SWITCH_RELOC_TYPE_NAME(IMAGE_REL_I386_REL32);
  1127. default:
  1128. return "Unknown";
  1129. }
  1130. break;
  1131. default:
  1132. return "Unknown";
  1133. }
  1134. }
  1135. #undef LLVM_COFF_SWITCH_RELOC_TYPE_NAME
  1136. void COFFObjectFile::getRelocationTypeName(
  1137. DataRefImpl Rel, SmallVectorImpl<char> &Result) const {
  1138. const coff_relocation *Reloc = toRel(Rel);
  1139. StringRef Res = getRelocationTypeName(Reloc->Type);
  1140. Result.append(Res.begin(), Res.end());
  1141. }
  1142. bool COFFObjectFile::isRelocatableObject() const {
  1143. return !DataDirectory;
  1144. }
  1145. StringRef COFFObjectFile::mapDebugSectionName(StringRef Name) const {
  1146. return StringSwitch<StringRef>(Name)
  1147. .Case("eh_fram", "eh_frame")
  1148. .Default(Name);
  1149. }
  1150. bool ImportDirectoryEntryRef::
  1151. operator==(const ImportDirectoryEntryRef &Other) const {
  1152. return ImportTable == Other.ImportTable && Index == Other.Index;
  1153. }
  1154. void ImportDirectoryEntryRef::moveNext() {
  1155. ++Index;
  1156. if (ImportTable[Index].isNull()) {
  1157. Index = -1;
  1158. ImportTable = nullptr;
  1159. }
  1160. }
  1161. Error ImportDirectoryEntryRef::getImportTableEntry(
  1162. const coff_import_directory_table_entry *&Result) const {
  1163. return getObject(Result, OwningObject->Data, ImportTable + Index);
  1164. }
  1165. static imported_symbol_iterator
  1166. makeImportedSymbolIterator(const COFFObjectFile *Object,
  1167. uintptr_t Ptr, int Index) {
  1168. if (Object->getBytesInAddress() == 4) {
  1169. auto *P = reinterpret_cast<const import_lookup_table_entry32 *>(Ptr);
  1170. return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
  1171. }
  1172. auto *P = reinterpret_cast<const import_lookup_table_entry64 *>(Ptr);
  1173. return imported_symbol_iterator(ImportedSymbolRef(P, Index, Object));
  1174. }
  1175. static imported_symbol_iterator
  1176. importedSymbolBegin(uint32_t RVA, const COFFObjectFile *Object) {
  1177. uintptr_t IntPtr = 0;
  1178. // FIXME: Handle errors.
  1179. cantFail(Object->getRvaPtr(RVA, IntPtr));
  1180. return makeImportedSymbolIterator(Object, IntPtr, 0);
  1181. }
  1182. static imported_symbol_iterator
  1183. importedSymbolEnd(uint32_t RVA, const COFFObjectFile *Object) {
  1184. uintptr_t IntPtr = 0;
  1185. // FIXME: Handle errors.
  1186. cantFail(Object->getRvaPtr(RVA, IntPtr));
  1187. // Forward the pointer to the last entry which is null.
  1188. int Index = 0;
  1189. if (Object->getBytesInAddress() == 4) {
  1190. auto *Entry = reinterpret_cast<ulittle32_t *>(IntPtr);
  1191. while (*Entry++)
  1192. ++Index;
  1193. } else {
  1194. auto *Entry = reinterpret_cast<ulittle64_t *>(IntPtr);
  1195. while (*Entry++)
  1196. ++Index;
  1197. }
  1198. return makeImportedSymbolIterator(Object, IntPtr, Index);
  1199. }
  1200. imported_symbol_iterator
  1201. ImportDirectoryEntryRef::imported_symbol_begin() const {
  1202. return importedSymbolBegin(ImportTable[Index].ImportAddressTableRVA,
  1203. OwningObject);
  1204. }
  1205. imported_symbol_iterator
  1206. ImportDirectoryEntryRef::imported_symbol_end() const {
  1207. return importedSymbolEnd(ImportTable[Index].ImportAddressTableRVA,
  1208. OwningObject);
  1209. }
  1210. iterator_range<imported_symbol_iterator>
  1211. ImportDirectoryEntryRef::imported_symbols() const {
  1212. return make_range(imported_symbol_begin(), imported_symbol_end());
  1213. }
  1214. imported_symbol_iterator ImportDirectoryEntryRef::lookup_table_begin() const {
  1215. return importedSymbolBegin(ImportTable[Index].ImportLookupTableRVA,
  1216. OwningObject);
  1217. }
  1218. imported_symbol_iterator ImportDirectoryEntryRef::lookup_table_end() const {
  1219. return importedSymbolEnd(ImportTable[Index].ImportLookupTableRVA,
  1220. OwningObject);
  1221. }
  1222. iterator_range<imported_symbol_iterator>
  1223. ImportDirectoryEntryRef::lookup_table_symbols() const {
  1224. return make_range(lookup_table_begin(), lookup_table_end());
  1225. }
  1226. Error ImportDirectoryEntryRef::getName(StringRef &Result) const {
  1227. uintptr_t IntPtr = 0;
  1228. if (Error E = OwningObject->getRvaPtr(ImportTable[Index].NameRVA, IntPtr))
  1229. return E;
  1230. Result = StringRef(reinterpret_cast<const char *>(IntPtr));
  1231. return Error::success();
  1232. }
  1233. Error
  1234. ImportDirectoryEntryRef::getImportLookupTableRVA(uint32_t &Result) const {
  1235. Result = ImportTable[Index].ImportLookupTableRVA;
  1236. return Error::success();
  1237. }
  1238. Error ImportDirectoryEntryRef::getImportAddressTableRVA(
  1239. uint32_t &Result) const {
  1240. Result = ImportTable[Index].ImportAddressTableRVA;
  1241. return Error::success();
  1242. }
  1243. bool DelayImportDirectoryEntryRef::
  1244. operator==(const DelayImportDirectoryEntryRef &Other) const {
  1245. return Table == Other.Table && Index == Other.Index;
  1246. }
  1247. void DelayImportDirectoryEntryRef::moveNext() {
  1248. ++Index;
  1249. }
  1250. imported_symbol_iterator
  1251. DelayImportDirectoryEntryRef::imported_symbol_begin() const {
  1252. return importedSymbolBegin(Table[Index].DelayImportNameTable,
  1253. OwningObject);
  1254. }
  1255. imported_symbol_iterator
  1256. DelayImportDirectoryEntryRef::imported_symbol_end() const {
  1257. return importedSymbolEnd(Table[Index].DelayImportNameTable,
  1258. OwningObject);
  1259. }
  1260. iterator_range<imported_symbol_iterator>
  1261. DelayImportDirectoryEntryRef::imported_symbols() const {
  1262. return make_range(imported_symbol_begin(), imported_symbol_end());
  1263. }
  1264. Error DelayImportDirectoryEntryRef::getName(StringRef &Result) const {
  1265. uintptr_t IntPtr = 0;
  1266. if (Error E = OwningObject->getRvaPtr(Table[Index].Name, IntPtr))
  1267. return E;
  1268. Result = StringRef(reinterpret_cast<const char *>(IntPtr));
  1269. return Error::success();
  1270. }
  1271. Error DelayImportDirectoryEntryRef::getDelayImportTable(
  1272. const delay_import_directory_table_entry *&Result) const {
  1273. Result = &Table[Index];
  1274. return Error::success();
  1275. }
  1276. Error DelayImportDirectoryEntryRef::getImportAddress(int AddrIndex,
  1277. uint64_t &Result) const {
  1278. uint32_t RVA = Table[Index].DelayImportAddressTable +
  1279. AddrIndex * (OwningObject->is64() ? 8 : 4);
  1280. uintptr_t IntPtr = 0;
  1281. if (Error E = OwningObject->getRvaPtr(RVA, IntPtr))
  1282. return E;
  1283. if (OwningObject->is64())
  1284. Result = *reinterpret_cast<const ulittle64_t *>(IntPtr);
  1285. else
  1286. Result = *reinterpret_cast<const ulittle32_t *>(IntPtr);
  1287. return Error::success();
  1288. }
  1289. bool ExportDirectoryEntryRef::
  1290. operator==(const ExportDirectoryEntryRef &Other) const {
  1291. return ExportTable == Other.ExportTable && Index == Other.Index;
  1292. }
  1293. void ExportDirectoryEntryRef::moveNext() {
  1294. ++Index;
  1295. }
  1296. // Returns the name of the current export symbol. If the symbol is exported only
  1297. // by ordinal, the empty string is set as a result.
  1298. Error ExportDirectoryEntryRef::getDllName(StringRef &Result) const {
  1299. uintptr_t IntPtr = 0;
  1300. if (Error E = OwningObject->getRvaPtr(ExportTable->NameRVA, IntPtr))
  1301. return E;
  1302. Result = StringRef(reinterpret_cast<const char *>(IntPtr));
  1303. return Error::success();
  1304. }
  1305. // Returns the starting ordinal number.
  1306. Error ExportDirectoryEntryRef::getOrdinalBase(uint32_t &Result) const {
  1307. Result = ExportTable->OrdinalBase;
  1308. return Error::success();
  1309. }
  1310. // Returns the export ordinal of the current export symbol.
  1311. Error ExportDirectoryEntryRef::getOrdinal(uint32_t &Result) const {
  1312. Result = ExportTable->OrdinalBase + Index;
  1313. return Error::success();
  1314. }
  1315. // Returns the address of the current export symbol.
  1316. Error ExportDirectoryEntryRef::getExportRVA(uint32_t &Result) const {
  1317. uintptr_t IntPtr = 0;
  1318. if (Error EC =
  1319. OwningObject->getRvaPtr(ExportTable->ExportAddressTableRVA, IntPtr))
  1320. return EC;
  1321. const export_address_table_entry *entry =
  1322. reinterpret_cast<const export_address_table_entry *>(IntPtr);
  1323. Result = entry[Index].ExportRVA;
  1324. return Error::success();
  1325. }
  1326. // Returns the name of the current export symbol. If the symbol is exported only
  1327. // by ordinal, the empty string is set as a result.
  1328. Error
  1329. ExportDirectoryEntryRef::getSymbolName(StringRef &Result) const {
  1330. uintptr_t IntPtr = 0;
  1331. if (Error EC =
  1332. OwningObject->getRvaPtr(ExportTable->OrdinalTableRVA, IntPtr))
  1333. return EC;
  1334. const ulittle16_t *Start = reinterpret_cast<const ulittle16_t *>(IntPtr);
  1335. uint32_t NumEntries = ExportTable->NumberOfNamePointers;
  1336. int Offset = 0;
  1337. for (const ulittle16_t *I = Start, *E = Start + NumEntries;
  1338. I < E; ++I, ++Offset) {
  1339. if (*I != Index)
  1340. continue;
  1341. if (Error EC =
  1342. OwningObject->getRvaPtr(ExportTable->NamePointerRVA, IntPtr))
  1343. return EC;
  1344. const ulittle32_t *NamePtr = reinterpret_cast<const ulittle32_t *>(IntPtr);
  1345. if (Error EC = OwningObject->getRvaPtr(NamePtr[Offset], IntPtr))
  1346. return EC;
  1347. Result = StringRef(reinterpret_cast<const char *>(IntPtr));
  1348. return Error::success();
  1349. }
  1350. Result = "";
  1351. return Error::success();
  1352. }
  1353. Error ExportDirectoryEntryRef::isForwarder(bool &Result) const {
  1354. const data_directory *DataEntry =
  1355. OwningObject->getDataDirectory(COFF::EXPORT_TABLE);
  1356. if (!DataEntry)
  1357. return errorCodeToError(object_error::parse_failed);
  1358. uint32_t RVA;
  1359. if (auto EC = getExportRVA(RVA))
  1360. return EC;
  1361. uint32_t Begin = DataEntry->RelativeVirtualAddress;
  1362. uint32_t End = DataEntry->RelativeVirtualAddress + DataEntry->Size;
  1363. Result = (Begin <= RVA && RVA < End);
  1364. return Error::success();
  1365. }
  1366. Error ExportDirectoryEntryRef::getForwardTo(StringRef &Result) const {
  1367. uint32_t RVA;
  1368. if (auto EC = getExportRVA(RVA))
  1369. return EC;
  1370. uintptr_t IntPtr = 0;
  1371. if (auto EC = OwningObject->getRvaPtr(RVA, IntPtr))
  1372. return EC;
  1373. Result = StringRef(reinterpret_cast<const char *>(IntPtr));
  1374. return Error::success();
  1375. }
  1376. bool ImportedSymbolRef::
  1377. operator==(const ImportedSymbolRef &Other) const {
  1378. return Entry32 == Other.Entry32 && Entry64 == Other.Entry64
  1379. && Index == Other.Index;
  1380. }
  1381. void ImportedSymbolRef::moveNext() {
  1382. ++Index;
  1383. }
  1384. Error ImportedSymbolRef::getSymbolName(StringRef &Result) const {
  1385. uint32_t RVA;
  1386. if (Entry32) {
  1387. // If a symbol is imported only by ordinal, it has no name.
  1388. if (Entry32[Index].isOrdinal())
  1389. return Error::success();
  1390. RVA = Entry32[Index].getHintNameRVA();
  1391. } else {
  1392. if (Entry64[Index].isOrdinal())
  1393. return Error::success();
  1394. RVA = Entry64[Index].getHintNameRVA();
  1395. }
  1396. uintptr_t IntPtr = 0;
  1397. if (Error EC = OwningObject->getRvaPtr(RVA, IntPtr))
  1398. return EC;
  1399. // +2 because the first two bytes is hint.
  1400. Result = StringRef(reinterpret_cast<const char *>(IntPtr + 2));
  1401. return Error::success();
  1402. }
  1403. Error ImportedSymbolRef::isOrdinal(bool &Result) const {
  1404. if (Entry32)
  1405. Result = Entry32[Index].isOrdinal();
  1406. else
  1407. Result = Entry64[Index].isOrdinal();
  1408. return Error::success();
  1409. }
  1410. Error ImportedSymbolRef::getHintNameRVA(uint32_t &Result) const {
  1411. if (Entry32)
  1412. Result = Entry32[Index].getHintNameRVA();
  1413. else
  1414. Result = Entry64[Index].getHintNameRVA();
  1415. return Error::success();
  1416. }
  1417. Error ImportedSymbolRef::getOrdinal(uint16_t &Result) const {
  1418. uint32_t RVA;
  1419. if (Entry32) {
  1420. if (Entry32[Index].isOrdinal()) {
  1421. Result = Entry32[Index].getOrdinal();
  1422. return Error::success();
  1423. }
  1424. RVA = Entry32[Index].getHintNameRVA();
  1425. } else {
  1426. if (Entry64[Index].isOrdinal()) {
  1427. Result = Entry64[Index].getOrdinal();
  1428. return Error::success();
  1429. }
  1430. RVA = Entry64[Index].getHintNameRVA();
  1431. }
  1432. uintptr_t IntPtr = 0;
  1433. if (Error EC = OwningObject->getRvaPtr(RVA, IntPtr))
  1434. return EC;
  1435. Result = *reinterpret_cast<const ulittle16_t *>(IntPtr);
  1436. return Error::success();
  1437. }
  1438. Expected<std::unique_ptr<COFFObjectFile>>
  1439. ObjectFile::createCOFFObjectFile(MemoryBufferRef Object) {
  1440. return COFFObjectFile::create(Object);
  1441. }
  1442. bool BaseRelocRef::operator==(const BaseRelocRef &Other) const {
  1443. return Header == Other.Header && Index == Other.Index;
  1444. }
  1445. void BaseRelocRef::moveNext() {
  1446. // Header->BlockSize is the size of the current block, including the
  1447. // size of the header itself.
  1448. uint32_t Size = sizeof(*Header) +
  1449. sizeof(coff_base_reloc_block_entry) * (Index + 1);
  1450. if (Size == Header->BlockSize) {
  1451. // .reloc contains a list of base relocation blocks. Each block
  1452. // consists of the header followed by entries. The header contains
  1453. // how many entories will follow. When we reach the end of the
  1454. // current block, proceed to the next block.
  1455. Header = reinterpret_cast<const coff_base_reloc_block_header *>(
  1456. reinterpret_cast<const uint8_t *>(Header) + Size);
  1457. Index = 0;
  1458. } else {
  1459. ++Index;
  1460. }
  1461. }
  1462. Error BaseRelocRef::getType(uint8_t &Type) const {
  1463. auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1);
  1464. Type = Entry[Index].getType();
  1465. return Error::success();
  1466. }
  1467. Error BaseRelocRef::getRVA(uint32_t &Result) const {
  1468. auto *Entry = reinterpret_cast<const coff_base_reloc_block_entry *>(Header + 1);
  1469. Result = Header->PageRVA + Entry[Index].getOffset();
  1470. return Error::success();
  1471. }
  1472. #define RETURN_IF_ERROR(Expr) \
  1473. do { \
  1474. Error E = (Expr); \
  1475. if (E) \
  1476. return std::move(E); \
  1477. } while (0)
  1478. Expected<ArrayRef<UTF16>>
  1479. ResourceSectionRef::getDirStringAtOffset(uint32_t Offset) {
  1480. BinaryStreamReader Reader = BinaryStreamReader(BBS);
  1481. Reader.setOffset(Offset);
  1482. uint16_t Length;
  1483. RETURN_IF_ERROR(Reader.readInteger(Length));
  1484. ArrayRef<UTF16> RawDirString;
  1485. RETURN_IF_ERROR(Reader.readArray(RawDirString, Length));
  1486. return RawDirString;
  1487. }
  1488. Expected<ArrayRef<UTF16>>
  1489. ResourceSectionRef::getEntryNameString(const coff_resource_dir_entry &Entry) {
  1490. return getDirStringAtOffset(Entry.Identifier.getNameOffset());
  1491. }
  1492. Expected<const coff_resource_dir_table &>
  1493. ResourceSectionRef::getTableAtOffset(uint32_t Offset) {
  1494. const coff_resource_dir_table *Table = nullptr;
  1495. BinaryStreamReader Reader(BBS);
  1496. Reader.setOffset(Offset);
  1497. RETURN_IF_ERROR(Reader.readObject(Table));
  1498. assert(Table != nullptr);
  1499. return *Table;
  1500. }
  1501. Expected<const coff_resource_dir_entry &>
  1502. ResourceSectionRef::getTableEntryAtOffset(uint32_t Offset) {
  1503. const coff_resource_dir_entry *Entry = nullptr;
  1504. BinaryStreamReader Reader(BBS);
  1505. Reader.setOffset(Offset);
  1506. RETURN_IF_ERROR(Reader.readObject(Entry));
  1507. assert(Entry != nullptr);
  1508. return *Entry;
  1509. }
  1510. Expected<const coff_resource_data_entry &>
  1511. ResourceSectionRef::getDataEntryAtOffset(uint32_t Offset) {
  1512. const coff_resource_data_entry *Entry = nullptr;
  1513. BinaryStreamReader Reader(BBS);
  1514. Reader.setOffset(Offset);
  1515. RETURN_IF_ERROR(Reader.readObject(Entry));
  1516. assert(Entry != nullptr);
  1517. return *Entry;
  1518. }
  1519. Expected<const coff_resource_dir_table &>
  1520. ResourceSectionRef::getEntrySubDir(const coff_resource_dir_entry &Entry) {
  1521. assert(Entry.Offset.isSubDir());
  1522. return getTableAtOffset(Entry.Offset.value());
  1523. }
  1524. Expected<const coff_resource_data_entry &>
  1525. ResourceSectionRef::getEntryData(const coff_resource_dir_entry &Entry) {
  1526. assert(!Entry.Offset.isSubDir());
  1527. return getDataEntryAtOffset(Entry.Offset.value());
  1528. }
  1529. Expected<const coff_resource_dir_table &> ResourceSectionRef::getBaseTable() {
  1530. return getTableAtOffset(0);
  1531. }
  1532. Expected<const coff_resource_dir_entry &>
  1533. ResourceSectionRef::getTableEntry(const coff_resource_dir_table &Table,
  1534. uint32_t Index) {
  1535. if (Index >= (uint32_t)(Table.NumberOfNameEntries + Table.NumberOfIDEntries))
  1536. return createStringError(object_error::parse_failed, "index out of range");
  1537. const uint8_t *TablePtr = reinterpret_cast<const uint8_t *>(&Table);
  1538. ptrdiff_t TableOffset = TablePtr - BBS.data().data();
  1539. return getTableEntryAtOffset(TableOffset + sizeof(Table) +
  1540. Index * sizeof(coff_resource_dir_entry));
  1541. }
  1542. Error ResourceSectionRef::load(const COFFObjectFile *O) {
  1543. for (const SectionRef &S : O->sections()) {
  1544. Expected<StringRef> Name = S.getName();
  1545. if (!Name)
  1546. return Name.takeError();
  1547. if (*Name == ".rsrc" || *Name == ".rsrc$01")
  1548. return load(O, S);
  1549. }
  1550. return createStringError(object_error::parse_failed,
  1551. "no resource section found");
  1552. }
  1553. Error ResourceSectionRef::load(const COFFObjectFile *O, const SectionRef &S) {
  1554. Obj = O;
  1555. Section = S;
  1556. Expected<StringRef> Contents = Section.getContents();
  1557. if (!Contents)
  1558. return Contents.takeError();
  1559. BBS = BinaryByteStream(*Contents, support::little);
  1560. const coff_section *COFFSect = Obj->getCOFFSection(Section);
  1561. ArrayRef<coff_relocation> OrigRelocs = Obj->getRelocations(COFFSect);
  1562. Relocs.reserve(OrigRelocs.size());
  1563. for (const coff_relocation &R : OrigRelocs)
  1564. Relocs.push_back(&R);
  1565. llvm::sort(Relocs, [](const coff_relocation *A, const coff_relocation *B) {
  1566. return A->VirtualAddress < B->VirtualAddress;
  1567. });
  1568. return Error::success();
  1569. }
  1570. Expected<StringRef>
  1571. ResourceSectionRef::getContents(const coff_resource_data_entry &Entry) {
  1572. if (!Obj)
  1573. return createStringError(object_error::parse_failed, "no object provided");
  1574. // Find a potential relocation at the DataRVA field (first member of
  1575. // the coff_resource_data_entry struct).
  1576. const uint8_t *EntryPtr = reinterpret_cast<const uint8_t *>(&Entry);
  1577. ptrdiff_t EntryOffset = EntryPtr - BBS.data().data();
  1578. coff_relocation RelocTarget{ulittle32_t(EntryOffset), ulittle32_t(0),
  1579. ulittle16_t(0)};
  1580. auto RelocsForOffset =
  1581. std::equal_range(Relocs.begin(), Relocs.end(), &RelocTarget,
  1582. [](const coff_relocation *A, const coff_relocation *B) {
  1583. return A->VirtualAddress < B->VirtualAddress;
  1584. });
  1585. if (RelocsForOffset.first != RelocsForOffset.second) {
  1586. // We found a relocation with the right offset. Check that it does have
  1587. // the expected type.
  1588. const coff_relocation &R = **RelocsForOffset.first;
  1589. uint16_t RVAReloc;
  1590. switch (Obj->getMachine()) {
  1591. case COFF::IMAGE_FILE_MACHINE_I386:
  1592. RVAReloc = COFF::IMAGE_REL_I386_DIR32NB;
  1593. break;
  1594. case COFF::IMAGE_FILE_MACHINE_AMD64:
  1595. RVAReloc = COFF::IMAGE_REL_AMD64_ADDR32NB;
  1596. break;
  1597. case COFF::IMAGE_FILE_MACHINE_ARMNT:
  1598. RVAReloc = COFF::IMAGE_REL_ARM_ADDR32NB;
  1599. break;
  1600. case COFF::IMAGE_FILE_MACHINE_ARM64:
  1601. RVAReloc = COFF::IMAGE_REL_ARM64_ADDR32NB;
  1602. break;
  1603. default:
  1604. return createStringError(object_error::parse_failed,
  1605. "unsupported architecture");
  1606. }
  1607. if (R.Type != RVAReloc)
  1608. return createStringError(object_error::parse_failed,
  1609. "unexpected relocation type");
  1610. // Get the relocation's symbol
  1611. Expected<COFFSymbolRef> Sym = Obj->getSymbol(R.SymbolTableIndex);
  1612. if (!Sym)
  1613. return Sym.takeError();
  1614. // And the symbol's section
  1615. Expected<const coff_section *> Section =
  1616. Obj->getSection(Sym->getSectionNumber());
  1617. if (!Section)
  1618. return Section.takeError();
  1619. // Add the initial value of DataRVA to the symbol's offset to find the
  1620. // data it points at.
  1621. uint64_t Offset = Entry.DataRVA + Sym->getValue();
  1622. ArrayRef<uint8_t> Contents;
  1623. if (Error E = Obj->getSectionContents(*Section, Contents))
  1624. return std::move(E);
  1625. if (Offset + Entry.DataSize > Contents.size())
  1626. return createStringError(object_error::parse_failed,
  1627. "data outside of section");
  1628. // Return a reference to the data inside the section.
  1629. return StringRef(reinterpret_cast<const char *>(Contents.data()) + Offset,
  1630. Entry.DataSize);
  1631. } else {
  1632. // Relocatable objects need a relocation for the DataRVA field.
  1633. if (Obj->isRelocatableObject())
  1634. return createStringError(object_error::parse_failed,
  1635. "no relocation found for DataRVA");
  1636. // Locate the section that contains the address that DataRVA points at.
  1637. uint64_t VA = Entry.DataRVA + Obj->getImageBase();
  1638. for (const SectionRef &S : Obj->sections()) {
  1639. if (VA >= S.getAddress() &&
  1640. VA + Entry.DataSize <= S.getAddress() + S.getSize()) {
  1641. uint64_t Offset = VA - S.getAddress();
  1642. Expected<StringRef> Contents = S.getContents();
  1643. if (!Contents)
  1644. return Contents.takeError();
  1645. return Contents->slice(Offset, Offset + Entry.DataSize);
  1646. }
  1647. }
  1648. return createStringError(object_error::parse_failed,
  1649. "address not found in image");
  1650. }
  1651. }