Writer.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. //===- Writer.cpp ---------------------------------------------------------===//
  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. #include "Writer.h"
  9. #include "Object.h"
  10. #include "llvm/ADT/ArrayRef.h"
  11. #include "llvm/ADT/StringRef.h"
  12. #include "llvm/BinaryFormat/COFF.h"
  13. #include "llvm/Object/COFF.h"
  14. #include "llvm/Support/Errc.h"
  15. #include "llvm/Support/ErrorHandling.h"
  16. #include <cstddef>
  17. #include <cstdint>
  18. namespace llvm {
  19. namespace objcopy {
  20. namespace coff {
  21. using namespace object;
  22. using namespace COFF;
  23. Error COFFWriter::finalizeRelocTargets() {
  24. for (Section &Sec : Obj.getMutableSections()) {
  25. for (Relocation &R : Sec.Relocs) {
  26. const Symbol *Sym = Obj.findSymbol(R.Target);
  27. if (Sym == nullptr)
  28. return createStringError(object_error::invalid_symbol_index,
  29. "relocation target '%s' (%zu) not found",
  30. R.TargetName.str().c_str(), R.Target);
  31. R.Reloc.SymbolTableIndex = Sym->RawIndex;
  32. }
  33. }
  34. return Error::success();
  35. }
  36. Error COFFWriter::finalizeSymbolContents() {
  37. for (Symbol &Sym : Obj.getMutableSymbols()) {
  38. if (Sym.TargetSectionId <= 0) {
  39. // Undefined, or a special kind of symbol. These negative values
  40. // are stored in the SectionNumber field which is unsigned.
  41. Sym.Sym.SectionNumber = static_cast<uint32_t>(Sym.TargetSectionId);
  42. } else {
  43. const Section *Sec = Obj.findSection(Sym.TargetSectionId);
  44. if (Sec == nullptr)
  45. return createStringError(object_error::invalid_symbol_index,
  46. "symbol '%s' points to a removed section",
  47. Sym.Name.str().c_str());
  48. Sym.Sym.SectionNumber = Sec->Index;
  49. if (Sym.Sym.NumberOfAuxSymbols == 1 &&
  50. Sym.Sym.StorageClass == IMAGE_SYM_CLASS_STATIC) {
  51. coff_aux_section_definition *SD =
  52. reinterpret_cast<coff_aux_section_definition *>(
  53. Sym.AuxData[0].Opaque);
  54. uint32_t SDSectionNumber;
  55. if (Sym.AssociativeComdatTargetSectionId == 0) {
  56. // Not a comdat associative section; just set the Number field to
  57. // the number of the section itself.
  58. SDSectionNumber = Sec->Index;
  59. } else {
  60. Sec = Obj.findSection(Sym.AssociativeComdatTargetSectionId);
  61. if (Sec == nullptr)
  62. return createStringError(
  63. object_error::invalid_symbol_index,
  64. "symbol '%s' is associative to a removed section",
  65. Sym.Name.str().c_str());
  66. SDSectionNumber = Sec->Index;
  67. }
  68. // Update the section definition with the new section number.
  69. SD->NumberLowPart = static_cast<uint16_t>(SDSectionNumber);
  70. SD->NumberHighPart = static_cast<uint16_t>(SDSectionNumber >> 16);
  71. }
  72. }
  73. // Check that we actually have got AuxData to match the weak symbol target
  74. // we want to set. Only >= 1 would be required, but only == 1 makes sense.
  75. if (Sym.WeakTargetSymbolId && Sym.Sym.NumberOfAuxSymbols == 1) {
  76. coff_aux_weak_external *WE =
  77. reinterpret_cast<coff_aux_weak_external *>(Sym.AuxData[0].Opaque);
  78. const Symbol *Target = Obj.findSymbol(*Sym.WeakTargetSymbolId);
  79. if (Target == nullptr)
  80. return createStringError(object_error::invalid_symbol_index,
  81. "symbol '%s' is missing its weak target",
  82. Sym.Name.str().c_str());
  83. WE->TagIndex = Target->RawIndex;
  84. }
  85. }
  86. return Error::success();
  87. }
  88. void COFFWriter::layoutSections() {
  89. for (auto &S : Obj.getMutableSections()) {
  90. if (S.Header.SizeOfRawData > 0)
  91. S.Header.PointerToRawData = FileSize;
  92. FileSize += S.Header.SizeOfRawData; // For executables, this is already
  93. // aligned to FileAlignment.
  94. if (S.Relocs.size() >= 0xffff) {
  95. S.Header.Characteristics |= COFF::IMAGE_SCN_LNK_NRELOC_OVFL;
  96. S.Header.NumberOfRelocations = 0xffff;
  97. S.Header.PointerToRelocations = FileSize;
  98. FileSize += sizeof(coff_relocation);
  99. } else {
  100. S.Header.NumberOfRelocations = S.Relocs.size();
  101. S.Header.PointerToRelocations = S.Relocs.size() ? FileSize : 0;
  102. }
  103. FileSize += S.Relocs.size() * sizeof(coff_relocation);
  104. FileSize = alignTo(FileSize, FileAlignment);
  105. if (S.Header.Characteristics & IMAGE_SCN_CNT_INITIALIZED_DATA)
  106. SizeOfInitializedData += S.Header.SizeOfRawData;
  107. }
  108. }
  109. Expected<size_t> COFFWriter::finalizeStringTable() {
  110. for (const auto &S : Obj.getSections())
  111. if (S.Name.size() > COFF::NameSize)
  112. StrTabBuilder.add(S.Name);
  113. for (const auto &S : Obj.getSymbols())
  114. if (S.Name.size() > COFF::NameSize)
  115. StrTabBuilder.add(S.Name);
  116. StrTabBuilder.finalize();
  117. for (auto &S : Obj.getMutableSections()) {
  118. memset(S.Header.Name, 0, sizeof(S.Header.Name));
  119. if (S.Name.size() <= COFF::NameSize) {
  120. // Short names can go in the field directly.
  121. memcpy(S.Header.Name, S.Name.data(), S.Name.size());
  122. } else {
  123. // Offset of the section name in the string table.
  124. size_t Offset = StrTabBuilder.getOffset(S.Name);
  125. if (!COFF::encodeSectionName(S.Header.Name, Offset))
  126. return createStringError(object_error::invalid_section_index,
  127. "COFF string table is greater than 64GB, "
  128. "unable to encode section name offset");
  129. }
  130. }
  131. for (auto &S : Obj.getMutableSymbols()) {
  132. if (S.Name.size() > COFF::NameSize) {
  133. S.Sym.Name.Offset.Zeroes = 0;
  134. S.Sym.Name.Offset.Offset = StrTabBuilder.getOffset(S.Name);
  135. } else {
  136. strncpy(S.Sym.Name.ShortName, S.Name.data(), COFF::NameSize);
  137. }
  138. }
  139. return StrTabBuilder.getSize();
  140. }
  141. template <class SymbolTy>
  142. std::pair<size_t, size_t> COFFWriter::finalizeSymbolTable() {
  143. size_t RawSymIndex = 0;
  144. for (auto &S : Obj.getMutableSymbols()) {
  145. // Symbols normally have NumberOfAuxSymbols set correctly all the time.
  146. // For file symbols, we need to know the output file's symbol size to be
  147. // able to calculate the number of slots it occupies.
  148. if (!S.AuxFile.empty())
  149. S.Sym.NumberOfAuxSymbols =
  150. alignTo(S.AuxFile.size(), sizeof(SymbolTy)) / sizeof(SymbolTy);
  151. S.RawIndex = RawSymIndex;
  152. RawSymIndex += 1 + S.Sym.NumberOfAuxSymbols;
  153. }
  154. return std::make_pair(RawSymIndex * sizeof(SymbolTy), sizeof(SymbolTy));
  155. }
  156. Error COFFWriter::finalize(bool IsBigObj) {
  157. size_t SymTabSize, SymbolSize;
  158. std::tie(SymTabSize, SymbolSize) = IsBigObj
  159. ? finalizeSymbolTable<coff_symbol32>()
  160. : finalizeSymbolTable<coff_symbol16>();
  161. if (Error E = finalizeRelocTargets())
  162. return E;
  163. if (Error E = finalizeSymbolContents())
  164. return E;
  165. size_t SizeOfHeaders = 0;
  166. FileAlignment = 1;
  167. size_t PeHeaderSize = 0;
  168. if (Obj.IsPE) {
  169. Obj.DosHeader.AddressOfNewExeHeader =
  170. sizeof(Obj.DosHeader) + Obj.DosStub.size();
  171. SizeOfHeaders += Obj.DosHeader.AddressOfNewExeHeader + sizeof(PEMagic);
  172. FileAlignment = Obj.PeHeader.FileAlignment;
  173. Obj.PeHeader.NumberOfRvaAndSize = Obj.DataDirectories.size();
  174. PeHeaderSize = Obj.Is64 ? sizeof(pe32plus_header) : sizeof(pe32_header);
  175. SizeOfHeaders +=
  176. PeHeaderSize + sizeof(data_directory) * Obj.DataDirectories.size();
  177. }
  178. Obj.CoffFileHeader.NumberOfSections = Obj.getSections().size();
  179. SizeOfHeaders +=
  180. IsBigObj ? sizeof(coff_bigobj_file_header) : sizeof(coff_file_header);
  181. SizeOfHeaders += sizeof(coff_section) * Obj.getSections().size();
  182. SizeOfHeaders = alignTo(SizeOfHeaders, FileAlignment);
  183. Obj.CoffFileHeader.SizeOfOptionalHeader =
  184. PeHeaderSize + sizeof(data_directory) * Obj.DataDirectories.size();
  185. FileSize = SizeOfHeaders;
  186. SizeOfInitializedData = 0;
  187. layoutSections();
  188. if (Obj.IsPE) {
  189. Obj.PeHeader.SizeOfHeaders = SizeOfHeaders;
  190. Obj.PeHeader.SizeOfInitializedData = SizeOfInitializedData;
  191. if (!Obj.getSections().empty()) {
  192. const Section &S = Obj.getSections().back();
  193. Obj.PeHeader.SizeOfImage =
  194. alignTo(S.Header.VirtualAddress + S.Header.VirtualSize,
  195. Obj.PeHeader.SectionAlignment);
  196. }
  197. // If the PE header had a checksum, clear it, since it isn't valid
  198. // any longer. (We don't calculate a new one.)
  199. Obj.PeHeader.CheckSum = 0;
  200. }
  201. Expected<size_t> StrTabSizeOrErr = finalizeStringTable();
  202. if (!StrTabSizeOrErr)
  203. return StrTabSizeOrErr.takeError();
  204. size_t StrTabSize = *StrTabSizeOrErr;
  205. size_t PointerToSymbolTable = FileSize;
  206. // StrTabSize <= 4 is the size of an empty string table, only consisting
  207. // of the length field.
  208. if (SymTabSize == 0 && StrTabSize <= 4 && Obj.IsPE) {
  209. // For executables, don't point to the symbol table and skip writing
  210. // the length field, if both the symbol and string tables are empty.
  211. PointerToSymbolTable = 0;
  212. StrTabSize = 0;
  213. }
  214. size_t NumRawSymbols = SymTabSize / SymbolSize;
  215. Obj.CoffFileHeader.PointerToSymbolTable = PointerToSymbolTable;
  216. Obj.CoffFileHeader.NumberOfSymbols = NumRawSymbols;
  217. FileSize += SymTabSize + StrTabSize;
  218. FileSize = alignTo(FileSize, FileAlignment);
  219. return Error::success();
  220. }
  221. void COFFWriter::writeHeaders(bool IsBigObj) {
  222. uint8_t *Ptr = reinterpret_cast<uint8_t *>(Buf->getBufferStart());
  223. if (Obj.IsPE) {
  224. memcpy(Ptr, &Obj.DosHeader, sizeof(Obj.DosHeader));
  225. Ptr += sizeof(Obj.DosHeader);
  226. memcpy(Ptr, Obj.DosStub.data(), Obj.DosStub.size());
  227. Ptr += Obj.DosStub.size();
  228. memcpy(Ptr, PEMagic, sizeof(PEMagic));
  229. Ptr += sizeof(PEMagic);
  230. }
  231. if (!IsBigObj) {
  232. memcpy(Ptr, &Obj.CoffFileHeader, sizeof(Obj.CoffFileHeader));
  233. Ptr += sizeof(Obj.CoffFileHeader);
  234. } else {
  235. // Generate a coff_bigobj_file_header, filling it in with the values
  236. // from Obj.CoffFileHeader. All extra fields that don't exist in
  237. // coff_file_header can be set to hardcoded values.
  238. coff_bigobj_file_header BigObjHeader;
  239. BigObjHeader.Sig1 = IMAGE_FILE_MACHINE_UNKNOWN;
  240. BigObjHeader.Sig2 = 0xffff;
  241. BigObjHeader.Version = BigObjHeader::MinBigObjectVersion;
  242. BigObjHeader.Machine = Obj.CoffFileHeader.Machine;
  243. BigObjHeader.TimeDateStamp = Obj.CoffFileHeader.TimeDateStamp;
  244. memcpy(BigObjHeader.UUID, BigObjMagic, sizeof(BigObjMagic));
  245. BigObjHeader.unused1 = 0;
  246. BigObjHeader.unused2 = 0;
  247. BigObjHeader.unused3 = 0;
  248. BigObjHeader.unused4 = 0;
  249. // The value in Obj.CoffFileHeader.NumberOfSections is truncated, thus
  250. // get the original one instead.
  251. BigObjHeader.NumberOfSections = Obj.getSections().size();
  252. BigObjHeader.PointerToSymbolTable = Obj.CoffFileHeader.PointerToSymbolTable;
  253. BigObjHeader.NumberOfSymbols = Obj.CoffFileHeader.NumberOfSymbols;
  254. memcpy(Ptr, &BigObjHeader, sizeof(BigObjHeader));
  255. Ptr += sizeof(BigObjHeader);
  256. }
  257. if (Obj.IsPE) {
  258. if (Obj.Is64) {
  259. memcpy(Ptr, &Obj.PeHeader, sizeof(Obj.PeHeader));
  260. Ptr += sizeof(Obj.PeHeader);
  261. } else {
  262. pe32_header PeHeader;
  263. copyPeHeader(PeHeader, Obj.PeHeader);
  264. // The pe32plus_header (stored in Object) lacks the BaseOfData field.
  265. PeHeader.BaseOfData = Obj.BaseOfData;
  266. memcpy(Ptr, &PeHeader, sizeof(PeHeader));
  267. Ptr += sizeof(PeHeader);
  268. }
  269. for (const auto &DD : Obj.DataDirectories) {
  270. memcpy(Ptr, &DD, sizeof(DD));
  271. Ptr += sizeof(DD);
  272. }
  273. }
  274. for (const auto &S : Obj.getSections()) {
  275. memcpy(Ptr, &S.Header, sizeof(S.Header));
  276. Ptr += sizeof(S.Header);
  277. }
  278. }
  279. void COFFWriter::writeSections() {
  280. for (const auto &S : Obj.getSections()) {
  281. uint8_t *Ptr = reinterpret_cast<uint8_t *>(Buf->getBufferStart()) +
  282. S.Header.PointerToRawData;
  283. ArrayRef<uint8_t> Contents = S.getContents();
  284. std::copy(Contents.begin(), Contents.end(), Ptr);
  285. // For executable sections, pad the remainder of the raw data size with
  286. // 0xcc, which is int3 on x86.
  287. if ((S.Header.Characteristics & IMAGE_SCN_CNT_CODE) &&
  288. S.Header.SizeOfRawData > Contents.size())
  289. memset(Ptr + Contents.size(), 0xcc,
  290. S.Header.SizeOfRawData - Contents.size());
  291. Ptr += S.Header.SizeOfRawData;
  292. if (S.Relocs.size() >= 0xffff) {
  293. object::coff_relocation R;
  294. R.VirtualAddress = S.Relocs.size() + 1;
  295. R.SymbolTableIndex = 0;
  296. R.Type = 0;
  297. memcpy(Ptr, &R, sizeof(R));
  298. Ptr += sizeof(R);
  299. }
  300. for (const auto &R : S.Relocs) {
  301. memcpy(Ptr, &R.Reloc, sizeof(R.Reloc));
  302. Ptr += sizeof(R.Reloc);
  303. }
  304. }
  305. }
  306. template <class SymbolTy> void COFFWriter::writeSymbolStringTables() {
  307. uint8_t *Ptr = reinterpret_cast<uint8_t *>(Buf->getBufferStart()) +
  308. Obj.CoffFileHeader.PointerToSymbolTable;
  309. for (const auto &S : Obj.getSymbols()) {
  310. // Convert symbols back to the right size, from coff_symbol32.
  311. copySymbol<SymbolTy, coff_symbol32>(*reinterpret_cast<SymbolTy *>(Ptr),
  312. S.Sym);
  313. Ptr += sizeof(SymbolTy);
  314. if (!S.AuxFile.empty()) {
  315. // For file symbols, just write the string into the aux symbol slots,
  316. // assuming that the unwritten parts are initialized to zero in the memory
  317. // mapped file.
  318. std::copy(S.AuxFile.begin(), S.AuxFile.end(), Ptr);
  319. Ptr += S.Sym.NumberOfAuxSymbols * sizeof(SymbolTy);
  320. } else {
  321. // For other auxillary symbols, write their opaque payload into one symbol
  322. // table slot each. For big object files, the symbols are larger than the
  323. // opaque auxillary symbol struct and we leave padding at the end of each
  324. // entry.
  325. for (const AuxSymbol &AuxSym : S.AuxData) {
  326. ArrayRef<uint8_t> Ref = AuxSym.getRef();
  327. std::copy(Ref.begin(), Ref.end(), Ptr);
  328. Ptr += sizeof(SymbolTy);
  329. }
  330. }
  331. }
  332. if (StrTabBuilder.getSize() > 4 || !Obj.IsPE) {
  333. // Always write a string table in object files, even an empty one.
  334. StrTabBuilder.write(Ptr);
  335. Ptr += StrTabBuilder.getSize();
  336. }
  337. }
  338. Error COFFWriter::write(bool IsBigObj) {
  339. if (Error E = finalize(IsBigObj))
  340. return E;
  341. Buf = WritableMemoryBuffer::getNewMemBuffer(FileSize);
  342. if (!Buf)
  343. return createStringError(llvm::errc::not_enough_memory,
  344. "failed to allocate memory buffer of " +
  345. Twine::utohexstr(FileSize) + " bytes.");
  346. writeHeaders(IsBigObj);
  347. writeSections();
  348. if (IsBigObj)
  349. writeSymbolStringTables<coff_symbol32>();
  350. else
  351. writeSymbolStringTables<coff_symbol16>();
  352. if (Obj.IsPE)
  353. if (Error E = patchDebugDirectory())
  354. return E;
  355. // TODO: Implement direct writing to the output stream (without intermediate
  356. // memory buffer Buf).
  357. Out.write(Buf->getBufferStart(), Buf->getBufferSize());
  358. return Error::success();
  359. }
  360. Expected<uint32_t> COFFWriter::virtualAddressToFileAddress(uint32_t RVA) {
  361. for (const auto &S : Obj.getSections()) {
  362. if (RVA >= S.Header.VirtualAddress &&
  363. RVA < S.Header.VirtualAddress + S.Header.SizeOfRawData)
  364. return S.Header.PointerToRawData + RVA - S.Header.VirtualAddress;
  365. }
  366. return createStringError(object_error::parse_failed,
  367. "debug directory payload not found");
  368. }
  369. // Locate which sections contain the debug directories, iterate over all
  370. // the debug_directory structs in there, and set the PointerToRawData field
  371. // in all of them, according to their new physical location in the file.
  372. Error COFFWriter::patchDebugDirectory() {
  373. if (Obj.DataDirectories.size() <= DEBUG_DIRECTORY)
  374. return Error::success();
  375. const data_directory *Dir = &Obj.DataDirectories[DEBUG_DIRECTORY];
  376. if (Dir->Size <= 0)
  377. return Error::success();
  378. for (const auto &S : Obj.getSections()) {
  379. if (Dir->RelativeVirtualAddress >= S.Header.VirtualAddress &&
  380. Dir->RelativeVirtualAddress <
  381. S.Header.VirtualAddress + S.Header.SizeOfRawData) {
  382. if (Dir->RelativeVirtualAddress + Dir->Size >
  383. S.Header.VirtualAddress + S.Header.SizeOfRawData)
  384. return createStringError(object_error::parse_failed,
  385. "debug directory extends past end of section");
  386. size_t Offset = Dir->RelativeVirtualAddress - S.Header.VirtualAddress;
  387. uint8_t *Ptr = reinterpret_cast<uint8_t *>(Buf->getBufferStart()) +
  388. S.Header.PointerToRawData + Offset;
  389. uint8_t *End = Ptr + Dir->Size;
  390. while (Ptr < End) {
  391. debug_directory *Debug = reinterpret_cast<debug_directory *>(Ptr);
  392. if (Debug->PointerToRawData) {
  393. if (Expected<uint32_t> FilePosOrErr =
  394. virtualAddressToFileAddress(Debug->AddressOfRawData))
  395. Debug->PointerToRawData = *FilePosOrErr;
  396. else
  397. return FilePosOrErr.takeError();
  398. }
  399. Ptr += sizeof(debug_directory);
  400. Offset += sizeof(debug_directory);
  401. }
  402. // Debug directory found and patched, all done.
  403. return Error::success();
  404. }
  405. }
  406. return createStringError(object_error::parse_failed,
  407. "debug directory not found");
  408. }
  409. Error COFFWriter::write() {
  410. bool IsBigObj = Obj.getSections().size() > MaxNumberOfSections16;
  411. if (IsBigObj && Obj.IsPE)
  412. return createStringError(object_error::parse_failed,
  413. "too many sections for executable");
  414. return write(IsBigObj);
  415. }
  416. } // end namespace coff
  417. } // end namespace objcopy
  418. } // end namespace llvm