LLVM: lib/ObjectYAML/COFFEmitter.cpp Source File (original) (raw)

1

2

3

4

5

6

7

8

9

10

11

12

13

24#include

25#include

26

27using namespace llvm;

28

29namespace {

30

31

32

33struct COFFParser {

35 : Obj(Obj), SectionTableStart(0), SectionTableSize(0), ErrHandler(EH) {

36

37

38 StringTable.append(4, char(0));

39 }

40

41 bool useBigObj() const {

42 return static_cast<int32_t>(Obj.Sections.size()) >

44 }

45

46 bool isPE() const { return Obj.OptionalHeader.has_value(); }

48

49 uint32_t getFileAlignment() const {

50 return Obj.OptionalHeader->Header.FileAlignment;

51 }

52

55 }

56

57 unsigned getSymbolSize() const {

59 }

60

61 bool parseSections() {

62 for (COFFYAML::Section &Sec : Obj.Sections) {

63

64

66

69 } else {

70

72 std::string str = utostr(Index);

73 if (str.size() > 7) {

74 ErrHandler("string table got too large");

75 return false;

76 }

79 }

80

83 ErrHandler("section alignment is too large");

84 return false;

85 }

87 ErrHandler("section alignment is not a power of 2");

88 return false;

89 }

91 }

92 }

93 return true;

94 }

95

96 bool parseSymbols() {

97 for (COFFYAML::Symbol &Sym : Obj.Symbols) {

98

99

103 } else {

104

107 Index;

108 }

109

112 }

113 return true;

114 }

115

117 if (!parseSections())

118 return false;

119 if (!parseSymbols())

120 return false;

121 return true;

122 }

123

125 auto [It, Inserted] = StringTableMap.try_emplace(Str, StringTable.size());

126 if (Inserted) {

127 StringTable.append(Str.begin(), Str.end());

128 StringTable.push_back(0);

129 }

130 return It->second;

131 }

132

133 COFFYAML::Object &Obj;

134

135 codeview::StringsAndChecksums StringsAndChecksums;

137 StringMap StringTableMap;

138 std::string StringTable;

139 uint32_t SectionTableStart;

140 uint32_t SectionTableSize;

141

143};

144

145enum { DOSStubSize = 128 };

146

147}

148

149

150

152 if (!CP.isPE())

153 return true;

156 CP.Obj.Header.SizeOfOptionalHeader =

158 CP.Obj.OptionalHeader->Header.NumberOfRvaAndSize;

159 return true;

160}

161

166 ExitOnError Err("Error occurred writing .debug$S section");

167 auto CVSS =

169

170 std::vector Builders;

172 for (auto &SS : CVSS) {

173 DebugSubsectionRecordBuilder B(SS);

174 Size += B.calculateSerializedLength();

175 Builders.push_back(std::move(B));

176 }

180

182 for (const auto &B : Builders) {

183 Err(B.commit(Writer, CodeViewContainer::ObjectFile));

184 }

185 return {Output};

186}

187

188

189

191

192

193 CP.SectionTableStart =

194 CP.getHeaderSize() + CP.Obj.Header.SizeOfOptionalHeader;

195 if (CP.isPE())

196 CP.SectionTableStart += DOSStubSize + sizeof(COFF::PEMagic);

197 CP.SectionTableSize = COFF::SectionSize * CP.Obj.Sections.size();

198

199 uint32_t CurrentSectionDataOffset =

200 CP.SectionTableStart + CP.SectionTableSize;

201

203

204

207 CP.StringsAndChecksums);

208 if (CP.StringsAndChecksums.hasChecksums() &&

209 CP.StringsAndChecksums.hasStrings())

210 break;

211 }

212 }

213

214

216 if (S.Name == ".debug$S") {

218 assert(CP.StringsAndChecksums.hasStrings() &&

219 "Object file does not have debug string table!");

220

222 toDebugS(S.DebugS, CP.StringsAndChecksums, CP.Allocator);

223 }

224 } else if (S.Name == ".debug$T") {

227 } else if (S.Name == ".debug$P") {

230 } else if (S.Name == ".debug$H") {

233 }

234

239 CurrentSectionDataOffset = alignTo(CurrentSectionDataOffset,

240 CP.isPE() ? CP.getFileAlignment() : 4);

242 if (CP.isPE())

252 } else

255 }

256 } else {

257

258

260 }

261 }

262

263 uint32_t SymbolTableStart = CurrentSectionDataOffset;

264

265

