1 //===-- WindowsResource.cpp -------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the .res file class.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Object/WindowsResource.h"
15 #include "llvm/Object/COFF.h"
16 #include "llvm/Support/FileOutputBuffer.h"
17 #include "llvm/Support/FormatVariadic.h"
18 #include "llvm/Support/MathExtras.h"
21 #include <system_error>
24 using namespace object;
29 #define RETURN_IF_ERROR(X) \
33 const uint32_t MIN_HEADER_SIZE = 7 * sizeof(uint32_t) + 2 * sizeof(uint16_t);
35 // COFF files seem to be inconsistent with alignment between sections, just use
36 // 8-byte because it makes everyone happy.
37 const uint32_t SECTION_ALIGNMENT = sizeof(uint64_t);
39 uint32_t WindowsResourceParser::TreeNode::StringCount = 0;
40 uint32_t WindowsResourceParser::TreeNode::DataCount = 0;
42 WindowsResource::WindowsResource(MemoryBufferRef Source)
43 : Binary(Binary::ID_WinRes, Source) {
44 size_t LeadingSize = WIN_RES_MAGIC_SIZE + WIN_RES_NULL_ENTRY_SIZE;
45 BBS = BinaryByteStream(Data.getBuffer().drop_front(LeadingSize),
49 Expected<std::unique_ptr<WindowsResource>>
50 WindowsResource::createWindowsResource(MemoryBufferRef Source) {
51 if (Source.getBufferSize() < WIN_RES_MAGIC_SIZE + WIN_RES_NULL_ENTRY_SIZE)
52 return make_error<GenericBinaryError>(
53 "File too small to be a resource file",
54 object_error::invalid_file_type);
55 std::unique_ptr<WindowsResource> Ret(new WindowsResource(Source));
56 return std::move(Ret);
59 Expected<ResourceEntryRef> WindowsResource::getHeadEntry() {
60 if (BBS.getLength() < sizeof(WinResHeaderPrefix) + sizeof(WinResHeaderSuffix))
61 return make_error<EmptyResError>(".res contains no entries",
62 object_error::unexpected_eof);
63 return ResourceEntryRef::create(BinaryStreamRef(BBS), this);
66 ResourceEntryRef::ResourceEntryRef(BinaryStreamRef Ref,
67 const WindowsResource *Owner)
70 Expected<ResourceEntryRef>
71 ResourceEntryRef::create(BinaryStreamRef BSR, const WindowsResource *Owner) {
72 auto Ref = ResourceEntryRef(BSR, Owner);
73 if (auto E = Ref.loadNext())
78 Error ResourceEntryRef::moveNext(bool &End) {
79 // Reached end of all the entries.
80 if (Reader.bytesRemaining() == 0) {
82 return Error::success();
84 RETURN_IF_ERROR(loadNext());
86 return Error::success();
89 static Error readStringOrId(BinaryStreamReader &Reader, uint16_t &ID,
90 ArrayRef<UTF16> &Str, bool &IsString) {
92 RETURN_IF_ERROR(Reader.readInteger(IDFlag));
93 IsString = IDFlag != 0xffff;
98 sizeof(uint16_t)); // Re-read the bytes which we used to check the flag.
99 RETURN_IF_ERROR(Reader.readWideString(Str));
101 RETURN_IF_ERROR(Reader.readInteger(ID));
103 return Error::success();
106 Error ResourceEntryRef::loadNext() {
107 const WinResHeaderPrefix *Prefix;
108 RETURN_IF_ERROR(Reader.readObject(Prefix));
110 if (Prefix->HeaderSize < MIN_HEADER_SIZE)
111 return make_error<GenericBinaryError>("Header size is too small.",
112 object_error::parse_failed);
114 RETURN_IF_ERROR(readStringOrId(Reader, TypeID, Type, IsStringType));
116 RETURN_IF_ERROR(readStringOrId(Reader, NameID, Name, IsStringName));
118 RETURN_IF_ERROR(Reader.padToAlignment(WIN_RES_HEADER_ALIGNMENT));
120 RETURN_IF_ERROR(Reader.readObject(Suffix));
122 RETURN_IF_ERROR(Reader.readArray(Data, Prefix->DataSize));
124 RETURN_IF_ERROR(Reader.padToAlignment(WIN_RES_DATA_ALIGNMENT));
126 return Error::success();
129 WindowsResourceParser::WindowsResourceParser() : Root(false) {}
131 Error WindowsResourceParser::parse(WindowsResource *WR) {
132 auto EntryOrErr = WR->getHeadEntry();
134 auto E = EntryOrErr.takeError();
135 if (E.isA<EmptyResError>()) {
136 // Check if the .res file contains no entries. In this case we don't have
137 // to throw an error but can rather just return without parsing anything.
138 // This applies for files which have a valid PE header magic and the
139 // mandatory empty null resource entry. Files which do not fit this
140 // criteria would have already been filtered out by
141 // WindowsResource::createWindowsResource().
142 consumeError(std::move(E));
143 return Error::success();
148 ResourceEntryRef Entry = EntryOrErr.get();
151 Data.push_back(Entry.getData());
153 bool IsNewTypeString = false;
154 bool IsNewNameString = false;
156 Root.addEntry(Entry, IsNewTypeString, IsNewNameString);
159 StringTable.push_back(Entry.getTypeString());
162 StringTable.push_back(Entry.getNameString());
164 RETURN_IF_ERROR(Entry.moveNext(End));
167 return Error::success();
170 void WindowsResourceParser::printTree(raw_ostream &OS) const {
171 ScopedPrinter Writer(OS);
172 Root.print(Writer, "Resource Tree");
175 void WindowsResourceParser::TreeNode::addEntry(const ResourceEntryRef &Entry,
176 bool &IsNewTypeString,
177 bool &IsNewNameString) {
178 TreeNode &TypeNode = addTypeNode(Entry, IsNewTypeString);
179 TreeNode &NameNode = TypeNode.addNameNode(Entry, IsNewNameString);
180 NameNode.addLanguageNode(Entry);
183 WindowsResourceParser::TreeNode::TreeNode(bool IsStringNode) {
185 StringIndex = StringCount++;
188 WindowsResourceParser::TreeNode::TreeNode(uint16_t MajorVersion,
189 uint16_t MinorVersion,
190 uint32_t Characteristics)
191 : IsDataNode(true), MajorVersion(MajorVersion), MinorVersion(MinorVersion),
192 Characteristics(Characteristics) {
193 DataIndex = DataCount++;
196 std::unique_ptr<WindowsResourceParser::TreeNode>
197 WindowsResourceParser::TreeNode::createStringNode() {
198 return std::unique_ptr<TreeNode>(new TreeNode(true));
201 std::unique_ptr<WindowsResourceParser::TreeNode>
202 WindowsResourceParser::TreeNode::createIDNode() {
203 return std::unique_ptr<TreeNode>(new TreeNode(false));
206 std::unique_ptr<WindowsResourceParser::TreeNode>
207 WindowsResourceParser::TreeNode::createDataNode(uint16_t MajorVersion,
208 uint16_t MinorVersion,
209 uint32_t Characteristics) {
210 return std::unique_ptr<TreeNode>(
211 new TreeNode(MajorVersion, MinorVersion, Characteristics));
214 WindowsResourceParser::TreeNode &
215 WindowsResourceParser::TreeNode::addTypeNode(const ResourceEntryRef &Entry,
216 bool &IsNewTypeString) {
217 if (Entry.checkTypeString())
218 return addChild(Entry.getTypeString(), IsNewTypeString);
220 return addChild(Entry.getTypeID());
223 WindowsResourceParser::TreeNode &
224 WindowsResourceParser::TreeNode::addNameNode(const ResourceEntryRef &Entry,
225 bool &IsNewNameString) {
226 if (Entry.checkNameString())
227 return addChild(Entry.getNameString(), IsNewNameString);
229 return addChild(Entry.getNameID());
232 WindowsResourceParser::TreeNode &
233 WindowsResourceParser::TreeNode::addLanguageNode(
234 const ResourceEntryRef &Entry) {
235 return addChild(Entry.getLanguage(), true, Entry.getMajorVersion(),
236 Entry.getMinorVersion(), Entry.getCharacteristics());
239 WindowsResourceParser::TreeNode &WindowsResourceParser::TreeNode::addChild(
240 uint32_t ID, bool IsDataNode, uint16_t MajorVersion, uint16_t MinorVersion,
241 uint32_t Characteristics) {
242 auto Child = IDChildren.find(ID);
243 if (Child == IDChildren.end()) {
245 IsDataNode ? createDataNode(MajorVersion, MinorVersion, Characteristics)
247 WindowsResourceParser::TreeNode &Node = *NewChild;
248 IDChildren.emplace(ID, std::move(NewChild));
251 return *(Child->second);
254 WindowsResourceParser::TreeNode &
255 WindowsResourceParser::TreeNode::addChild(ArrayRef<UTF16> NameRef,
257 std::string NameString;
258 ArrayRef<UTF16> CorrectedName;
259 std::vector<UTF16> EndianCorrectedName;
260 if (sys::IsBigEndianHost) {
261 EndianCorrectedName.resize(NameRef.size() + 1);
262 llvm::copy(NameRef, EndianCorrectedName.begin() + 1);
263 EndianCorrectedName[0] = UNI_UTF16_BYTE_ORDER_MARK_SWAPPED;
264 CorrectedName = makeArrayRef(EndianCorrectedName);
266 CorrectedName = NameRef;
267 convertUTF16ToUTF8String(CorrectedName, NameString);
269 auto Child = StringChildren.find(NameString);
270 if (Child == StringChildren.end()) {
271 auto NewChild = createStringNode();
273 WindowsResourceParser::TreeNode &Node = *NewChild;
274 StringChildren.emplace(NameString, std::move(NewChild));
277 return *(Child->second);
280 void WindowsResourceParser::TreeNode::print(ScopedPrinter &Writer,
281 StringRef Name) const {
282 ListScope NodeScope(Writer, Name);
283 for (auto const &Child : StringChildren) {
284 Child.second->print(Writer, Child.first);
286 for (auto const &Child : IDChildren) {
287 Child.second->print(Writer, to_string(Child.first));
291 // This function returns the size of the entire resource tree, including
292 // directory tables, directory entries, and data entries. It does not include
293 // the directory strings or the relocations of the .rsrc section.
294 uint32_t WindowsResourceParser::TreeNode::getTreeSize() const {
295 uint32_t Size = (IDChildren.size() + StringChildren.size()) *
296 sizeof(coff_resource_dir_entry);
298 // Reached a node pointing to a data entry.
300 Size += sizeof(coff_resource_data_entry);
304 // If the node does not point to data, it must have a directory table pointing
306 Size += sizeof(coff_resource_dir_table);
308 for (auto const &Child : StringChildren) {
309 Size += Child.second->getTreeSize();
311 for (auto const &Child : IDChildren) {
312 Size += Child.second->getTreeSize();
317 class WindowsResourceCOFFWriter {
319 WindowsResourceCOFFWriter(COFF::MachineTypes MachineType,
320 const WindowsResourceParser &Parser, Error &E);
321 std::unique_ptr<MemoryBuffer> write();
324 void performFileLayout();
325 void performSectionOneLayout();
326 void performSectionTwoLayout();
327 void writeCOFFHeader();
328 void writeFirstSectionHeader();
329 void writeSecondSectionHeader();
330 void writeFirstSection();
331 void writeSecondSection();
332 void writeSymbolTable();
333 void writeStringTable();
334 void writeDirectoryTree();
335 void writeDirectoryStringTable();
336 void writeFirstSectionRelocations();
337 std::unique_ptr<WritableMemoryBuffer> OutputBuffer;
339 uint64_t CurrentOffset = 0;
340 COFF::MachineTypes MachineType;
341 const WindowsResourceParser::TreeNode &Resources;
342 const ArrayRef<std::vector<uint8_t>> Data;
344 uint32_t SymbolTableOffset;
345 uint32_t SectionOneSize;
346 uint32_t SectionOneOffset;
347 uint32_t SectionOneRelocations;
348 uint32_t SectionTwoSize;
349 uint32_t SectionTwoOffset;
350 const ArrayRef<std::vector<UTF16>> StringTable;
351 std::vector<uint32_t> StringTableOffsets;
352 std::vector<uint32_t> DataOffsets;
353 std::vector<uint32_t> RelocationAddresses;
356 WindowsResourceCOFFWriter::WindowsResourceCOFFWriter(
357 COFF::MachineTypes MachineType, const WindowsResourceParser &Parser,
359 : MachineType(MachineType), Resources(Parser.getTree()),
360 Data(Parser.getData()), StringTable(Parser.getStringTable()) {
363 OutputBuffer = WritableMemoryBuffer::getNewMemBuffer(FileSize);
366 void WindowsResourceCOFFWriter::performFileLayout() {
367 // Add size of COFF header.
368 FileSize = COFF::Header16Size;
370 // one .rsrc section header for directory tree, another for resource data.
371 FileSize += 2 * COFF::SectionSize;
373 performSectionOneLayout();
374 performSectionTwoLayout();
376 // We have reached the address of the symbol table.
377 SymbolTableOffset = FileSize;
379 FileSize += COFF::Symbol16Size; // size of the @feat.00 symbol.
380 FileSize += 4 * COFF::Symbol16Size; // symbol + aux for each section.
381 FileSize += Data.size() * COFF::Symbol16Size; // 1 symbol per resource.
382 FileSize += 4; // four null bytes for the string table.
385 void WindowsResourceCOFFWriter::performSectionOneLayout() {
386 SectionOneOffset = FileSize;
388 SectionOneSize = Resources.getTreeSize();
389 uint32_t CurrentStringOffset = SectionOneSize;
390 uint32_t TotalStringTableSize = 0;
391 for (auto const &String : StringTable) {
392 StringTableOffsets.push_back(CurrentStringOffset);
393 uint32_t StringSize = String.size() * sizeof(UTF16) + sizeof(uint16_t);
394 CurrentStringOffset += StringSize;
395 TotalStringTableSize += StringSize;
397 SectionOneSize += alignTo(TotalStringTableSize, sizeof(uint32_t));
399 // account for the relocations of section one.
400 SectionOneRelocations = FileSize + SectionOneSize;
401 FileSize += SectionOneSize;
403 Data.size() * COFF::RelocationSize; // one relocation for each resource.
404 FileSize = alignTo(FileSize, SECTION_ALIGNMENT);
407 void WindowsResourceCOFFWriter::performSectionTwoLayout() {
408 // add size of .rsrc$2 section, which contains all resource data on 8-byte
410 SectionTwoOffset = FileSize;
412 for (auto const &Entry : Data) {
413 DataOffsets.push_back(SectionTwoSize);
414 SectionTwoSize += alignTo(Entry.size(), sizeof(uint64_t));
416 FileSize += SectionTwoSize;
417 FileSize = alignTo(FileSize, SECTION_ALIGNMENT);
420 static std::time_t getTime() {
421 std::time_t Now = time(nullptr);
422 if (Now < 0 || !isUInt<32>(Now))
427 std::unique_ptr<MemoryBuffer> WindowsResourceCOFFWriter::write() {
428 BufferStart = OutputBuffer->getBufferStart();
431 writeFirstSectionHeader();
432 writeSecondSectionHeader();
434 writeSecondSection();
438 return std::move(OutputBuffer);
441 void WindowsResourceCOFFWriter::writeCOFFHeader() {
442 // Write the COFF header.
443 auto *Header = reinterpret_cast<coff_file_header *>(BufferStart);
444 Header->Machine = MachineType;
445 Header->NumberOfSections = 2;
446 Header->TimeDateStamp = getTime();
447 Header->PointerToSymbolTable = SymbolTableOffset;
448 // One symbol for every resource plus 2 for each section and @feat.00
449 Header->NumberOfSymbols = Data.size() + 5;
450 Header->SizeOfOptionalHeader = 0;
451 Header->Characteristics = COFF::IMAGE_FILE_32BIT_MACHINE;
454 void WindowsResourceCOFFWriter::writeFirstSectionHeader() {
455 // Write the first section header.
456 CurrentOffset += sizeof(coff_file_header);
457 auto *SectionOneHeader =
458 reinterpret_cast<coff_section *>(BufferStart + CurrentOffset);
459 strncpy(SectionOneHeader->Name, ".rsrc$01", (size_t)COFF::NameSize);
460 SectionOneHeader->VirtualSize = 0;
461 SectionOneHeader->VirtualAddress = 0;
462 SectionOneHeader->SizeOfRawData = SectionOneSize;
463 SectionOneHeader->PointerToRawData = SectionOneOffset;
464 SectionOneHeader->PointerToRelocations = SectionOneRelocations;
465 SectionOneHeader->PointerToLinenumbers = 0;
466 SectionOneHeader->NumberOfRelocations = Data.size();
467 SectionOneHeader->NumberOfLinenumbers = 0;
468 SectionOneHeader->Characteristics += COFF::IMAGE_SCN_CNT_INITIALIZED_DATA;
469 SectionOneHeader->Characteristics += COFF::IMAGE_SCN_MEM_READ;
472 void WindowsResourceCOFFWriter::writeSecondSectionHeader() {
473 // Write the second section header.
474 CurrentOffset += sizeof(coff_section);
475 auto *SectionTwoHeader =
476 reinterpret_cast<coff_section *>(BufferStart + CurrentOffset);
477 strncpy(SectionTwoHeader->Name, ".rsrc$02", (size_t)COFF::NameSize);
478 SectionTwoHeader->VirtualSize = 0;
479 SectionTwoHeader->VirtualAddress = 0;
480 SectionTwoHeader->SizeOfRawData = SectionTwoSize;
481 SectionTwoHeader->PointerToRawData = SectionTwoOffset;
482 SectionTwoHeader->PointerToRelocations = 0;
483 SectionTwoHeader->PointerToLinenumbers = 0;
484 SectionTwoHeader->NumberOfRelocations = 0;
485 SectionTwoHeader->NumberOfLinenumbers = 0;
486 SectionTwoHeader->Characteristics = COFF::IMAGE_SCN_CNT_INITIALIZED_DATA;
487 SectionTwoHeader->Characteristics += COFF::IMAGE_SCN_MEM_READ;
490 void WindowsResourceCOFFWriter::writeFirstSection() {
491 // Write section one.
492 CurrentOffset += sizeof(coff_section);
494 writeDirectoryTree();
495 writeDirectoryStringTable();
496 writeFirstSectionRelocations();
498 CurrentOffset = alignTo(CurrentOffset, SECTION_ALIGNMENT);
501 void WindowsResourceCOFFWriter::writeSecondSection() {
502 // Now write the .rsrc$02 section.
503 for (auto const &RawDataEntry : Data) {
504 llvm::copy(RawDataEntry, BufferStart + CurrentOffset);
505 CurrentOffset += alignTo(RawDataEntry.size(), sizeof(uint64_t));
508 CurrentOffset = alignTo(CurrentOffset, SECTION_ALIGNMENT);
511 void WindowsResourceCOFFWriter::writeSymbolTable() {
512 // Now write the symbol table.
513 // First, the feat symbol.
514 auto *Symbol = reinterpret_cast<coff_symbol16 *>(BufferStart + CurrentOffset);
515 strncpy(Symbol->Name.ShortName, "@feat.00", (size_t)COFF::NameSize);
516 Symbol->Value = 0x11;
517 Symbol->SectionNumber = 0xffff;
518 Symbol->Type = COFF::IMAGE_SYM_DTYPE_NULL;
519 Symbol->StorageClass = COFF::IMAGE_SYM_CLASS_STATIC;
520 Symbol->NumberOfAuxSymbols = 0;
521 CurrentOffset += sizeof(coff_symbol16);
523 // Now write the .rsrc1 symbol + aux.
524 Symbol = reinterpret_cast<coff_symbol16 *>(BufferStart + CurrentOffset);
525 strncpy(Symbol->Name.ShortName, ".rsrc$01", (size_t)COFF::NameSize);
527 Symbol->SectionNumber = 1;
528 Symbol->Type = COFF::IMAGE_SYM_DTYPE_NULL;
529 Symbol->StorageClass = COFF::IMAGE_SYM_CLASS_STATIC;
530 Symbol->NumberOfAuxSymbols = 1;
531 CurrentOffset += sizeof(coff_symbol16);
532 auto *Aux = reinterpret_cast<coff_aux_section_definition *>(BufferStart +
534 Aux->Length = SectionOneSize;
535 Aux->NumberOfRelocations = Data.size();
536 Aux->NumberOfLinenumbers = 0;
538 Aux->NumberLowPart = 0;
540 CurrentOffset += sizeof(coff_aux_section_definition);
542 // Now write the .rsrc2 symbol + aux.
543 Symbol = reinterpret_cast<coff_symbol16 *>(BufferStart + CurrentOffset);
544 strncpy(Symbol->Name.ShortName, ".rsrc$02", (size_t)COFF::NameSize);
546 Symbol->SectionNumber = 2;
547 Symbol->Type = COFF::IMAGE_SYM_DTYPE_NULL;
548 Symbol->StorageClass = COFF::IMAGE_SYM_CLASS_STATIC;
549 Symbol->NumberOfAuxSymbols = 1;
550 CurrentOffset += sizeof(coff_symbol16);
551 Aux = reinterpret_cast<coff_aux_section_definition *>(BufferStart +
553 Aux->Length = SectionTwoSize;
554 Aux->NumberOfRelocations = 0;
555 Aux->NumberOfLinenumbers = 0;
557 Aux->NumberLowPart = 0;
559 CurrentOffset += sizeof(coff_aux_section_definition);
561 // Now write a symbol for each relocation.
562 for (unsigned i = 0; i < Data.size(); i++) {
563 auto RelocationName = formatv("$R{0:X-6}", i & 0xffffff).sstr<COFF::NameSize>();
564 Symbol = reinterpret_cast<coff_symbol16 *>(BufferStart + CurrentOffset);
565 memcpy(Symbol->Name.ShortName, RelocationName.data(), (size_t) COFF::NameSize);
566 Symbol->Value = DataOffsets[i];
567 Symbol->SectionNumber = 2;
568 Symbol->Type = COFF::IMAGE_SYM_DTYPE_NULL;
569 Symbol->StorageClass = COFF::IMAGE_SYM_CLASS_STATIC;
570 Symbol->NumberOfAuxSymbols = 0;
571 CurrentOffset += sizeof(coff_symbol16);
575 void WindowsResourceCOFFWriter::writeStringTable() {
576 // Just 4 null bytes for the string table.
577 auto COFFStringTable = reinterpret_cast<void *>(BufferStart + CurrentOffset);
578 memset(COFFStringTable, 0, 4);
581 void WindowsResourceCOFFWriter::writeDirectoryTree() {
582 // Traverse parsed resource tree breadth-first and write the corresponding
584 std::queue<const WindowsResourceParser::TreeNode *> Queue;
585 Queue.push(&Resources);
586 uint32_t NextLevelOffset =
587 sizeof(coff_resource_dir_table) + (Resources.getStringChildren().size() +
588 Resources.getIDChildren().size()) *
589 sizeof(coff_resource_dir_entry);
590 std::vector<const WindowsResourceParser::TreeNode *> DataEntriesTreeOrder;
591 uint32_t CurrentRelativeOffset = 0;
593 while (!Queue.empty()) {
594 auto CurrentNode = Queue.front();
596 auto *Table = reinterpret_cast<coff_resource_dir_table *>(BufferStart +
598 Table->Characteristics = CurrentNode->getCharacteristics();
599 Table->TimeDateStamp = 0;
600 Table->MajorVersion = CurrentNode->getMajorVersion();
601 Table->MinorVersion = CurrentNode->getMinorVersion();
602 auto &IDChildren = CurrentNode->getIDChildren();
603 auto &StringChildren = CurrentNode->getStringChildren();
604 Table->NumberOfNameEntries = StringChildren.size();
605 Table->NumberOfIDEntries = IDChildren.size();
606 CurrentOffset += sizeof(coff_resource_dir_table);
607 CurrentRelativeOffset += sizeof(coff_resource_dir_table);
609 // Write the directory entries immediately following each directory table.
610 for (auto const &Child : StringChildren) {
611 auto *Entry = reinterpret_cast<coff_resource_dir_entry *>(BufferStart +
613 Entry->Identifier.setNameOffset(
614 StringTableOffsets[Child.second->getStringIndex()]);
615 if (Child.second->checkIsDataNode()) {
616 Entry->Offset.DataEntryOffset = NextLevelOffset;
617 NextLevelOffset += sizeof(coff_resource_data_entry);
618 DataEntriesTreeOrder.push_back(Child.second.get());
620 Entry->Offset.SubdirOffset = NextLevelOffset + (1 << 31);
621 NextLevelOffset += sizeof(coff_resource_dir_table) +
622 (Child.second->getStringChildren().size() +
623 Child.second->getIDChildren().size()) *
624 sizeof(coff_resource_dir_entry);
625 Queue.push(Child.second.get());
627 CurrentOffset += sizeof(coff_resource_dir_entry);
628 CurrentRelativeOffset += sizeof(coff_resource_dir_entry);
630 for (auto const &Child : IDChildren) {
631 auto *Entry = reinterpret_cast<coff_resource_dir_entry *>(BufferStart +
633 Entry->Identifier.ID = Child.first;
634 if (Child.second->checkIsDataNode()) {
635 Entry->Offset.DataEntryOffset = NextLevelOffset;
636 NextLevelOffset += sizeof(coff_resource_data_entry);
637 DataEntriesTreeOrder.push_back(Child.second.get());
639 Entry->Offset.SubdirOffset = NextLevelOffset + (1 << 31);
640 NextLevelOffset += sizeof(coff_resource_dir_table) +
641 (Child.second->getStringChildren().size() +
642 Child.second->getIDChildren().size()) *
643 sizeof(coff_resource_dir_entry);
644 Queue.push(Child.second.get());
646 CurrentOffset += sizeof(coff_resource_dir_entry);
647 CurrentRelativeOffset += sizeof(coff_resource_dir_entry);
651 RelocationAddresses.resize(Data.size());
652 // Now write all the resource data entries.
653 for (auto DataNodes : DataEntriesTreeOrder) {
654 auto *Entry = reinterpret_cast<coff_resource_data_entry *>(BufferStart +
656 RelocationAddresses[DataNodes->getDataIndex()] = CurrentRelativeOffset;
657 Entry->DataRVA = 0; // Set to zero because it is a relocation.
658 Entry->DataSize = Data[DataNodes->getDataIndex()].size();
661 CurrentOffset += sizeof(coff_resource_data_entry);
662 CurrentRelativeOffset += sizeof(coff_resource_data_entry);
666 void WindowsResourceCOFFWriter::writeDirectoryStringTable() {
667 // Now write the directory string table for .rsrc$01
668 uint32_t TotalStringTableSize = 0;
669 for (auto &String : StringTable) {
670 uint16_t Length = String.size();
671 support::endian::write16le(BufferStart + CurrentOffset, Length);
672 CurrentOffset += sizeof(uint16_t);
673 auto *Start = reinterpret_cast<UTF16 *>(BufferStart + CurrentOffset);
674 llvm::copy(String, Start);
675 CurrentOffset += Length * sizeof(UTF16);
676 TotalStringTableSize += Length * sizeof(UTF16) + sizeof(uint16_t);
679 alignTo(TotalStringTableSize, sizeof(uint32_t)) - TotalStringTableSize;
682 void WindowsResourceCOFFWriter::writeFirstSectionRelocations() {
684 // Now write the relocations for .rsrc$01
685 // Five symbols already in table before we start, @feat.00 and 2 for each
687 uint32_t NextSymbolIndex = 5;
688 for (unsigned i = 0; i < Data.size(); i++) {
690 reinterpret_cast<coff_relocation *>(BufferStart + CurrentOffset);
691 Reloc->VirtualAddress = RelocationAddresses[i];
692 Reloc->SymbolTableIndex = NextSymbolIndex++;
693 switch (MachineType) {
694 case COFF::IMAGE_FILE_MACHINE_ARMNT:
695 Reloc->Type = COFF::IMAGE_REL_ARM_ADDR32NB;
697 case COFF::IMAGE_FILE_MACHINE_AMD64:
698 Reloc->Type = COFF::IMAGE_REL_AMD64_ADDR32NB;
700 case COFF::IMAGE_FILE_MACHINE_I386:
701 Reloc->Type = COFF::IMAGE_REL_I386_DIR32NB;
703 case COFF::IMAGE_FILE_MACHINE_ARM64:
704 Reloc->Type = COFF::IMAGE_REL_ARM64_ADDR32NB;
707 llvm_unreachable("unknown machine type");
709 CurrentOffset += sizeof(coff_relocation);
713 Expected<std::unique_ptr<MemoryBuffer>>
714 writeWindowsResourceCOFF(COFF::MachineTypes MachineType,
715 const WindowsResourceParser &Parser) {
716 Error E = Error::success();
717 WindowsResourceCOFFWriter Writer(MachineType, Parser, E);
720 return Writer.write();
723 } // namespace object