24using namespace object;
27Error COFFWriter::finalizeRelocTargets() {
29 for (Relocation &R : Sec.Relocs) {
33 "relocation target '%s' (%zu) not found",
34 R.TargetName.str().c_str(),
R.Target);
35 R.Reloc.SymbolTableIndex =
Sym->RawIndex;
41Error COFFWriter::finalizeSymbolContents() {
43 if (
Sym.TargetSectionId <= 0) {
46 Sym.Sym.SectionNumber =
static_cast<uint32_t>(
Sym.TargetSectionId);
51 "symbol '%s' points to a removed section",
52 Sym.Name.str().c_str());
53 Sym.Sym.SectionNumber = Sec->Index;
55 if (
Sym.Sym.NumberOfAuxSymbols == 1 &&
57 coff_aux_section_definition *SD =
58 reinterpret_cast<coff_aux_section_definition *
>(
59 Sym.AuxData[0].Opaque);
61 if (
Sym.AssociativeComdatTargetSectionId == 0) {
64 SDSectionNumber = Sec->Index;
69 object_error::invalid_symbol_index,
70 "symbol '%s' is associative to a removed section",
71 Sym.Name.str().c_str());
72 SDSectionNumber = Sec->Index;
75 SD->NumberLowPart =
static_cast<uint16_t>(SDSectionNumber);
76 SD->NumberHighPart =
static_cast<uint16_t>(SDSectionNumber >> 16);
81 if (
Sym.WeakTargetSymbolId &&
Sym.Sym.NumberOfAuxSymbols == 1) {
82 coff_aux_weak_external *WE =
83 reinterpret_cast<coff_aux_weak_external *
>(
Sym.AuxData[0].Opaque);
85 if (Target ==
nullptr)
87 "symbol '%s' is missing its weak target",
88 Sym.Name.str().c_str());
89 WE->TagIndex =
Target->RawIndex;
95void COFFWriter::layoutSections() {
97 if (S.Header.SizeOfRawData > 0)
98 S.Header.PointerToRawData = FileSize;
100 S.Header.PointerToRawData = 0;
101 FileSize += S.Header.SizeOfRawData;
103 if (S.Relocs.size() >= 0xffff) {
105 S.Header.NumberOfRelocations = 0xffff;
106 S.Header.PointerToRelocations = FileSize;
107 FileSize +=
sizeof(coff_relocation);
109 S.Header.NumberOfRelocations = S.Relocs.size();
110 S.Header.PointerToRelocations = S.Relocs.size() ? FileSize : 0;
113 FileSize += S.Relocs.size() *
sizeof(coff_relocation);
114 FileSize =
alignTo(FileSize, FileAlignment);
117 SizeOfInitializedData += S.Header.SizeOfRawData;
121Expected<size_t> COFFWriter::finalizeStringTable() {
124 StrTabBuilder.
add(S.Name);
128 StrTabBuilder.
add(S.Name);
133 memset(S.Header.Name, 0,
sizeof(S.Header.Name));
136 memcpy(S.Header.Name, S.Name.data(), S.Name.size());
142 "COFF string table is greater than 64GB, "
143 "unable to encode section name offset");
148 S.Sym.Name.Offset.Zeroes = 0;
149 S.Sym.Name.Offset.Offset = StrTabBuilder.
getOffset(S.Name);
154 return StrTabBuilder.
getSize();
157template <
class SymbolTy>
158std::pair<size_t, size_t> COFFWriter::finalizeSymbolTable() {
159 size_t RawSymIndex = 0;
164 if (!S.AuxFile.empty())
165 S.Sym.NumberOfAuxSymbols =
166 alignTo(S.AuxFile.size(),
sizeof(SymbolTy)) /
sizeof(SymbolTy);
167 S.RawIndex = RawSymIndex;
168 RawSymIndex += 1 + S.Sym.NumberOfAuxSymbols;
170 return std::make_pair(RawSymIndex *
sizeof(SymbolTy),
sizeof(SymbolTy));
173Error COFFWriter::finalize(
bool IsBigObj) {
174 size_t SymTabSize, SymbolSize;
175 std::tie(SymTabSize, SymbolSize) = IsBigObj
176 ? finalizeSymbolTable<coff_symbol32>()
179 if (Error
E = finalizeRelocTargets())
181 if (Error
E = finalizeSymbolContents())
184 size_t SizeOfHeaders = 0;
186 size_t PeHeaderSize = 0;
195 PeHeaderSize = Obj.
Is64 ?
sizeof(pe32plus_header) :
sizeof(pe32_header);
201 IsBigObj ?
sizeof(coff_bigobj_file_header) :
sizeof(coff_file_header);
202 SizeOfHeaders +=
sizeof(coff_section) * Obj.
getSections().size();
203 SizeOfHeaders =
alignTo(SizeOfHeaders, FileAlignment);
208 FileSize = SizeOfHeaders;
209 SizeOfInitializedData = 0;
220 alignTo(S.Header.VirtualAddress + S.Header.VirtualSize,
229 Expected<size_t> StrTabSizeOrErr = finalizeStringTable();
230 if (!StrTabSizeOrErr)
231 return StrTabSizeOrErr.takeError();
233 size_t StrTabSize = *StrTabSizeOrErr;
235 size_t PointerToSymbolTable = FileSize;
238 if (SymTabSize == 0 && StrTabSize <= 4 && Obj.
IsPE) {
241 PointerToSymbolTable = 0;
245 size_t NumRawSymbols = SymTabSize / SymbolSize;
248 FileSize += SymTabSize + StrTabSize;
249 FileSize =
alignTo(FileSize, FileAlignment);
254void COFFWriter::writeHeaders(
bool IsBigObj) {
271 coff_bigobj_file_header BigObjHeader;
273 BigObjHeader.Sig2 = 0xffff;
278 BigObjHeader.unused1 = 0;
279 BigObjHeader.unused2 = 0;
280 BigObjHeader.unused3 = 0;
281 BigObjHeader.unused4 = 0;
284 BigObjHeader.NumberOfSections = Obj.
getSections().size();
288 memcpy(
Ptr, &BigObjHeader,
sizeof(BigObjHeader));
289 Ptr +=
sizeof(BigObjHeader);
296 pe32_header PeHeader;
301 memcpy(
Ptr, &PeHeader,
sizeof(PeHeader));
302 Ptr +=
sizeof(PeHeader);
305 memcpy(
Ptr, &DD,
sizeof(DD));
310 memcpy(
Ptr, &S.Header,
sizeof(S.Header));
311 Ptr +=
sizeof(S.Header);
315void COFFWriter::writeSections() {
318 S.Header.PointerToRawData;
319 ArrayRef<uint8_t> Contents = S.getContents();
320 std::copy(Contents.begin(), Contents.end(),
Ptr);
325 S.Header.SizeOfRawData > Contents.size())
326 memset(
Ptr + Contents.size(), 0xcc,
327 S.Header.SizeOfRawData - Contents.size());
329 Ptr += S.Header.SizeOfRawData;
331 if (S.Relocs.size() >= 0xffff) {
332 object::coff_relocation
R;
333 R.VirtualAddress = S.Relocs.size() + 1;
334 R.SymbolTableIndex = 0;
336 memcpy(
Ptr, &R,
sizeof(R));
339 for (
const auto &R : S.Relocs) {
340 memcpy(
Ptr, &
R.Reloc,
sizeof(
R.Reloc));
341 Ptr +=
sizeof(
R.Reloc);
346template <
class SymbolTy>
void COFFWriter::writeSymbolStringTables() {
351 copySymbol<SymbolTy, coff_symbol32>(*
reinterpret_cast<SymbolTy *
>(
Ptr),
353 Ptr +=
sizeof(SymbolTy);
354 if (!S.AuxFile.empty()) {
358 std::copy(S.AuxFile.begin(), S.AuxFile.end(),
Ptr);
359 Ptr += S.Sym.NumberOfAuxSymbols *
sizeof(SymbolTy);
365 for (
const AuxSymbol &AuxSym : S.AuxData) {
366 ArrayRef<uint8_t>
Ref = AuxSym.getRef();
368 Ptr +=
sizeof(SymbolTy);
386 "failed to allocate memory buffer of " +
389 writeHeaders(IsBigObj);
392 writeSymbolStringTables<coff_symbol32>();
394 writeSymbolStringTables<coff_symbol16>();
397 if (Error
E = patchDebugDirectory())
402 Out.
write(Buf->getBufferStart(), Buf->getBufferSize());
406Expected<uint32_t> COFFWriter::virtualAddressToFileAddress(
uint32_t RVA) {
408 if (RVA >= S.Header.VirtualAddress &&
409 RVA < S.Header.VirtualAddress + S.Header.SizeOfRawData)
410 return S.Header.PointerToRawData + RVA - S.Header.VirtualAddress;
413 "debug directory payload not found");
419Error COFFWriter::patchDebugDirectory() {
426 if (Dir->RelativeVirtualAddress >= S.Header.VirtualAddress &&
427 Dir->RelativeVirtualAddress <
428 S.Header.VirtualAddress + S.Header.SizeOfRawData) {
429 if (Dir->RelativeVirtualAddress + Dir->Size >
430 S.Header.VirtualAddress + S.Header.SizeOfRawData)
432 "debug directory extends past end of section");
434 size_t Offset = Dir->RelativeVirtualAddress - S.Header.VirtualAddress;
436 S.Header.PointerToRawData +
Offset;
439 debug_directory *
Debug =
reinterpret_cast<debug_directory *
>(
Ptr);
440 if (
Debug->PointerToRawData) {
441 if (Expected<uint32_t> FilePosOrErr =
442 virtualAddressToFileAddress(
Debug->AddressOfRawData))
443 Debug->PointerToRawData = *FilePosOrErr;
445 return FilePosOrErr.takeError();
447 Ptr +=
sizeof(debug_directory);
448 Offset +=
sizeof(debug_directory);
455 "debug directory not found");
460 if (IsBigObj && Obj.
IsPE)
462 "too many sections for executable");
463 return write(IsBigObj);
for(const MachineOperand &MO :llvm::drop_begin(OldMI.operands(), Desc.getNumOperands()))
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
while(!ToSimplify.empty())
size_t size() const
size - Get the array size.
Lightweight error class with error context and mandatory checking.
static ErrorSuccess success()
Create a success value.
size_t getOffset(CachedHashStringRef S) const
Get the offest of a string in the string table.
void write(raw_ostream &OS) const
size_t add(CachedHashStringRef S)
Add a string to the builder.
void finalize()
Analyze the strings and build the final table.
static Twine utohexstr(const uint64_t &Val)
static std::unique_ptr< WritableMemoryBuffer > getNewMemBuffer(size_t Size, const Twine &BufferName="")
Allocate a new zero-initialized MemoryBuffer of the specified size.
raw_ostream & write(unsigned char C)
@ IMAGE_FILE_MACHINE_UNKNOWN
@ IMAGE_SCN_CNT_INITIALIZED_DATA
@ IMAGE_SCN_LNK_NRELOC_OVFL
@ IMAGE_SYM_CLASS_STATIC
Static.
bool encodeSectionName(char *Out, uint64_t Offset)
Encode section name based on string table offset.
const int32_t MaxNumberOfSections16
static const char BigObjMagic[]
static const char PEMagic[]
void copyPeHeader(PeHeader1Ty &Dest, const PeHeader2Ty &Src)
coff_symbol< support::ulittle16_t > coff_symbol16
This is an optimization pass for GlobalISel generic memory operations.
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
@ Ref
The access may reference the value stored in memory.
uint64_t alignTo(uint64_t Size, Align A)
Returns a multiple of A needed to store Size bytes.
ArrayRef< Symbol > getSymbols() const
ArrayRef< uint8_t > DosStub
iterator_range< std::vector< Symbol >::iterator > getMutableSymbols()
object::coff_file_header CoffFileHeader
const Symbol * findSymbol(size_t UniqueId) const
std::vector< object::data_directory > DataDirectories
const Section * findSection(ssize_t UniqueId) const
object::pe32plus_header PeHeader
iterator_range< std::vector< Section >::iterator > getMutableSections()
object::dos_header DosHeader
ArrayRef< Section > getSections() const