266 uint32_t NumberOfSymbols = 0;

267 for (std::vectorCOFFYAML::Symbol::iterator i = CP.Obj.Symbols.begin(),

268 e = CP.Obj.Symbols.end();

269 i != e; ++i) {

270 uint32_t NumberOfAuxSymbols = 0;

271 if (i->FunctionDefinition)

272 NumberOfAuxSymbols += 1;

273 if (i->bfAndefSymbol)

274 NumberOfAuxSymbols += 1;

275 if (i->WeakExternal)

276 NumberOfAuxSymbols += 1;

277 if (!i->File.empty())

278 NumberOfAuxSymbols +=

279 (i->File.size() + CP.getSymbolSize() - 1) / CP.getSymbolSize();

280 if (i->SectionDefinition)

281 NumberOfAuxSymbols += 1;

282 if (i->CLRToken)

283 NumberOfAuxSymbols += 1;

284 i->Header.NumberOfAuxSymbols = NumberOfAuxSymbols;

285 NumberOfSymbols += 1 + NumberOfAuxSymbols;

286 }

287

288

289 CP.Obj.Header.NumberOfSections = CP.Obj.Sections.size();

290 CP.Obj.Header.NumberOfSymbols = NumberOfSymbols;

291 if (NumberOfSymbols > 0 || CP.StringTable.size() > 4)

292 CP.Obj.Header.PointerToSymbolTable = SymbolTableStart;

293 else

294 CP.Obj.Header.PointerToSymbolTable = 0;

295

297 CP.StringTable.size();

298

299 return true;

300}

301

306

307template <typename value_type>

310 char Buffer[sizeof(BLE.Value)];

314 return OS;

315}

316

317template <typename value_type>

321

323

324template <size_t NumBytes>

326 char Buffer[NumBytes];

327 memset(Buffer, 0, sizeof(Buffer));

328 OS.write(Buffer, sizeof(Buffer));

329 return OS;

330}

331

335

336template

338 T Header) {

339 memset(Header, 0, sizeof(*Header));

340 Header->Magic = Magic;

341 Header->SectionAlignment = CP.Obj.OptionalHeader->Header.SectionAlignment;

342 Header->FileAlignment = CP.Obj.OptionalHeader->Header.FileAlignment;

343 uint32_t SizeOfCode = 0, SizeOfInitializedData = 0,

344 SizeOfUninitializedData = 0;

345 uint32_t SizeOfHeaders = alignTo(CP.SectionTableStart + CP.SectionTableSize,

346 Header->FileAlignment);

347 uint32_t SizeOfImage = alignTo(SizeOfHeaders, Header->SectionAlignment);

356 if (S.Name == ".text")

358 else if (S.Name == ".data")

362 }

363 Header->SizeOfCode = SizeOfCode;

364 Header->SizeOfInitializedData = SizeOfInitializedData;

365 Header->SizeOfUninitializedData = SizeOfUninitializedData;

366 Header->AddressOfEntryPoint =

367 CP.Obj.OptionalHeader->Header.AddressOfEntryPoint;

368 Header->ImageBase = CP.Obj.OptionalHeader->Header.ImageBase;

369 Header->MajorOperatingSystemVersion =

370 CP.Obj.OptionalHeader->Header.MajorOperatingSystemVersion;

371 Header->MinorOperatingSystemVersion =

372 CP.Obj.OptionalHeader->Header.MinorOperatingSystemVersion;

373 Header->MajorImageVersion = CP.Obj.OptionalHeader->Header.MajorImageVersion;

374 Header->MinorImageVersion = CP.Obj.OptionalHeader->Header.MinorImageVersion;

375 Header->MajorSubsystemVersion =

376 CP.Obj.OptionalHeader->Header.MajorSubsystemVersion;

377 Header->MinorSubsystemVersion =

378 CP.Obj.OptionalHeader->Header.MinorSubsystemVersion;

379 Header->SizeOfImage = SizeOfImage;

380 Header->SizeOfHeaders = SizeOfHeaders;

381 Header->Subsystem = CP.Obj.OptionalHeader->Header.Subsystem;

382 Header->DLLCharacteristics = CP.Obj.OptionalHeader->Header.DLLCharacteristics;

383 Header->SizeOfStackReserve = CP.Obj.OptionalHeader->Header.SizeOfStackReserve;

384 Header->SizeOfStackCommit = CP.Obj.OptionalHeader->Header.SizeOfStackCommit;

