XCOFFObjectFile.cpp 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491
  1. //===--- XCOFFObjectFile.cpp - XCOFF 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 defines the XCOFFObjectFile class.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/Object/XCOFFObjectFile.h"
  13. #include "llvm/ADT/StringSwitch.h"
  14. #include "llvm/MC/SubtargetFeature.h"
  15. #include "llvm/Support/DataExtractor.h"
  16. #include <cstddef>
  17. #include <cstring>
  18. namespace llvm {
  19. using namespace XCOFF;
  20. namespace object {
  21. static const uint8_t FunctionSym = 0x20;
  22. static const uint16_t NoRelMask = 0x0001;
  23. static const size_t SymbolAuxTypeOffset = 17;
  24. // Checks that [Ptr, Ptr + Size) bytes fall inside the memory buffer
  25. // 'M'. Returns a pointer to the underlying object on success.
  26. template <typename T>
  27. static Expected<const T *> getObject(MemoryBufferRef M, const void *Ptr,
  28. const uint64_t Size = sizeof(T)) {
  29. uintptr_t Addr = reinterpret_cast<uintptr_t>(Ptr);
  30. if (Error E = Binary::checkOffset(M, Addr, Size))
  31. return std::move(E);
  32. return reinterpret_cast<const T *>(Addr);
  33. }
  34. static uintptr_t getWithOffset(uintptr_t Base, ptrdiff_t Offset) {
  35. return reinterpret_cast<uintptr_t>(reinterpret_cast<const char *>(Base) +
  36. Offset);
  37. }
  38. template <typename T> static const T *viewAs(uintptr_t in) {
  39. return reinterpret_cast<const T *>(in);
  40. }
  41. static StringRef generateXCOFFFixedNameStringRef(const char *Name) {
  42. auto NulCharPtr =
  43. static_cast<const char *>(memchr(Name, '\0', XCOFF::NameSize));
  44. return NulCharPtr ? StringRef(Name, NulCharPtr - Name)
  45. : StringRef(Name, XCOFF::NameSize);
  46. }
  47. template <typename T> StringRef XCOFFSectionHeader<T>::getName() const {
  48. const T &DerivedXCOFFSectionHeader = static_cast<const T &>(*this);
  49. return generateXCOFFFixedNameStringRef(DerivedXCOFFSectionHeader.Name);
  50. }
  51. template <typename T> uint16_t XCOFFSectionHeader<T>::getSectionType() const {
  52. const T &DerivedXCOFFSectionHeader = static_cast<const T &>(*this);
  53. return DerivedXCOFFSectionHeader.Flags & SectionFlagsTypeMask;
  54. }
  55. template <typename T>
  56. bool XCOFFSectionHeader<T>::isReservedSectionType() const {
  57. return getSectionType() & SectionFlagsReservedMask;
  58. }
  59. template <typename AddressType>
  60. bool XCOFFRelocation<AddressType>::isRelocationSigned() const {
  61. return Info & XR_SIGN_INDICATOR_MASK;
  62. }
  63. template <typename AddressType>
  64. bool XCOFFRelocation<AddressType>::isFixupIndicated() const {
  65. return Info & XR_FIXUP_INDICATOR_MASK;
  66. }
  67. template <typename AddressType>
  68. uint8_t XCOFFRelocation<AddressType>::getRelocatedLength() const {
  69. // The relocation encodes the bit length being relocated minus 1. Add back
  70. // the 1 to get the actual length being relocated.
  71. return (Info & XR_BIASED_LENGTH_MASK) + 1;
  72. }
  73. uintptr_t
  74. XCOFFObjectFile::getAdvancedSymbolEntryAddress(uintptr_t CurrentAddress,
  75. uint32_t Distance) {
  76. return getWithOffset(CurrentAddress, Distance * XCOFF::SymbolTableEntrySize);
  77. }
  78. const XCOFF::SymbolAuxType *
  79. XCOFFObjectFile::getSymbolAuxType(uintptr_t AuxEntryAddress) const {
  80. assert(is64Bit() && "64-bit interface called on a 32-bit object file.");
  81. return viewAs<XCOFF::SymbolAuxType>(
  82. getWithOffset(AuxEntryAddress, SymbolAuxTypeOffset));
  83. }
  84. void XCOFFObjectFile::checkSectionAddress(uintptr_t Addr,
  85. uintptr_t TableAddress) const {
  86. if (Addr < TableAddress)
  87. report_fatal_error("Section header outside of section header table.");
  88. uintptr_t Offset = Addr - TableAddress;
  89. if (Offset >= getSectionHeaderSize() * getNumberOfSections())
  90. report_fatal_error("Section header outside of section header table.");
  91. if (Offset % getSectionHeaderSize() != 0)
  92. report_fatal_error(
  93. "Section header pointer does not point to a valid section header.");
  94. }
  95. const XCOFFSectionHeader32 *
  96. XCOFFObjectFile::toSection32(DataRefImpl Ref) const {
  97. assert(!is64Bit() && "32-bit interface called on 64-bit object file.");
  98. #ifndef NDEBUG
  99. checkSectionAddress(Ref.p, getSectionHeaderTableAddress());
  100. #endif
  101. return viewAs<XCOFFSectionHeader32>(Ref.p);
  102. }
  103. const XCOFFSectionHeader64 *
  104. XCOFFObjectFile::toSection64(DataRefImpl Ref) const {
  105. assert(is64Bit() && "64-bit interface called on a 32-bit object file.");
  106. #ifndef NDEBUG
  107. checkSectionAddress(Ref.p, getSectionHeaderTableAddress());
  108. #endif
  109. return viewAs<XCOFFSectionHeader64>(Ref.p);
  110. }
  111. XCOFFSymbolRef XCOFFObjectFile::toSymbolRef(DataRefImpl Ref) const {
  112. assert(Ref.p != 0 && "Symbol table pointer can not be nullptr!");
  113. #ifndef NDEBUG
  114. checkSymbolEntryPointer(Ref.p);
  115. #endif
  116. return XCOFFSymbolRef(Ref, this);
  117. }
  118. const XCOFFFileHeader32 *XCOFFObjectFile::fileHeader32() const {
  119. assert(!is64Bit() && "32-bit interface called on 64-bit object file.");
  120. return static_cast<const XCOFFFileHeader32 *>(FileHeader);
  121. }
  122. const XCOFFFileHeader64 *XCOFFObjectFile::fileHeader64() const {
  123. assert(is64Bit() && "64-bit interface called on a 32-bit object file.");
  124. return static_cast<const XCOFFFileHeader64 *>(FileHeader);
  125. }
  126. const XCOFFAuxiliaryHeader32 *XCOFFObjectFile::auxiliaryHeader32() const {
  127. assert(!is64Bit() && "32-bit interface called on 64-bit object file.");
  128. return static_cast<const XCOFFAuxiliaryHeader32 *>(AuxiliaryHeader);
  129. }
  130. const XCOFFAuxiliaryHeader64 *XCOFFObjectFile::auxiliaryHeader64() const {
  131. assert(is64Bit() && "64-bit interface called on a 32-bit object file.");
  132. return static_cast<const XCOFFAuxiliaryHeader64 *>(AuxiliaryHeader);
  133. }
  134. template <typename T> const T *XCOFFObjectFile::sectionHeaderTable() const {
  135. return static_cast<const T *>(SectionHeaderTable);
  136. }
  137. const XCOFFSectionHeader32 *
  138. XCOFFObjectFile::sectionHeaderTable32() const {
  139. assert(!is64Bit() && "32-bit interface called on 64-bit object file.");
  140. return static_cast<const XCOFFSectionHeader32 *>(SectionHeaderTable);
  141. }
  142. const XCOFFSectionHeader64 *
  143. XCOFFObjectFile::sectionHeaderTable64() const {
  144. assert(is64Bit() && "64-bit interface called on a 32-bit object file.");
  145. return static_cast<const XCOFFSectionHeader64 *>(SectionHeaderTable);
  146. }
  147. void XCOFFObjectFile::moveSymbolNext(DataRefImpl &Symb) const {
  148. uintptr_t NextSymbolAddr = getAdvancedSymbolEntryAddress(
  149. Symb.p, toSymbolRef(Symb).getNumberOfAuxEntries() + 1);
  150. #ifndef NDEBUG
  151. // This function is used by basic_symbol_iterator, which allows to
  152. // point to the end-of-symbol-table address.
  153. if (NextSymbolAddr != getEndOfSymbolTableAddress())
  154. checkSymbolEntryPointer(NextSymbolAddr);
  155. #endif
  156. Symb.p = NextSymbolAddr;
  157. }
  158. Expected<StringRef>
  159. XCOFFObjectFile::getStringTableEntry(uint32_t Offset) const {
  160. // The byte offset is relative to the start of the string table.
  161. // A byte offset value of 0 is a null or zero-length symbol
  162. // name. A byte offset in the range 1 to 3 (inclusive) points into the length
  163. // field; as a soft-error recovery mechanism, we treat such cases as having an
  164. // offset of 0.
  165. if (Offset < 4)
  166. return StringRef(nullptr, 0);
  167. if (StringTable.Data != nullptr && StringTable.Size > Offset)
  168. return (StringTable.Data + Offset);
  169. return createError("entry with offset 0x" + Twine::utohexstr(Offset) +
  170. " in a string table with size 0x" +
  171. Twine::utohexstr(StringTable.Size) + " is invalid");
  172. }
  173. StringRef XCOFFObjectFile::getStringTable() const {
  174. // If the size is less than or equal to 4, then the string table contains no
  175. // string data.
  176. return StringRef(StringTable.Data,
  177. StringTable.Size <= 4 ? 0 : StringTable.Size);
  178. }
  179. Expected<StringRef>
  180. XCOFFObjectFile::getCFileName(const XCOFFFileAuxEnt *CFileEntPtr) const {
  181. if (CFileEntPtr->NameInStrTbl.Magic != XCOFFSymbolRef::NAME_IN_STR_TBL_MAGIC)
  182. return generateXCOFFFixedNameStringRef(CFileEntPtr->Name);
  183. return getStringTableEntry(CFileEntPtr->NameInStrTbl.Offset);
  184. }
  185. Expected<StringRef> XCOFFObjectFile::getSymbolName(DataRefImpl Symb) const {
  186. return toSymbolRef(Symb).getName();
  187. }
  188. Expected<uint64_t> XCOFFObjectFile::getSymbolAddress(DataRefImpl Symb) const {
  189. return toSymbolRef(Symb).getValue();
  190. }
  191. uint64_t XCOFFObjectFile::getSymbolValueImpl(DataRefImpl Symb) const {
  192. return toSymbolRef(Symb).getValue();
  193. }
  194. uint32_t XCOFFObjectFile::getSymbolAlignment(DataRefImpl Symb) const {
  195. uint64_t Result = 0;
  196. XCOFFSymbolRef XCOFFSym = toSymbolRef(Symb);
  197. if (XCOFFSym.isCsectSymbol()) {
  198. Expected<XCOFFCsectAuxRef> CsectAuxRefOrError =
  199. XCOFFSym.getXCOFFCsectAuxRef();
  200. if (!CsectAuxRefOrError)
  201. // TODO: report the error up the stack.
  202. consumeError(CsectAuxRefOrError.takeError());
  203. else
  204. Result = 1ULL << CsectAuxRefOrError.get().getAlignmentLog2();
  205. }
  206. return Result;
  207. }
  208. uint64_t XCOFFObjectFile::getCommonSymbolSizeImpl(DataRefImpl Symb) const {
  209. uint64_t Result = 0;
  210. XCOFFSymbolRef XCOFFSym = toSymbolRef(Symb);
  211. if (XCOFFSym.isCsectSymbol()) {
  212. Expected<XCOFFCsectAuxRef> CsectAuxRefOrError =
  213. XCOFFSym.getXCOFFCsectAuxRef();
  214. if (!CsectAuxRefOrError)
  215. // TODO: report the error up the stack.
  216. consumeError(CsectAuxRefOrError.takeError());
  217. else {
  218. XCOFFCsectAuxRef CsectAuxRef = CsectAuxRefOrError.get();
  219. assert(CsectAuxRef.getSymbolType() == XCOFF::XTY_CM);
  220. Result = CsectAuxRef.getSectionOrLength();
  221. }
  222. }
  223. return Result;
  224. }
  225. Expected<SymbolRef::Type>
  226. XCOFFObjectFile::getSymbolType(DataRefImpl Symb) const {
  227. XCOFFSymbolRef XCOFFSym = toSymbolRef(Symb);
  228. if (XCOFFSym.isFunction())
  229. return SymbolRef::ST_Function;
  230. if (XCOFF::C_FILE == XCOFFSym.getStorageClass())
  231. return SymbolRef::ST_File;
  232. int16_t SecNum = XCOFFSym.getSectionNumber();
  233. if (SecNum <= 0)
  234. return SymbolRef::ST_Other;
  235. Expected<DataRefImpl> SecDRIOrErr =
  236. getSectionByNum(XCOFFSym.getSectionNumber());
  237. if (!SecDRIOrErr)
  238. return SecDRIOrErr.takeError();
  239. DataRefImpl SecDRI = SecDRIOrErr.get();
  240. Expected<StringRef> SymNameOrError = XCOFFSym.getName();
  241. if (SymNameOrError) {
  242. // The "TOC" symbol is treated as SymbolRef::ST_Other.
  243. if (SymNameOrError.get() == "TOC")
  244. return SymbolRef::ST_Other;
  245. // The symbol for a section name is treated as SymbolRef::ST_Other.
  246. StringRef SecName;
  247. if (is64Bit())
  248. SecName = XCOFFObjectFile::toSection64(SecDRIOrErr.get())->getName();
  249. else
  250. SecName = XCOFFObjectFile::toSection32(SecDRIOrErr.get())->getName();
  251. if (SecName == SymNameOrError.get())
  252. return SymbolRef::ST_Other;
  253. } else
  254. return SymNameOrError.takeError();
  255. if (isSectionData(SecDRI) || isSectionBSS(SecDRI))
  256. return SymbolRef::ST_Data;
  257. if (isDebugSection(SecDRI))
  258. return SymbolRef::ST_Debug;
  259. return SymbolRef::ST_Other;
  260. }
  261. Expected<section_iterator>
  262. XCOFFObjectFile::getSymbolSection(DataRefImpl Symb) const {
  263. const int16_t SectNum = toSymbolRef(Symb).getSectionNumber();
  264. if (isReservedSectionNumber(SectNum))
  265. return section_end();
  266. Expected<DataRefImpl> ExpSec = getSectionByNum(SectNum);
  267. if (!ExpSec)
  268. return ExpSec.takeError();
  269. return section_iterator(SectionRef(ExpSec.get(), this));
  270. }
  271. void XCOFFObjectFile::moveSectionNext(DataRefImpl &Sec) const {
  272. const char *Ptr = reinterpret_cast<const char *>(Sec.p);
  273. Sec.p = reinterpret_cast<uintptr_t>(Ptr + getSectionHeaderSize());
  274. }
  275. Expected<StringRef> XCOFFObjectFile::getSectionName(DataRefImpl Sec) const {
  276. return generateXCOFFFixedNameStringRef(getSectionNameInternal(Sec));
  277. }
  278. uint64_t XCOFFObjectFile::getSectionAddress(DataRefImpl Sec) const {
  279. // Avoid ternary due to failure to convert the ubig32_t value to a unit64_t
  280. // with MSVC.
  281. if (is64Bit())
  282. return toSection64(Sec)->VirtualAddress;
  283. return toSection32(Sec)->VirtualAddress;
  284. }
  285. uint64_t XCOFFObjectFile::getSectionIndex(DataRefImpl Sec) const {
  286. // Section numbers in XCOFF are numbered beginning at 1. A section number of
  287. // zero is used to indicate that a symbol is being imported or is undefined.
  288. if (is64Bit())
  289. return toSection64(Sec) - sectionHeaderTable64() + 1;
  290. else
  291. return toSection32(Sec) - sectionHeaderTable32() + 1;
  292. }
  293. uint64_t XCOFFObjectFile::getSectionSize(DataRefImpl Sec) const {
  294. // Avoid ternary due to failure to convert the ubig32_t value to a unit64_t
  295. // with MSVC.
  296. if (is64Bit())
  297. return toSection64(Sec)->SectionSize;
  298. return toSection32(Sec)->SectionSize;
  299. }
  300. Expected<ArrayRef<uint8_t>>
  301. XCOFFObjectFile::getSectionContents(DataRefImpl Sec) const {
  302. if (isSectionVirtual(Sec))
  303. return ArrayRef<uint8_t>();
  304. uint64_t OffsetToRaw;
  305. if (is64Bit())
  306. OffsetToRaw = toSection64(Sec)->FileOffsetToRawData;
  307. else
  308. OffsetToRaw = toSection32(Sec)->FileOffsetToRawData;
  309. const uint8_t * ContentStart = base() + OffsetToRaw;
  310. uint64_t SectionSize = getSectionSize(Sec);
  311. if (Error E = Binary::checkOffset(
  312. Data, reinterpret_cast<uintptr_t>(ContentStart), SectionSize))
  313. return createError(
  314. toString(std::move(E)) + ": section data with offset 0x" +
  315. Twine::utohexstr(OffsetToRaw) + " and size 0x" +
  316. Twine::utohexstr(SectionSize) + " goes past the end of the file");
  317. return makeArrayRef(ContentStart,SectionSize);
  318. }
  319. uint64_t XCOFFObjectFile::getSectionAlignment(DataRefImpl Sec) const {
  320. uint64_t Result = 0;
  321. llvm_unreachable("Not yet implemented!");
  322. return Result;
  323. }
  324. Expected<uintptr_t> XCOFFObjectFile::getLoaderSectionAddress() const {
  325. uint64_t OffsetToLoaderSection = 0;
  326. uint64_t SizeOfLoaderSection = 0;
  327. if (is64Bit()) {
  328. for (const auto &Sec64 : sections64())
  329. if (Sec64.getSectionType() == XCOFF::STYP_LOADER) {
  330. OffsetToLoaderSection = Sec64.FileOffsetToRawData;
  331. SizeOfLoaderSection = Sec64.SectionSize;
  332. break;
  333. }
  334. } else {
  335. for (const auto &Sec32 : sections32())
  336. if (Sec32.getSectionType() == XCOFF::STYP_LOADER) {
  337. OffsetToLoaderSection = Sec32.FileOffsetToRawData;
  338. SizeOfLoaderSection = Sec32.SectionSize;
  339. break;
  340. }
  341. }
  342. // No loader section is not an error.
  343. if (!SizeOfLoaderSection)
  344. return 0;
  345. uintptr_t LoderSectionStart =
  346. reinterpret_cast<uintptr_t>(base() + OffsetToLoaderSection);
  347. if (Error E =
  348. Binary::checkOffset(Data, LoderSectionStart, SizeOfLoaderSection))
  349. return createError(toString(std::move(E)) +
  350. ": loader section with offset 0x" +
  351. Twine::utohexstr(OffsetToLoaderSection) +
  352. " and size 0x" + Twine::utohexstr(SizeOfLoaderSection) +
  353. " goes past the end of the file");
  354. return LoderSectionStart;
  355. }
  356. bool XCOFFObjectFile::isSectionCompressed(DataRefImpl Sec) const {
  357. return false;
  358. }
  359. bool XCOFFObjectFile::isSectionText(DataRefImpl Sec) const {
  360. return getSectionFlags(Sec) & XCOFF::STYP_TEXT;
  361. }
  362. bool XCOFFObjectFile::isSectionData(DataRefImpl Sec) const {
  363. uint32_t Flags = getSectionFlags(Sec);
  364. return Flags & (XCOFF::STYP_DATA | XCOFF::STYP_TDATA);
  365. }
  366. bool XCOFFObjectFile::isSectionBSS(DataRefImpl Sec) const {
  367. uint32_t Flags = getSectionFlags(Sec);
  368. return Flags & (XCOFF::STYP_BSS | XCOFF::STYP_TBSS);
  369. }
  370. bool XCOFFObjectFile::isDebugSection(DataRefImpl Sec) const {
  371. uint32_t Flags = getSectionFlags(Sec);
  372. return Flags & (XCOFF::STYP_DEBUG | XCOFF::STYP_DWARF);
  373. }
  374. bool XCOFFObjectFile::isSectionVirtual(DataRefImpl Sec) const {
  375. return is64Bit() ? toSection64(Sec)->FileOffsetToRawData == 0
  376. : toSection32(Sec)->FileOffsetToRawData == 0;
  377. }
  378. relocation_iterator XCOFFObjectFile::section_rel_begin(DataRefImpl Sec) const {
  379. DataRefImpl Ret;
  380. if (is64Bit()) {
  381. const XCOFFSectionHeader64 *SectionEntPtr = toSection64(Sec);
  382. auto RelocationsOrErr =
  383. relocations<XCOFFSectionHeader64, XCOFFRelocation64>(*SectionEntPtr);
  384. if (Error E = RelocationsOrErr.takeError()) {
  385. // TODO: report the error up the stack.
  386. consumeError(std::move(E));
  387. return relocation_iterator(RelocationRef());
  388. }
  389. Ret.p = reinterpret_cast<uintptr_t>(&*RelocationsOrErr.get().begin());
  390. } else {
  391. const XCOFFSectionHeader32 *SectionEntPtr = toSection32(Sec);
  392. auto RelocationsOrErr =
  393. relocations<XCOFFSectionHeader32, XCOFFRelocation32>(*SectionEntPtr);
  394. if (Error E = RelocationsOrErr.takeError()) {
  395. // TODO: report the error up the stack.
  396. consumeError(std::move(E));
  397. return relocation_iterator(RelocationRef());
  398. }
  399. Ret.p = reinterpret_cast<uintptr_t>(&*RelocationsOrErr.get().begin());
  400. }
  401. return relocation_iterator(RelocationRef(Ret, this));
  402. }
  403. relocation_iterator XCOFFObjectFile::section_rel_end(DataRefImpl Sec) const {
  404. DataRefImpl Ret;
  405. if (is64Bit()) {
  406. const XCOFFSectionHeader64 *SectionEntPtr = toSection64(Sec);
  407. auto RelocationsOrErr =
  408. relocations<XCOFFSectionHeader64, XCOFFRelocation64>(*SectionEntPtr);
  409. if (Error E = RelocationsOrErr.takeError()) {
  410. // TODO: report the error up the stack.
  411. consumeError(std::move(E));
  412. return relocation_iterator(RelocationRef());
  413. }
  414. Ret.p = reinterpret_cast<uintptr_t>(&*RelocationsOrErr.get().end());
  415. } else {
  416. const XCOFFSectionHeader32 *SectionEntPtr = toSection32(Sec);
  417. auto RelocationsOrErr =
  418. relocations<XCOFFSectionHeader32, XCOFFRelocation32>(*SectionEntPtr);
  419. if (Error E = RelocationsOrErr.takeError()) {
  420. // TODO: report the error up the stack.
  421. consumeError(std::move(E));
  422. return relocation_iterator(RelocationRef());
  423. }
  424. Ret.p = reinterpret_cast<uintptr_t>(&*RelocationsOrErr.get().end());
  425. }
  426. return relocation_iterator(RelocationRef(Ret, this));
  427. }
  428. void XCOFFObjectFile::moveRelocationNext(DataRefImpl &Rel) const {
  429. if (is64Bit())
  430. Rel.p = reinterpret_cast<uintptr_t>(viewAs<XCOFFRelocation64>(Rel.p) + 1);
  431. else
  432. Rel.p = reinterpret_cast<uintptr_t>(viewAs<XCOFFRelocation32>(Rel.p) + 1);
  433. }
  434. uint64_t XCOFFObjectFile::getRelocationOffset(DataRefImpl Rel) const {
  435. if (is64Bit()) {
  436. const XCOFFRelocation64 *Reloc = viewAs<XCOFFRelocation64>(Rel.p);
  437. const XCOFFSectionHeader64 *Sec64 = sectionHeaderTable64();
  438. const uint64_t RelocAddress = Reloc->VirtualAddress;
  439. const uint16_t NumberOfSections = getNumberOfSections();
  440. for (uint16_t I = 0; I < NumberOfSections; ++I) {
  441. // Find which section this relocation belongs to, and get the
  442. // relocation offset relative to the start of the section.
  443. if (Sec64->VirtualAddress <= RelocAddress &&
  444. RelocAddress < Sec64->VirtualAddress + Sec64->SectionSize) {
  445. return RelocAddress - Sec64->VirtualAddress;
  446. }
  447. ++Sec64;
  448. }
  449. } else {
  450. const XCOFFRelocation32 *Reloc = viewAs<XCOFFRelocation32>(Rel.p);
  451. const XCOFFSectionHeader32 *Sec32 = sectionHeaderTable32();
  452. const uint32_t RelocAddress = Reloc->VirtualAddress;
  453. const uint16_t NumberOfSections = getNumberOfSections();
  454. for (uint16_t I = 0; I < NumberOfSections; ++I) {
  455. // Find which section this relocation belongs to, and get the
  456. // relocation offset relative to the start of the section.
  457. if (Sec32->VirtualAddress <= RelocAddress &&
  458. RelocAddress < Sec32->VirtualAddress + Sec32->SectionSize) {
  459. return RelocAddress - Sec32->VirtualAddress;
  460. }
  461. ++Sec32;
  462. }
  463. }
  464. return InvalidRelocOffset;
  465. }
  466. symbol_iterator XCOFFObjectFile::getRelocationSymbol(DataRefImpl Rel) const {
  467. uint32_t Index;
  468. if (is64Bit()) {
  469. const XCOFFRelocation64 *Reloc = viewAs<XCOFFRelocation64>(Rel.p);
  470. Index = Reloc->SymbolIndex;
  471. if (Index >= getNumberOfSymbolTableEntries64())
  472. return symbol_end();
  473. } else {
  474. const XCOFFRelocation32 *Reloc = viewAs<XCOFFRelocation32>(Rel.p);
  475. Index = Reloc->SymbolIndex;
  476. if (Index >= getLogicalNumberOfSymbolTableEntries32())
  477. return symbol_end();
  478. }
  479. DataRefImpl SymDRI;
  480. SymDRI.p = getSymbolEntryAddressByIndex(Index);
  481. return symbol_iterator(SymbolRef(SymDRI, this));
  482. }
  483. uint64_t XCOFFObjectFile::getRelocationType(DataRefImpl Rel) const {
  484. if (is64Bit())
  485. return viewAs<XCOFFRelocation64>(Rel.p)->Type;
  486. return viewAs<XCOFFRelocation32>(Rel.p)->Type;
  487. }
  488. void XCOFFObjectFile::getRelocationTypeName(
  489. DataRefImpl Rel, SmallVectorImpl<char> &Result) const {
  490. StringRef Res;
  491. if (is64Bit()) {
  492. const XCOFFRelocation64 *Reloc = viewAs<XCOFFRelocation64>(Rel.p);
  493. Res = XCOFF::getRelocationTypeString(Reloc->Type);
  494. } else {
  495. const XCOFFRelocation32 *Reloc = viewAs<XCOFFRelocation32>(Rel.p);
  496. Res = XCOFF::getRelocationTypeString(Reloc->Type);
  497. }
  498. Result.append(Res.begin(), Res.end());
  499. }
  500. Expected<uint32_t> XCOFFObjectFile::getSymbolFlags(DataRefImpl Symb) const {
  501. XCOFFSymbolRef XCOFFSym = toSymbolRef(Symb);
  502. uint32_t Result = SymbolRef::SF_None;
  503. if (XCOFFSym.getSectionNumber() == XCOFF::N_ABS)
  504. Result |= SymbolRef::SF_Absolute;
  505. XCOFF::StorageClass SC = XCOFFSym.getStorageClass();
  506. if (XCOFF::C_EXT == SC || XCOFF::C_WEAKEXT == SC)
  507. Result |= SymbolRef::SF_Global;
  508. if (XCOFF::C_WEAKEXT == SC)
  509. Result |= SymbolRef::SF_Weak;
  510. if (XCOFFSym.isCsectSymbol()) {
  511. Expected<XCOFFCsectAuxRef> CsectAuxEntOrErr =
  512. XCOFFSym.getXCOFFCsectAuxRef();
  513. if (CsectAuxEntOrErr) {
  514. if (CsectAuxEntOrErr.get().getSymbolType() == XCOFF::XTY_CM)
  515. Result |= SymbolRef::SF_Common;
  516. } else
  517. return CsectAuxEntOrErr.takeError();
  518. }
  519. if (XCOFFSym.getSectionNumber() == XCOFF::N_UNDEF)
  520. Result |= SymbolRef::SF_Undefined;
  521. return Result;
  522. }
  523. basic_symbol_iterator XCOFFObjectFile::symbol_begin() const {
  524. DataRefImpl SymDRI;
  525. SymDRI.p = reinterpret_cast<uintptr_t>(SymbolTblPtr);
  526. return basic_symbol_iterator(SymbolRef(SymDRI, this));
  527. }
  528. basic_symbol_iterator XCOFFObjectFile::symbol_end() const {
  529. DataRefImpl SymDRI;
  530. const uint32_t NumberOfSymbolTableEntries = getNumberOfSymbolTableEntries();
  531. SymDRI.p = getSymbolEntryAddressByIndex(NumberOfSymbolTableEntries);
  532. return basic_symbol_iterator(SymbolRef(SymDRI, this));
  533. }
  534. section_iterator XCOFFObjectFile::section_begin() const {
  535. DataRefImpl DRI;
  536. DRI.p = getSectionHeaderTableAddress();
  537. return section_iterator(SectionRef(DRI, this));
  538. }
  539. section_iterator XCOFFObjectFile::section_end() const {
  540. DataRefImpl DRI;
  541. DRI.p = getWithOffset(getSectionHeaderTableAddress(),
  542. getNumberOfSections() * getSectionHeaderSize());
  543. return section_iterator(SectionRef(DRI, this));
  544. }
  545. uint8_t XCOFFObjectFile::getBytesInAddress() const { return is64Bit() ? 8 : 4; }
  546. StringRef XCOFFObjectFile::getFileFormatName() const {
  547. return is64Bit() ? "aix5coff64-rs6000" : "aixcoff-rs6000";
  548. }
  549. Triple::ArchType XCOFFObjectFile::getArch() const {
  550. return is64Bit() ? Triple::ppc64 : Triple::ppc;
  551. }
  552. SubtargetFeatures XCOFFObjectFile::getFeatures() const {
  553. return SubtargetFeatures();
  554. }
  555. bool XCOFFObjectFile::isRelocatableObject() const {
  556. if (is64Bit())
  557. return !(fileHeader64()->Flags & NoRelMask);
  558. return !(fileHeader32()->Flags & NoRelMask);
  559. }
  560. Expected<uint64_t> XCOFFObjectFile::getStartAddress() const {
  561. // TODO FIXME Should get from auxiliary_header->o_entry when support for the
  562. // auxiliary_header is added.
  563. return 0;
  564. }
  565. StringRef XCOFFObjectFile::mapDebugSectionName(StringRef Name) const {
  566. return StringSwitch<StringRef>(Name)
  567. .Case("dwinfo", "debug_info")
  568. .Case("dwline", "debug_line")
  569. .Case("dwpbnms", "debug_pubnames")
  570. .Case("dwpbtyp", "debug_pubtypes")
  571. .Case("dwarnge", "debug_aranges")
  572. .Case("dwabrev", "debug_abbrev")
  573. .Case("dwstr", "debug_str")
  574. .Case("dwrnges", "debug_ranges")
  575. .Case("dwloc", "debug_loc")
  576. .Case("dwframe", "debug_frame")
  577. .Case("dwmac", "debug_macinfo")
  578. .Default(Name);
  579. }
  580. size_t XCOFFObjectFile::getFileHeaderSize() const {
  581. return is64Bit() ? sizeof(XCOFFFileHeader64) : sizeof(XCOFFFileHeader32);
  582. }
  583. size_t XCOFFObjectFile::getSectionHeaderSize() const {
  584. return is64Bit() ? sizeof(XCOFFSectionHeader64) :
  585. sizeof(XCOFFSectionHeader32);
  586. }
  587. bool XCOFFObjectFile::is64Bit() const {
  588. return Binary::ID_XCOFF64 == getType();
  589. }
  590. uint16_t XCOFFObjectFile::getMagic() const {
  591. return is64Bit() ? fileHeader64()->Magic : fileHeader32()->Magic;
  592. }
  593. Expected<DataRefImpl> XCOFFObjectFile::getSectionByNum(int16_t Num) const {
  594. if (Num <= 0 || Num > getNumberOfSections())
  595. return createStringError(object_error::invalid_section_index,
  596. "the section index (" + Twine(Num) +
  597. ") is invalid");
  598. DataRefImpl DRI;
  599. DRI.p = getWithOffset(getSectionHeaderTableAddress(),
  600. getSectionHeaderSize() * (Num - 1));
  601. return DRI;
  602. }
  603. Expected<StringRef>
  604. XCOFFObjectFile::getSymbolSectionName(XCOFFSymbolRef SymEntPtr) const {
  605. const int16_t SectionNum = SymEntPtr.getSectionNumber();
  606. switch (SectionNum) {
  607. case XCOFF::N_DEBUG:
  608. return "N_DEBUG";
  609. case XCOFF::N_ABS:
  610. return "N_ABS";
  611. case XCOFF::N_UNDEF:
  612. return "N_UNDEF";
  613. default:
  614. Expected<DataRefImpl> SecRef = getSectionByNum(SectionNum);
  615. if (SecRef)
  616. return generateXCOFFFixedNameStringRef(
  617. getSectionNameInternal(SecRef.get()));
  618. return SecRef.takeError();
  619. }
  620. }
  621. unsigned XCOFFObjectFile::getSymbolSectionID(SymbolRef Sym) const {
  622. XCOFFSymbolRef XCOFFSymRef(Sym.getRawDataRefImpl(), this);
  623. return XCOFFSymRef.getSectionNumber();
  624. }
  625. bool XCOFFObjectFile::isReservedSectionNumber(int16_t SectionNumber) {
  626. return (SectionNumber <= 0 && SectionNumber >= -2);
  627. }
  628. uint16_t XCOFFObjectFile::getNumberOfSections() const {
  629. return is64Bit() ? fileHeader64()->NumberOfSections
  630. : fileHeader32()->NumberOfSections;
  631. }
  632. int32_t XCOFFObjectFile::getTimeStamp() const {
  633. return is64Bit() ? fileHeader64()->TimeStamp : fileHeader32()->TimeStamp;
  634. }
  635. uint16_t XCOFFObjectFile::getOptionalHeaderSize() const {
  636. return is64Bit() ? fileHeader64()->AuxHeaderSize
  637. : fileHeader32()->AuxHeaderSize;
  638. }
  639. uint32_t XCOFFObjectFile::getSymbolTableOffset32() const {
  640. return fileHeader32()->SymbolTableOffset;
  641. }
  642. int32_t XCOFFObjectFile::getRawNumberOfSymbolTableEntries32() const {
  643. // As far as symbol table size is concerned, if this field is negative it is
  644. // to be treated as a 0. However since this field is also used for printing we
  645. // don't want to truncate any negative values.
  646. return fileHeader32()->NumberOfSymTableEntries;
  647. }
  648. uint32_t XCOFFObjectFile::getLogicalNumberOfSymbolTableEntries32() const {
  649. return (fileHeader32()->NumberOfSymTableEntries >= 0
  650. ? fileHeader32()->NumberOfSymTableEntries
  651. : 0);
  652. }
  653. uint64_t XCOFFObjectFile::getSymbolTableOffset64() const {
  654. return fileHeader64()->SymbolTableOffset;
  655. }
  656. uint32_t XCOFFObjectFile::getNumberOfSymbolTableEntries64() const {
  657. return fileHeader64()->NumberOfSymTableEntries;
  658. }
  659. uint32_t XCOFFObjectFile::getNumberOfSymbolTableEntries() const {
  660. return is64Bit() ? getNumberOfSymbolTableEntries64()
  661. : getLogicalNumberOfSymbolTableEntries32();
  662. }
  663. uintptr_t XCOFFObjectFile::getEndOfSymbolTableAddress() const {
  664. const uint32_t NumberOfSymTableEntries = getNumberOfSymbolTableEntries();
  665. return getWithOffset(reinterpret_cast<uintptr_t>(SymbolTblPtr),
  666. XCOFF::SymbolTableEntrySize * NumberOfSymTableEntries);
  667. }
  668. void XCOFFObjectFile::checkSymbolEntryPointer(uintptr_t SymbolEntPtr) const {
  669. if (SymbolEntPtr < reinterpret_cast<uintptr_t>(SymbolTblPtr))
  670. report_fatal_error("Symbol table entry is outside of symbol table.");
  671. if (SymbolEntPtr >= getEndOfSymbolTableAddress())
  672. report_fatal_error("Symbol table entry is outside of symbol table.");
  673. ptrdiff_t Offset = reinterpret_cast<const char *>(SymbolEntPtr) -
  674. reinterpret_cast<const char *>(SymbolTblPtr);
  675. if (Offset % XCOFF::SymbolTableEntrySize != 0)
  676. report_fatal_error(
  677. "Symbol table entry position is not valid inside of symbol table.");
  678. }
  679. uint32_t XCOFFObjectFile::getSymbolIndex(uintptr_t SymbolEntPtr) const {
  680. return (reinterpret_cast<const char *>(SymbolEntPtr) -
  681. reinterpret_cast<const char *>(SymbolTblPtr)) /
  682. XCOFF::SymbolTableEntrySize;
  683. }
  684. uint64_t XCOFFObjectFile::getSymbolSize(DataRefImpl Symb) const {
  685. uint64_t Result = 0;
  686. XCOFFSymbolRef XCOFFSym = toSymbolRef(Symb);
  687. if (XCOFFSym.isCsectSymbol()) {
  688. Expected<XCOFFCsectAuxRef> CsectAuxRefOrError =
  689. XCOFFSym.getXCOFFCsectAuxRef();
  690. if (!CsectAuxRefOrError)
  691. // TODO: report the error up the stack.
  692. consumeError(CsectAuxRefOrError.takeError());
  693. else {
  694. XCOFFCsectAuxRef CsectAuxRef = CsectAuxRefOrError.get();
  695. uint8_t SymType = CsectAuxRef.getSymbolType();
  696. if (SymType == XCOFF::XTY_SD || SymType == XCOFF::XTY_CM)
  697. Result = CsectAuxRef.getSectionOrLength();
  698. }
  699. }
  700. return Result;
  701. }
  702. uintptr_t XCOFFObjectFile::getSymbolEntryAddressByIndex(uint32_t Index) const {
  703. return getAdvancedSymbolEntryAddress(
  704. reinterpret_cast<uintptr_t>(getPointerToSymbolTable()), Index);
  705. }
  706. Expected<StringRef>
  707. XCOFFObjectFile::getSymbolNameByIndex(uint32_t Index) const {
  708. const uint32_t NumberOfSymTableEntries = getNumberOfSymbolTableEntries();
  709. if (Index >= NumberOfSymTableEntries)
  710. return createError("symbol index " + Twine(Index) +
  711. " exceeds symbol count " +
  712. Twine(NumberOfSymTableEntries));
  713. DataRefImpl SymDRI;
  714. SymDRI.p = getSymbolEntryAddressByIndex(Index);
  715. return getSymbolName(SymDRI);
  716. }
  717. uint16_t XCOFFObjectFile::getFlags() const {
  718. return is64Bit() ? fileHeader64()->Flags : fileHeader32()->Flags;
  719. }
  720. const char *XCOFFObjectFile::getSectionNameInternal(DataRefImpl Sec) const {
  721. return is64Bit() ? toSection64(Sec)->Name : toSection32(Sec)->Name;
  722. }
  723. uintptr_t XCOFFObjectFile::getSectionHeaderTableAddress() const {
  724. return reinterpret_cast<uintptr_t>(SectionHeaderTable);
  725. }
  726. int32_t XCOFFObjectFile::getSectionFlags(DataRefImpl Sec) const {
  727. return is64Bit() ? toSection64(Sec)->Flags : toSection32(Sec)->Flags;
  728. }
  729. XCOFFObjectFile::XCOFFObjectFile(unsigned int Type, MemoryBufferRef Object)
  730. : ObjectFile(Type, Object) {
  731. assert(Type == Binary::ID_XCOFF32 || Type == Binary::ID_XCOFF64);
  732. }
  733. ArrayRef<XCOFFSectionHeader64> XCOFFObjectFile::sections64() const {
  734. assert(is64Bit() && "64-bit interface called for non 64-bit file.");
  735. const XCOFFSectionHeader64 *TablePtr = sectionHeaderTable64();
  736. return ArrayRef<XCOFFSectionHeader64>(TablePtr,
  737. TablePtr + getNumberOfSections());
  738. }
  739. ArrayRef<XCOFFSectionHeader32> XCOFFObjectFile::sections32() const {
  740. assert(!is64Bit() && "32-bit interface called for non 32-bit file.");
  741. const XCOFFSectionHeader32 *TablePtr = sectionHeaderTable32();
  742. return ArrayRef<XCOFFSectionHeader32>(TablePtr,
  743. TablePtr + getNumberOfSections());
  744. }
  745. // In an XCOFF32 file, when the field value is 65535, then an STYP_OVRFLO
  746. // section header contains the actual count of relocation entries in the s_paddr
  747. // field. STYP_OVRFLO headers contain the section index of their corresponding
  748. // sections as their raw "NumberOfRelocations" field value.
  749. template <typename T>
  750. Expected<uint32_t> XCOFFObjectFile::getNumberOfRelocationEntries(
  751. const XCOFFSectionHeader<T> &Sec) const {
  752. const T &Section = static_cast<const T &>(Sec);
  753. if (is64Bit())
  754. return Section.NumberOfRelocations;
  755. uint16_t SectionIndex = &Section - sectionHeaderTable<T>() + 1;
  756. if (Section.NumberOfRelocations < XCOFF::RelocOverflow)
  757. return Section.NumberOfRelocations;
  758. for (const auto &Sec : sections32()) {
  759. if (Sec.Flags == XCOFF::STYP_OVRFLO &&
  760. Sec.NumberOfRelocations == SectionIndex)
  761. return Sec.PhysicalAddress;
  762. }
  763. return errorCodeToError(object_error::parse_failed);
  764. }
  765. template <typename Shdr, typename Reloc>
  766. Expected<ArrayRef<Reloc>> XCOFFObjectFile::relocations(const Shdr &Sec) const {
  767. uintptr_t RelocAddr = getWithOffset(reinterpret_cast<uintptr_t>(FileHeader),
  768. Sec.FileOffsetToRelocationInfo);
  769. auto NumRelocEntriesOrErr = getNumberOfRelocationEntries(Sec);
  770. if (Error E = NumRelocEntriesOrErr.takeError())
  771. return std::move(E);
  772. uint32_t NumRelocEntries = NumRelocEntriesOrErr.get();
  773. static_assert((sizeof(Reloc) == XCOFF::RelocationSerializationSize64 ||
  774. sizeof(Reloc) == XCOFF::RelocationSerializationSize32),
  775. "Relocation structure is incorrect");
  776. auto RelocationOrErr =
  777. getObject<Reloc>(Data, reinterpret_cast<void *>(RelocAddr),
  778. NumRelocEntries * sizeof(Reloc));
  779. if (!RelocationOrErr)
  780. return createError(
  781. toString(RelocationOrErr.takeError()) + ": relocations with offset 0x" +
  782. Twine::utohexstr(Sec.FileOffsetToRelocationInfo) + " and size 0x" +
  783. Twine::utohexstr(NumRelocEntries * sizeof(Reloc)) +
  784. " go past the end of the file");
  785. const Reloc *StartReloc = RelocationOrErr.get();
  786. return ArrayRef<Reloc>(StartReloc, StartReloc + NumRelocEntries);
  787. }
  788. Expected<XCOFFStringTable>
  789. XCOFFObjectFile::parseStringTable(const XCOFFObjectFile *Obj, uint64_t Offset) {
  790. // If there is a string table, then the buffer must contain at least 4 bytes
  791. // for the string table's size. Not having a string table is not an error.
  792. if (Error E = Binary::checkOffset(
  793. Obj->Data, reinterpret_cast<uintptr_t>(Obj->base() + Offset), 4)) {
  794. consumeError(std::move(E));
  795. return XCOFFStringTable{0, nullptr};
  796. }
  797. // Read the size out of the buffer.
  798. uint32_t Size = support::endian::read32be(Obj->base() + Offset);
  799. // If the size is less then 4, then the string table is just a size and no
  800. // string data.
  801. if (Size <= 4)
  802. return XCOFFStringTable{4, nullptr};
  803. auto StringTableOrErr =
  804. getObject<char>(Obj->Data, Obj->base() + Offset, Size);
  805. if (!StringTableOrErr)
  806. return createError(toString(StringTableOrErr.takeError()) +
  807. ": string table with offset 0x" +
  808. Twine::utohexstr(Offset) + " and size 0x" +
  809. Twine::utohexstr(Size) +
  810. " goes past the end of the file");
  811. const char *StringTablePtr = StringTableOrErr.get();
  812. if (StringTablePtr[Size - 1] != '\0')
  813. return errorCodeToError(object_error::string_table_non_null_end);
  814. return XCOFFStringTable{Size, StringTablePtr};
  815. }
  816. // This function returns the import file table. Each entry in the import file
  817. // table consists of: "path_name\0base_name\0archive_member_name\0".
  818. Expected<StringRef> XCOFFObjectFile::getImportFileTable() const {
  819. Expected<uintptr_t> LoaderSectionAddrOrError = getLoaderSectionAddress();
  820. if (!LoaderSectionAddrOrError)
  821. return LoaderSectionAddrOrError.takeError();
  822. uintptr_t LoaderSectionAddr = LoaderSectionAddrOrError.get();
  823. if (!LoaderSectionAddr)
  824. return StringRef();
  825. uint64_t OffsetToImportFileTable = 0;
  826. uint64_t LengthOfImportFileTable = 0;
  827. if (is64Bit()) {
  828. const LoaderSectionHeader64 *LoaderSec64 =
  829. viewAs<LoaderSectionHeader64>(LoaderSectionAddr);
  830. OffsetToImportFileTable = LoaderSec64->OffsetToImpid;
  831. LengthOfImportFileTable = LoaderSec64->LengthOfImpidStrTbl;
  832. } else {
  833. const LoaderSectionHeader32 *LoaderSec32 =
  834. viewAs<LoaderSectionHeader32>(LoaderSectionAddr);
  835. OffsetToImportFileTable = LoaderSec32->OffsetToImpid;
  836. LengthOfImportFileTable = LoaderSec32->LengthOfImpidStrTbl;
  837. }
  838. auto ImportTableOrErr = getObject<char>(
  839. Data,
  840. reinterpret_cast<void *>(LoaderSectionAddr + OffsetToImportFileTable),
  841. LengthOfImportFileTable);
  842. if (!ImportTableOrErr)
  843. return createError(
  844. toString(ImportTableOrErr.takeError()) +
  845. ": import file table with offset 0x" +
  846. Twine::utohexstr(LoaderSectionAddr + OffsetToImportFileTable) +
  847. " and size 0x" + Twine::utohexstr(LengthOfImportFileTable) +
  848. " goes past the end of the file");
  849. const char *ImportTablePtr = ImportTableOrErr.get();
  850. if (ImportTablePtr[LengthOfImportFileTable - 1] != '\0')
  851. return createError(
  852. ": import file name table with offset 0x" +
  853. Twine::utohexstr(LoaderSectionAddr + OffsetToImportFileTable) +
  854. " and size 0x" + Twine::utohexstr(LengthOfImportFileTable) +
  855. " must end with a null terminator");
  856. return StringRef(ImportTablePtr, LengthOfImportFileTable);
  857. }
  858. Expected<std::unique_ptr<XCOFFObjectFile>>
  859. XCOFFObjectFile::create(unsigned Type, MemoryBufferRef MBR) {
  860. // Can't use std::make_unique because of the private constructor.
  861. std::unique_ptr<XCOFFObjectFile> Obj;
  862. Obj.reset(new XCOFFObjectFile(Type, MBR));
  863. uint64_t CurOffset = 0;
  864. const auto *Base = Obj->base();
  865. MemoryBufferRef Data = Obj->Data;
  866. // Parse file header.
  867. auto FileHeaderOrErr =
  868. getObject<void>(Data, Base + CurOffset, Obj->getFileHeaderSize());
  869. if (Error E = FileHeaderOrErr.takeError())
  870. return std::move(E);
  871. Obj->FileHeader = FileHeaderOrErr.get();
  872. CurOffset += Obj->getFileHeaderSize();
  873. if (Obj->getOptionalHeaderSize()) {
  874. auto AuxiliaryHeaderOrErr =
  875. getObject<void>(Data, Base + CurOffset, Obj->getOptionalHeaderSize());
  876. if (Error E = AuxiliaryHeaderOrErr.takeError())
  877. return std::move(E);
  878. Obj->AuxiliaryHeader = AuxiliaryHeaderOrErr.get();
  879. }
  880. CurOffset += Obj->getOptionalHeaderSize();
  881. // Parse the section header table if it is present.
  882. if (Obj->getNumberOfSections()) {
  883. uint64_t SectionHeadersSize =
  884. Obj->getNumberOfSections() * Obj->getSectionHeaderSize();
  885. auto SecHeadersOrErr =
  886. getObject<void>(Data, Base + CurOffset, SectionHeadersSize);
  887. if (!SecHeadersOrErr)
  888. return createError(toString(SecHeadersOrErr.takeError()) +
  889. ": section headers with offset 0x" +
  890. Twine::utohexstr(CurOffset) + " and size 0x" +
  891. Twine::utohexstr(SectionHeadersSize) +
  892. " go past the end of the file");
  893. Obj->SectionHeaderTable = SecHeadersOrErr.get();
  894. }
  895. const uint32_t NumberOfSymbolTableEntries =
  896. Obj->getNumberOfSymbolTableEntries();
  897. // If there is no symbol table we are done parsing the memory buffer.
  898. if (NumberOfSymbolTableEntries == 0)
  899. return std::move(Obj);
  900. // Parse symbol table.
  901. CurOffset = Obj->is64Bit() ? Obj->getSymbolTableOffset64()
  902. : Obj->getSymbolTableOffset32();
  903. const uint64_t SymbolTableSize =
  904. static_cast<uint64_t>(XCOFF::SymbolTableEntrySize) *
  905. NumberOfSymbolTableEntries;
  906. auto SymTableOrErr =
  907. getObject<void *>(Data, Base + CurOffset, SymbolTableSize);
  908. if (!SymTableOrErr)
  909. return createError(
  910. toString(SymTableOrErr.takeError()) + ": symbol table with offset 0x" +
  911. Twine::utohexstr(CurOffset) + " and size 0x" +
  912. Twine::utohexstr(SymbolTableSize) + " goes past the end of the file");
  913. Obj->SymbolTblPtr = SymTableOrErr.get();
  914. CurOffset += SymbolTableSize;
  915. // Parse String table.
  916. Expected<XCOFFStringTable> StringTableOrErr =
  917. parseStringTable(Obj.get(), CurOffset);
  918. if (Error E = StringTableOrErr.takeError())
  919. return std::move(E);
  920. Obj->StringTable = StringTableOrErr.get();
  921. return std::move(Obj);
  922. }
  923. Expected<std::unique_ptr<ObjectFile>>
  924. ObjectFile::createXCOFFObjectFile(MemoryBufferRef MemBufRef,
  925. unsigned FileType) {
  926. return XCOFFObjectFile::create(FileType, MemBufRef);
  927. }
  928. bool XCOFFSymbolRef::isFunction() const {
  929. if (!isCsectSymbol())
  930. return false;
  931. if (getSymbolType() & FunctionSym)
  932. return true;
  933. Expected<XCOFFCsectAuxRef> ExpCsectAuxEnt = getXCOFFCsectAuxRef();
  934. if (!ExpCsectAuxEnt) {
  935. // If we could not get the CSECT auxiliary entry, then treat this symbol as
  936. // if it isn't a function. Consume the error and return `false` to move on.
  937. consumeError(ExpCsectAuxEnt.takeError());
  938. return false;
  939. }
  940. const XCOFFCsectAuxRef CsectAuxRef = ExpCsectAuxEnt.get();
  941. // A function definition should be a label definition.
  942. // FIXME: This is not necessarily the case when -ffunction-sections is
  943. // enabled.
  944. if (!CsectAuxRef.isLabel())
  945. return false;
  946. if (CsectAuxRef.getStorageMappingClass() != XCOFF::XMC_PR)
  947. return false;
  948. const int16_t SectNum = getSectionNumber();
  949. Expected<DataRefImpl> SI = OwningObjectPtr->getSectionByNum(SectNum);
  950. if (!SI) {
  951. // If we could not get the section, then this symbol should not be
  952. // a function. So consume the error and return `false` to move on.
  953. consumeError(SI.takeError());
  954. return false;
  955. }
  956. return (OwningObjectPtr->getSectionFlags(SI.get()) & XCOFF::STYP_TEXT);
  957. }
  958. bool XCOFFSymbolRef::isCsectSymbol() const {
  959. XCOFF::StorageClass SC = getStorageClass();
  960. return (SC == XCOFF::C_EXT || SC == XCOFF::C_WEAKEXT ||
  961. SC == XCOFF::C_HIDEXT);
  962. }
  963. Expected<XCOFFCsectAuxRef> XCOFFSymbolRef::getXCOFFCsectAuxRef() const {
  964. assert(isCsectSymbol() &&
  965. "Calling csect symbol interface with a non-csect symbol.");
  966. uint8_t NumberOfAuxEntries = getNumberOfAuxEntries();
  967. Expected<StringRef> NameOrErr = getName();
  968. if (auto Err = NameOrErr.takeError())
  969. return std::move(Err);
  970. uint32_t SymbolIdx = OwningObjectPtr->getSymbolIndex(getEntryAddress());
  971. if (!NumberOfAuxEntries) {
  972. return createError("csect symbol \"" + *NameOrErr + "\" with index " +
  973. Twine(SymbolIdx) + " contains no auxiliary entry");
  974. }
  975. if (!OwningObjectPtr->is64Bit()) {
  976. // In XCOFF32, the csect auxilliary entry is always the last auxiliary
  977. // entry for the symbol.
  978. uintptr_t AuxAddr = XCOFFObjectFile::getAdvancedSymbolEntryAddress(
  979. getEntryAddress(), NumberOfAuxEntries);
  980. return XCOFFCsectAuxRef(viewAs<XCOFFCsectAuxEnt32>(AuxAddr));
  981. }
  982. // XCOFF64 uses SymbolAuxType to identify the auxiliary entry type.
  983. // We need to iterate through all the auxiliary entries to find it.
  984. for (uint8_t Index = NumberOfAuxEntries; Index > 0; --Index) {
  985. uintptr_t AuxAddr = XCOFFObjectFile::getAdvancedSymbolEntryAddress(
  986. getEntryAddress(), Index);
  987. if (*OwningObjectPtr->getSymbolAuxType(AuxAddr) ==
  988. XCOFF::SymbolAuxType::AUX_CSECT) {
  989. #ifndef NDEBUG
  990. OwningObjectPtr->checkSymbolEntryPointer(AuxAddr);
  991. #endif
  992. return XCOFFCsectAuxRef(viewAs<XCOFFCsectAuxEnt64>(AuxAddr));
  993. }
  994. }
  995. return createError(
  996. "a csect auxiliary entry has not been found for symbol \"" + *NameOrErr +
  997. "\" with index " + Twine(SymbolIdx));
  998. }
  999. Expected<StringRef> XCOFFSymbolRef::getName() const {
  1000. // A storage class value with the high-order bit on indicates that the name is
  1001. // a symbolic debugger stabstring.
  1002. if (getStorageClass() & 0x80)
  1003. return StringRef("Unimplemented Debug Name");
  1004. if (Entry32) {
  1005. if (Entry32->NameInStrTbl.Magic != XCOFFSymbolRef::NAME_IN_STR_TBL_MAGIC)
  1006. return generateXCOFFFixedNameStringRef(Entry32->SymbolName);
  1007. return OwningObjectPtr->getStringTableEntry(Entry32->NameInStrTbl.Offset);
  1008. }
  1009. return OwningObjectPtr->getStringTableEntry(Entry64->Offset);
  1010. }
  1011. // Explictly instantiate template classes.
  1012. template struct XCOFFSectionHeader<XCOFFSectionHeader32>;
  1013. template struct XCOFFSectionHeader<XCOFFSectionHeader64>;
  1014. template struct XCOFFRelocation<llvm::support::ubig32_t>;
  1015. template struct XCOFFRelocation<llvm::support::ubig64_t>;
  1016. template llvm::Expected<llvm::ArrayRef<llvm::object::XCOFFRelocation64>>
  1017. llvm::object::XCOFFObjectFile::relocations<llvm::object::XCOFFSectionHeader64,
  1018. llvm::object::XCOFFRelocation64>(
  1019. llvm::object::XCOFFSectionHeader64 const &) const;
  1020. template llvm::Expected<llvm::ArrayRef<llvm::object::XCOFFRelocation32>>
  1021. llvm::object::XCOFFObjectFile::relocations<llvm::object::XCOFFSectionHeader32,
  1022. llvm::object::XCOFFRelocation32>(
  1023. llvm::object::XCOFFSectionHeader32 const &) const;
  1024. bool doesXCOFFTracebackTableBegin(ArrayRef<uint8_t> Bytes) {
  1025. if (Bytes.size() < 4)
  1026. return false;
  1027. return support::endian::read32be(Bytes.data()) == 0;
  1028. }
  1029. #define GETVALUEWITHMASK(X) (Data & (TracebackTable::X))
  1030. #define GETVALUEWITHMASKSHIFT(X, S) \
  1031. ((Data & (TracebackTable::X)) >> (TracebackTable::S))
  1032. Expected<TBVectorExt> TBVectorExt::create(StringRef TBvectorStrRef) {
  1033. Error Err = Error::success();
  1034. TBVectorExt TBTVecExt(TBvectorStrRef, Err);
  1035. if (Err)
  1036. return std::move(Err);
  1037. return TBTVecExt;
  1038. }
  1039. TBVectorExt::TBVectorExt(StringRef TBvectorStrRef, Error &Err) {
  1040. const uint8_t *Ptr = reinterpret_cast<const uint8_t *>(TBvectorStrRef.data());
  1041. Data = support::endian::read16be(Ptr);
  1042. uint32_t VecParmsTypeValue = support::endian::read32be(Ptr + 2);
  1043. unsigned ParmsNum =
  1044. GETVALUEWITHMASKSHIFT(NumberOfVectorParmsMask, NumberOfVectorParmsShift);
  1045. ErrorAsOutParameter EAO(&Err);
  1046. Expected<SmallString<32>> VecParmsTypeOrError =
  1047. parseVectorParmsType(VecParmsTypeValue, ParmsNum);
  1048. if (!VecParmsTypeOrError)
  1049. Err = VecParmsTypeOrError.takeError();
  1050. else
  1051. VecParmsInfo = VecParmsTypeOrError.get();
  1052. }
  1053. uint8_t TBVectorExt::getNumberOfVRSaved() const {
  1054. return GETVALUEWITHMASKSHIFT(NumberOfVRSavedMask, NumberOfVRSavedShift);
  1055. }
  1056. bool TBVectorExt::isVRSavedOnStack() const {
  1057. return GETVALUEWITHMASK(IsVRSavedOnStackMask);
  1058. }
  1059. bool TBVectorExt::hasVarArgs() const {
  1060. return GETVALUEWITHMASK(HasVarArgsMask);
  1061. }
  1062. uint8_t TBVectorExt::getNumberOfVectorParms() const {
  1063. return GETVALUEWITHMASKSHIFT(NumberOfVectorParmsMask,
  1064. NumberOfVectorParmsShift);
  1065. }
  1066. bool TBVectorExt::hasVMXInstruction() const {
  1067. return GETVALUEWITHMASK(HasVMXInstructionMask);
  1068. }
  1069. #undef GETVALUEWITHMASK
  1070. #undef GETVALUEWITHMASKSHIFT
  1071. Expected<XCOFFTracebackTable> XCOFFTracebackTable::create(const uint8_t *Ptr,
  1072. uint64_t &Size) {
  1073. Error Err = Error::success();
  1074. XCOFFTracebackTable TBT(Ptr, Size, Err);
  1075. if (Err)
  1076. return std::move(Err);
  1077. return TBT;
  1078. }
  1079. XCOFFTracebackTable::XCOFFTracebackTable(const uint8_t *Ptr, uint64_t &Size,
  1080. Error &Err)
  1081. : TBPtr(Ptr) {
  1082. ErrorAsOutParameter EAO(&Err);
  1083. DataExtractor DE(ArrayRef<uint8_t>(Ptr, Size), /*IsLittleEndian=*/false,
  1084. /*AddressSize=*/0);
  1085. DataExtractor::Cursor Cur(/*Offset=*/0);
  1086. // Skip 8 bytes of mandatory fields.
  1087. DE.getU64(Cur);
  1088. unsigned FixedParmsNum = getNumberOfFixedParms();
  1089. unsigned FloatingParmsNum = getNumberOfFPParms();
  1090. uint32_t ParamsTypeValue = 0;
  1091. // Begin to parse optional fields.
  1092. if (Cur && (FixedParmsNum + FloatingParmsNum) > 0)
  1093. ParamsTypeValue = DE.getU32(Cur);
  1094. if (Cur && hasTraceBackTableOffset())
  1095. TraceBackTableOffset = DE.getU32(Cur);
  1096. if (Cur && isInterruptHandler())
  1097. HandlerMask = DE.getU32(Cur);
  1098. if (Cur && hasControlledStorage()) {
  1099. NumOfCtlAnchors = DE.getU32(Cur);
  1100. if (Cur && NumOfCtlAnchors) {
  1101. SmallVector<uint32_t, 8> Disp;
  1102. Disp.reserve(NumOfCtlAnchors.getValue());
  1103. for (uint32_t I = 0; I < NumOfCtlAnchors && Cur; ++I)
  1104. Disp.push_back(DE.getU32(Cur));
  1105. if (Cur)
  1106. ControlledStorageInfoDisp = std::move(Disp);
  1107. }
  1108. }
  1109. if (Cur && isFuncNamePresent()) {
  1110. uint16_t FunctionNameLen = DE.getU16(Cur);
  1111. if (Cur)
  1112. FunctionName = DE.getBytes(Cur, FunctionNameLen);
  1113. }
  1114. if (Cur && isAllocaUsed())
  1115. AllocaRegister = DE.getU8(Cur);
  1116. unsigned VectorParmsNum = 0;
  1117. if (Cur && hasVectorInfo()) {
  1118. StringRef VectorExtRef = DE.getBytes(Cur, 6);
  1119. if (Cur) {
  1120. Expected<TBVectorExt> TBVecExtOrErr = TBVectorExt::create(VectorExtRef);
  1121. if (!TBVecExtOrErr) {
  1122. Err = TBVecExtOrErr.takeError();
  1123. return;
  1124. }
  1125. VecExt = TBVecExtOrErr.get();
  1126. VectorParmsNum = VecExt.getValue().getNumberOfVectorParms();
  1127. }
  1128. }
  1129. // As long as there is no fixed-point or floating-point parameter, this
  1130. // field remains not present even when hasVectorInfo gives true and
  1131. // indicates the presence of vector parameters.
  1132. if (Cur && (FixedParmsNum + FloatingParmsNum) > 0) {
  1133. Expected<SmallString<32>> ParmsTypeOrError =
  1134. hasVectorInfo()
  1135. ? parseParmsTypeWithVecInfo(ParamsTypeValue, FixedParmsNum,
  1136. FloatingParmsNum, VectorParmsNum)
  1137. : parseParmsType(ParamsTypeValue, FixedParmsNum, FloatingParmsNum);
  1138. if (!ParmsTypeOrError) {
  1139. Err = ParmsTypeOrError.takeError();
  1140. return;
  1141. }
  1142. ParmsType = ParmsTypeOrError.get();
  1143. }
  1144. if (Cur && hasExtensionTable())
  1145. ExtensionTable = DE.getU8(Cur);
  1146. if (!Cur)
  1147. Err = Cur.takeError();
  1148. Size = Cur.tell();
  1149. }
  1150. #define GETBITWITHMASK(P, X) \
  1151. (support::endian::read32be(TBPtr + (P)) & (TracebackTable::X))
  1152. #define GETBITWITHMASKSHIFT(P, X, S) \
  1153. ((support::endian::read32be(TBPtr + (P)) & (TracebackTable::X)) >> \
  1154. (TracebackTable::S))
  1155. uint8_t XCOFFTracebackTable::getVersion() const {
  1156. return GETBITWITHMASKSHIFT(0, VersionMask, VersionShift);
  1157. }
  1158. uint8_t XCOFFTracebackTable::getLanguageID() const {
  1159. return GETBITWITHMASKSHIFT(0, LanguageIdMask, LanguageIdShift);
  1160. }
  1161. bool XCOFFTracebackTable::isGlobalLinkage() const {
  1162. return GETBITWITHMASK(0, IsGlobaLinkageMask);
  1163. }
  1164. bool XCOFFTracebackTable::isOutOfLineEpilogOrPrologue() const {
  1165. return GETBITWITHMASK(0, IsOutOfLineEpilogOrPrologueMask);
  1166. }
  1167. bool XCOFFTracebackTable::hasTraceBackTableOffset() const {
  1168. return GETBITWITHMASK(0, HasTraceBackTableOffsetMask);
  1169. }
  1170. bool XCOFFTracebackTable::isInternalProcedure() const {
  1171. return GETBITWITHMASK(0, IsInternalProcedureMask);
  1172. }
  1173. bool XCOFFTracebackTable::hasControlledStorage() const {
  1174. return GETBITWITHMASK(0, HasControlledStorageMask);
  1175. }
  1176. bool XCOFFTracebackTable::isTOCless() const {
  1177. return GETBITWITHMASK(0, IsTOClessMask);
  1178. }
  1179. bool XCOFFTracebackTable::isFloatingPointPresent() const {
  1180. return GETBITWITHMASK(0, IsFloatingPointPresentMask);
  1181. }
  1182. bool XCOFFTracebackTable::isFloatingPointOperationLogOrAbortEnabled() const {
  1183. return GETBITWITHMASK(0, IsFloatingPointOperationLogOrAbortEnabledMask);
  1184. }
  1185. bool XCOFFTracebackTable::isInterruptHandler() const {
  1186. return GETBITWITHMASK(0, IsInterruptHandlerMask);
  1187. }
  1188. bool XCOFFTracebackTable::isFuncNamePresent() const {
  1189. return GETBITWITHMASK(0, IsFunctionNamePresentMask);
  1190. }
  1191. bool XCOFFTracebackTable::isAllocaUsed() const {
  1192. return GETBITWITHMASK(0, IsAllocaUsedMask);
  1193. }
  1194. uint8_t XCOFFTracebackTable::getOnConditionDirective() const {
  1195. return GETBITWITHMASKSHIFT(0, OnConditionDirectiveMask,
  1196. OnConditionDirectiveShift);
  1197. }
  1198. bool XCOFFTracebackTable::isCRSaved() const {
  1199. return GETBITWITHMASK(0, IsCRSavedMask);
  1200. }
  1201. bool XCOFFTracebackTable::isLRSaved() const {
  1202. return GETBITWITHMASK(0, IsLRSavedMask);
  1203. }
  1204. bool XCOFFTracebackTable::isBackChainStored() const {
  1205. return GETBITWITHMASK(4, IsBackChainStoredMask);
  1206. }
  1207. bool XCOFFTracebackTable::isFixup() const {
  1208. return GETBITWITHMASK(4, IsFixupMask);
  1209. }
  1210. uint8_t XCOFFTracebackTable::getNumOfFPRsSaved() const {
  1211. return GETBITWITHMASKSHIFT(4, FPRSavedMask, FPRSavedShift);
  1212. }
  1213. bool XCOFFTracebackTable::hasExtensionTable() const {
  1214. return GETBITWITHMASK(4, HasExtensionTableMask);
  1215. }
  1216. bool XCOFFTracebackTable::hasVectorInfo() const {
  1217. return GETBITWITHMASK(4, HasVectorInfoMask);
  1218. }
  1219. uint8_t XCOFFTracebackTable::getNumOfGPRsSaved() const {
  1220. return GETBITWITHMASKSHIFT(4, GPRSavedMask, GPRSavedShift);
  1221. }
  1222. uint8_t XCOFFTracebackTable::getNumberOfFixedParms() const {
  1223. return GETBITWITHMASKSHIFT(4, NumberOfFixedParmsMask,
  1224. NumberOfFixedParmsShift);
  1225. }
  1226. uint8_t XCOFFTracebackTable::getNumberOfFPParms() const {
  1227. return GETBITWITHMASKSHIFT(4, NumberOfFloatingPointParmsMask,
  1228. NumberOfFloatingPointParmsShift);
  1229. }
  1230. bool XCOFFTracebackTable::hasParmsOnStack() const {
  1231. return GETBITWITHMASK(4, HasParmsOnStackMask);
  1232. }
  1233. #undef GETBITWITHMASK
  1234. #undef GETBITWITHMASKSHIFT
  1235. } // namespace object
  1236. } // namespace llvm