385 Header->SizeOfHeapReserve = CP.Obj.OptionalHeader->Header.SizeOfHeapReserve;

386 Header->SizeOfHeapCommit = CP.Obj.OptionalHeader->Header.SizeOfHeapCommit;

387 Header->NumberOfRvaAndSize = CP.Obj.OptionalHeader->Header.NumberOfRvaAndSize;

388 return BaseOfData;

389}

390

392 if (CP.isPE()) {

393

395 memset(&DH, 0, sizeof(DH));

396

397

398 DH.Magic[0] = 'M';

399 DH.Magic[1] = 'Z';

400

401

402

404

406

407

408 OS.write(reinterpret_cast<char *>(&DH), sizeof(DH));

409

410

411 OS.write_zeros(DOSStubSize - sizeof(DH));

412

414 }

415 if (CP.useBigObj()) {

420 << binary_le(CP.Obj.Header.Machine)

421 << binary_le(CP.Obj.Header.TimeDateStamp);

425 << binary_le(CP.Obj.Header.PointerToSymbolTable)

426 << binary_le(CP.Obj.Header.NumberOfSymbols);

427 } else {

428 OS << binary_le(CP.Obj.Header.Machine)

429 << binary_le(static_cast<int16_t>(CP.Obj.Header.NumberOfSections))

430 << binary_le(CP.Obj.Header.TimeDateStamp)

431 << binary_le(CP.Obj.Header.PointerToSymbolTable)

432 << binary_le(CP.Obj.Header.NumberOfSymbols)

433 << binary_le(CP.Obj.Header.SizeOfOptionalHeader)

434 << binary_le(CP.Obj.Header.Characteristics);

435 }

436 if (CP.isPE()) {

437 if (CP.is64Bit()) {

440 OS.write(reinterpret_cast<char *>(&PEH), sizeof(PEH));

441 } else {

446 OS.write(reinterpret_cast<char *>(&PEH), sizeof(PEH));

447 }

448 for (uint32_t I = 0; I < CP.Obj.OptionalHeader->Header.NumberOfRvaAndSize;

449 ++I) {

450 const std::optionalCOFF::DataDirectory *DataDirectories =

451 CP.Obj.OptionalHeader->DataDirectories;

452 uint32_t NumDataDir = std::size(CP.Obj.OptionalHeader->DataDirectories);

453 if (I >= NumDataDir || !DataDirectories[I]) {

456 } else {

457 OS << binary_le(DataDirectories[I]->RelativeVirtualAddress);

459 }

460 }

461 }

462

463 assert(OS.tell() == CP.SectionTableStart);

464

476 }

477 assert(OS.tell() == CP.SectionTableStart + CP.SectionTableSize);

478

479 unsigned CurSymbol = 0;

482 SymbolTableIndexMap[Sym.Name] = CurSymbol;

484 }

485

486

489 continue;

493 E.writeAsBinary(OS);

499 OS << binary_le<uint32_t>( S.Relocations.size() + 1)

504 if (R.SymbolTableIndex) {

505 if (!R.SymbolName.empty())

507 << "Both SymbolName and SymbolTableIndex specified\n";

508 SymbolTableIndex = *R.SymbolTableIndex;

509 } else {

510 SymbolTableIndex = SymbolTableIndexMap[R.SymbolName];

511 }

514 }

515 }

516

517

518

519 for (std::vectorCOFFYAML::Symbol::const_iterator i = CP.Obj.Symbols.begin(),

520 e = CP.Obj.Symbols.end();

521 i != e; ++i) {

523 OS << binary_le(i->Header.Value);

524 if (CP.useBigObj())

525 OS << binary_le(i->Header.SectionNumber);

526 else

527 OS << binary_le(static_cast<int16_t>(i->Header.SectionNumber));

529 << binary_le(i->Header.NumberOfAuxSymbols);

530

531 if (i->FunctionDefinition) {

532 OS << binary_le(i->FunctionDefinition->TagIndex)

533 << binary_le(i->FunctionDefinition->TotalSize)

534 << binary_le(i->FunctionDefinition->PointerToLinenumber)

535 << binary_le(i->FunctionDefinition->PointerToNextFunction)

536 << zeros(i->FunctionDefinition->unused);

538 }

539 if (i->bfAndefSymbol) {

540 OS << zeros(i->bfAndefSymbol->unused1)

541 << binary_le(i->bfAndefSymbol->Linenumber)

542 << zeros(i->bfAndefSymbol->unused2)

543 << binary_le(i->bfAndefSymbol->PointerToNextFunction)

544 << zeros(i->bfAndefSymbol->unused3);

546 }

547 if (i->WeakExternal) {

548 OS << binary_le(i->WeakExternal->TagIndex)

549 << binary_le(i->WeakExternal->Characteristics)

550 << zeros(i->WeakExternal->unused);

552 }

553 if (!i->File.empty()) {

554 unsigned SymbolSize = CP.getSymbolSize();

555 uint32_t NumberOfAuxRecords =

556 (i->File.size() + SymbolSize - 1) / SymbolSize;

557 uint32_t NumberOfAuxBytes = NumberOfAuxRecords * SymbolSize;

558 uint32_t NumZeros = NumberOfAuxBytes - i->File.size();

559 OS.write(i->File.data(), i->File.size());

561 }

562 if (i->SectionDefinition) {

563 OS << binary_le(i->SectionDefinition->Length)

564 << binary_le(i->SectionDefinition->NumberOfRelocations)

565 << binary_le(i->SectionDefinition->NumberOfLinenumbers)

566 << binary_le(i->SectionDefinition->CheckSum)

567 << binary_le(static_cast<int16_t>(i->SectionDefinition->Number))

568 << binary_le(i->SectionDefinition->Selection)

569 << zeros(i->SectionDefinition->unused)

570 << binary_le(static_cast<int16_t>(i->SectionDefinition->Number >> 16));

572 }

573 if (i->CLRToken) {

574 OS << binary_le(i->CLRToken->AuxType) << zeros(i->CLRToken->unused1)

575 << binary_le(i->CLRToken->SymbolTableIndex)

576 << zeros(i->CLRToken->unused2);

578 }

579 }

580

581

582 if (CP.Obj.Header.PointerToSymbolTable)

583 OS.write(&CP.StringTable[0], CP.StringTable.size());

584 return true;

585}

586

590 Size += sizeof(*UInt32);

596}

597

599 OS.write(reinterpret_cast<const char *>(&S),

600 std::min(sizeof(S), static_cast<size_t>(S.Size)));

601 if (sizeof(S) < S.Size)

603}

604

608 Binary.writeAsBinary(OS);

613}

614

615namespace llvm {

616namespace yaml {

617

620 COFFParser CP(Doc, ErrHandler);

621 if (!CP.parse()) {

622 ErrHandler("failed to parse YAML file");

623 return false;

624 }

625

627 ErrHandler("failed to layout optional header for COFF file");

628 return false;

629 }

630

632 ErrHandler("failed to layout COFF file");

633 return false;

634 }

636 ErrHandler("failed to write COFF file");

637 return false;

638 }

639 return true;

640}

641

642}

643}

assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")

This file defines the StringMap class.

static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")

static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")

static bool layoutCOFF(COFFParser &CP)

Definition COFFEmitter.cpp:190

binary_le_impl< value_type > binary_le(value_type V)

Definition COFFEmitter.cpp:318

static void writeLoadConfig(T &S, raw_ostream &OS)

Definition COFFEmitter.cpp:598

static yaml::BinaryRef toDebugS(ArrayRef< CodeViewYAML::YAMLDebugSubsection > Subsections, const codeview::StringsAndChecksums &SC, BumpPtrAllocator &Allocator)

Definition COFFEmitter.cpp:163

zeros_impl< sizeof(T)> zeros(const T &)

Definition COFFEmitter.cpp:332

static uint32_t initializeOptionalHeader(COFFParser &CP, uint16_t Magic, T Header)

Definition COFFEmitter.cpp:337

static bool writeCOFF(COFFParser &CP, raw_ostream &OS)

Definition COFFEmitter.cpp:391

static bool layoutOptionalHeader(COFFParser &CP)

Definition COFFEmitter.cpp:151

static size_t getStringIndex(StringRef Name)

static llvm::Error parse(DataExtractor &Data, uint64_t BaseAddr, LineEntryCallback const &Callback)

static LLVM_PACKED_END size_t getHeaderSize(uint16_t Version)

static bool is64Bit(const char *name)

ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...

Provides write only access to a subclass of WritableBinaryStream.

Error writeInteger(T Value)

Write the integer Value to the underlying stream in the specified endianness.

Helper for check-and-exit error handling.

MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...

StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...

static LLVM_ABI raw_ostream & error()

Convenience method for printing "error: " to stderr.

This class implements an extremely fast bulk output stream that can only output to a stream.

raw_ostream & write_zeros(unsigned NumZeros)

write_zeros - Insert 'NumZeros' nulls.

uint64_t tell() const

tell - Return the current offset with the file.

raw_ostream & write(unsigned char C)

Specialized YAMLIO scalar type for representing a binary blob.

ArrayRef< uint8_t >::size_type binary_size() const

The number of bytes that are represented by this BinaryRef.

LLVM_ABI void writeAsBinary(raw_ostream &OS, uint64_t N=UINT64_MAX) const

Write the contents (regardless of whether it is binary or a hex string) as binary to the given raw_os...

@ IMAGE_FILE_MACHINE_UNKNOWN

@ IMAGE_SCN_CNT_UNINITIALIZED_DATA

@ IMAGE_SCN_CNT_INITIALIZED_DATA

@ IMAGE_SCN_LNK_NRELOC_OVFL

const int32_t MaxNumberOfSections16

static const char BigObjMagic[]

static const char PEMagic[]

@ SCT_COMPLEX_TYPE_SHIFT

Type is formed as (base + (derived << SCT_COMPLEX_TYPE_SHIFT))

LLVM_ABI void initializeStringsAndChecksums(ArrayRef< YAMLDebugSubsection > Sections, codeview::StringsAndChecksums &SC)

LLVM_ABI Expected< std::vector< std::shared_ptr< codeview::DebugSubsection > > > toCodeViewSubsectionList(BumpPtrAllocator &Allocator, ArrayRef< YAMLDebugSubsection > Subsections, const codeview::StringsAndChecksums &SC)

ArrayRef< uint8_t > toDebugH(const DebugHSection &DebugH, BumpPtrAllocator &Alloc)

LLVM_ABI ArrayRef< uint8_t > toDebugT(ArrayRef< LeafRecord >, BumpPtrAllocator &Alloc, StringRef SectionName)

void write(void *memory, value_type value, endianness endian)

Write a value to memory with a particular endianness.

detail::packed_endian_specific_integral< uint32_t, llvm::endianness::little, unaligned > ulittle32_t

detail::packed_endian_specific_integral< uint32_t, llvm::endianness::little, aligned > aligned_ulittle32_t

LLVM_ABI bool yaml2coff(COFFYAML::Object &Doc, raw_ostream &Out, ErrorHandler EH)

Definition COFFEmitter.cpp:618

llvm::function_ref< void(const Twine &Msg)> ErrorHandler

This is an optimization pass for GlobalISel generic memory operations.

FunctionAddr VTableAddr uintptr_t uintptr_t DataSize

std::string utostr(uint64_t X, bool isNeg=false)

unsigned Log2_32(uint32_t Value)

Return the floor log base 2 of the specified value, -1 if the value is zero.

constexpr bool isPowerOf2_32(uint32_t Value)

Return true if the argument is a power of two > 0.

uint64_t alignTo(uint64_t Size, Align A)

Returns a multiple of A needed to store Size bytes.

raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)

OutputIt copy(R &&Range, OutputIt Out)

BumpPtrAllocatorImpl<> BumpPtrAllocator

The standard BumpPtrAllocator which just uses the default template parameters.

Definition COFFEmitter.cpp:302

binary_le_impl(value_type V)

Definition COFFEmitter.cpp:304

value_type Value

Definition COFFEmitter.cpp:303

std::optional< object::coff_load_configuration64 > LoadConfig64

std::optional< object::coff_load_configuration32 > LoadConfig32

void writeAsBinary(raw_ostream &OS) const

Definition COFFEmitter.cpp:605

std::optional< uint32_t > UInt32

size_t size() const

Definition COFFEmitter.cpp:587

std::vector< CodeViewYAML::YAMLDebugSubsection > DebugS

std::vector< SectionDataEntry > StructuredData

std::vector< CodeViewYAML::LeafRecord > DebugT

yaml::BinaryRef SectionData

std::optional< CodeViewYAML::DebugHSection > DebugH

std::vector< CodeViewYAML::LeafRecord > DebugP

std::vector< Relocation > Relocations

COFF::SymbolComplexType ComplexType

COFF::SymbolBaseType SimpleType

uint32_t PointerToRelocations

uint16_t NumberOfLineNumbers

uint32_t PointerToRawData

uint16_t NumberOfRelocations

uint32_t PointerToLineNumbers

uint8_t NumberOfAuxSymbols

Definition COFFEmitter.cpp:322

Common declarations for yaml2obj.