1 //===- DWARFEmitter - Convert YAML to DWARF binary data -------------------===// 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 /// \file 10 /// The DWARF component of yaml2obj. Provided as library code for tests. 11 /// 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/ObjectYAML/DWARFEmitter.h" 15 #include "llvm/ADT/ArrayRef.h" 16 #include "llvm/ADT/StringMap.h" 17 #include "llvm/ADT/StringRef.h" 18 #include "llvm/ADT/StringSwitch.h" 19 #include "llvm/BinaryFormat/Dwarf.h" 20 #include "llvm/ObjectYAML/DWARFYAML.h" 21 #include "llvm/Support/Errc.h" 22 #include "llvm/Support/Error.h" 23 #include "llvm/Support/Host.h" 24 #include "llvm/Support/LEB128.h" 25 #include "llvm/Support/MathExtras.h" 26 #include "llvm/Support/MemoryBuffer.h" 27 #include "llvm/Support/SourceMgr.h" 28 #include "llvm/Support/SwapByteOrder.h" 29 #include "llvm/Support/YAMLTraits.h" 30 #include "llvm/Support/raw_ostream.h" 31 #include <algorithm> 32 #include <cassert> 33 #include <cstddef> 34 #include <cstdint> 35 #include <memory> 36 #include <string> 37 #include <vector> 38 39 using namespace llvm; 40 41 template <typename T> 42 static void writeInteger(T Integer, raw_ostream &OS, bool IsLittleEndian) { 43 if (IsLittleEndian != sys::IsLittleEndianHost) 44 sys::swapByteOrder(Integer); 45 OS.write(reinterpret_cast<char *>(&Integer), sizeof(T)); 46 } 47 48 static Error writeVariableSizedInteger(uint64_t Integer, size_t Size, 49 raw_ostream &OS, bool IsLittleEndian) { 50 if (8 == Size) 51 writeInteger((uint64_t)Integer, OS, IsLittleEndian); 52 else if (4 == Size) 53 writeInteger((uint32_t)Integer, OS, IsLittleEndian); 54 else if (2 == Size) 55 writeInteger((uint16_t)Integer, OS, IsLittleEndian); 56 else if (1 == Size) 57 writeInteger((uint8_t)Integer, OS, IsLittleEndian); 58 else 59 return createStringError(errc::not_supported, 60 "invalid integer write size: %zu", Size); 61 62 return Error::success(); 63 } 64 65 static void ZeroFillBytes(raw_ostream &OS, size_t Size) { 66 std::vector<uint8_t> FillData; 67 FillData.insert(FillData.begin(), Size, 0); 68 OS.write(reinterpret_cast<char *>(FillData.data()), Size); 69 } 70 71 static void writeInitialLength(const DWARFYAML::InitialLength &Length, 72 raw_ostream &OS, bool IsLittleEndian) { 73 writeInteger((uint32_t)Length.TotalLength, OS, IsLittleEndian); 74 if (Length.isDWARF64()) 75 writeInteger((uint64_t)Length.TotalLength64, OS, IsLittleEndian); 76 } 77 78 static void writeInitialLength(const dwarf::DwarfFormat Format, 79 const uint64_t Length, raw_ostream &OS, 80 bool IsLittleEndian) { 81 bool IsDWARF64 = Format == dwarf::DWARF64; 82 if (IsDWARF64) 83 cantFail(writeVariableSizedInteger(dwarf::DW_LENGTH_DWARF64, 4, OS, 84 IsLittleEndian)); 85 cantFail( 86 writeVariableSizedInteger(Length, IsDWARF64 ? 8 : 4, OS, IsLittleEndian)); 87 } 88 89 static void writeDWARFOffset(uint64_t Offset, dwarf::DwarfFormat Format, 90 raw_ostream &OS, bool IsLittleEndian) { 91 cantFail(writeVariableSizedInteger(Offset, Format == dwarf::DWARF64 ? 8 : 4, 92 OS, IsLittleEndian)); 93 } 94 95 Error DWARFYAML::emitDebugStr(raw_ostream &OS, const DWARFYAML::Data &DI) { 96 for (auto Str : DI.DebugStrings) { 97 OS.write(Str.data(), Str.size()); 98 OS.write('\0'); 99 } 100 101 return Error::success(); 102 } 103 104 Error DWARFYAML::emitDebugAbbrev(raw_ostream &OS, const DWARFYAML::Data &DI) { 105 uint64_t AbbrevCode = 0; 106 for (auto AbbrevDecl : DI.AbbrevDecls) { 107 AbbrevCode = AbbrevDecl.Code ? (uint64_t)*AbbrevDecl.Code : AbbrevCode + 1; 108 encodeULEB128(AbbrevCode, OS); 109 encodeULEB128(AbbrevDecl.Tag, OS); 110 OS.write(AbbrevDecl.Children); 111 for (auto Attr : AbbrevDecl.Attributes) { 112 encodeULEB128(Attr.Attribute, OS); 113 encodeULEB128(Attr.Form, OS); 114 if (Attr.Form == dwarf::DW_FORM_implicit_const) 115 encodeSLEB128(Attr.Value, OS); 116 } 117 encodeULEB128(0, OS); 118 encodeULEB128(0, OS); 119 } 120 121 // The abbreviations for a given compilation unit end with an entry consisting 122 // of a 0 byte for the abbreviation code. 123 OS.write_zeros(1); 124 125 return Error::success(); 126 } 127 128 Error DWARFYAML::emitDebugAranges(raw_ostream &OS, const DWARFYAML::Data &DI) { 129 assert(DI.DebugAranges && "unexpected emitDebugAranges() call"); 130 for (auto Range : *DI.DebugAranges) { 131 uint8_t AddrSize; 132 if (Range.AddrSize) 133 AddrSize = *Range.AddrSize; 134 else 135 AddrSize = DI.Is64BitAddrSize ? 8 : 4; 136 137 uint64_t Length = 4; // sizeof(version) 2 + sizeof(address_size) 1 + 138 // sizeof(segment_selector_size) 1 139 Length += 140 Range.Format == dwarf::DWARF64 ? 8 : 4; // sizeof(debug_info_offset) 141 142 const uint64_t HeaderLength = 143 Length + (Range.Format == dwarf::DWARF64 144 ? 12 145 : 4); // sizeof(unit_header) = 12 (DWARF64) or 4 (DWARF32) 146 const uint64_t PaddedHeaderLength = alignTo(HeaderLength, AddrSize * 2); 147 148 if (Range.Length) { 149 Length = *Range.Length; 150 } else { 151 Length += PaddedHeaderLength - HeaderLength; 152 Length += AddrSize * 2 * (Range.Descriptors.size() + 1); 153 } 154 155 writeInitialLength(Range.Format, Length, OS, DI.IsLittleEndian); 156 writeInteger((uint16_t)Range.Version, OS, DI.IsLittleEndian); 157 writeDWARFOffset(Range.CuOffset, Range.Format, OS, DI.IsLittleEndian); 158 writeInteger((uint8_t)AddrSize, OS, DI.IsLittleEndian); 159 writeInteger((uint8_t)Range.SegSize, OS, DI.IsLittleEndian); 160 ZeroFillBytes(OS, PaddedHeaderLength - HeaderLength); 161 162 for (auto Descriptor : Range.Descriptors) { 163 if (Error Err = writeVariableSizedInteger(Descriptor.Address, AddrSize, 164 OS, DI.IsLittleEndian)) 165 return createStringError(errc::not_supported, 166 "unable to write debug_aranges address: %s", 167 toString(std::move(Err)).c_str()); 168 cantFail(writeVariableSizedInteger(Descriptor.Length, AddrSize, OS, 169 DI.IsLittleEndian)); 170 } 171 ZeroFillBytes(OS, AddrSize * 2); 172 } 173 174 return Error::success(); 175 } 176 177 Error DWARFYAML::emitDebugRanges(raw_ostream &OS, const DWARFYAML::Data &DI) { 178 const size_t RangesOffset = OS.tell(); 179 uint64_t EntryIndex = 0; 180 for (auto DebugRanges : DI.DebugRanges) { 181 const size_t CurrOffset = OS.tell() - RangesOffset; 182 if (DebugRanges.Offset && (uint64_t)*DebugRanges.Offset < CurrOffset) 183 return createStringError(errc::invalid_argument, 184 "'Offset' for 'debug_ranges' with index " + 185 Twine(EntryIndex) + 186 " must be greater than or equal to the " 187 "number of bytes written already (0x" + 188 Twine::utohexstr(CurrOffset) + ")"); 189 if (DebugRanges.Offset) 190 ZeroFillBytes(OS, *DebugRanges.Offset - CurrOffset); 191 192 uint8_t AddrSize; 193 if (DebugRanges.AddrSize) 194 AddrSize = *DebugRanges.AddrSize; 195 else 196 AddrSize = DI.Is64BitAddrSize ? 8 : 4; 197 for (auto Entry : DebugRanges.Entries) { 198 if (Error Err = writeVariableSizedInteger(Entry.LowOffset, AddrSize, OS, 199 DI.IsLittleEndian)) 200 return createStringError( 201 errc::not_supported, 202 "unable to write debug_ranges address offset: %s", 203 toString(std::move(Err)).c_str()); 204 cantFail(writeVariableSizedInteger(Entry.HighOffset, AddrSize, OS, 205 DI.IsLittleEndian)); 206 } 207 ZeroFillBytes(OS, AddrSize * 2); 208 ++EntryIndex; 209 } 210 211 return Error::success(); 212 } 213 214 static Error emitPubSection(raw_ostream &OS, const DWARFYAML::PubSection &Sect, 215 bool IsLittleEndian, bool IsGNUPubSec = false) { 216 writeInitialLength(Sect.Length, OS, IsLittleEndian); 217 writeInteger((uint16_t)Sect.Version, OS, IsLittleEndian); 218 writeInteger((uint32_t)Sect.UnitOffset, OS, IsLittleEndian); 219 writeInteger((uint32_t)Sect.UnitSize, OS, IsLittleEndian); 220 for (auto Entry : Sect.Entries) { 221 writeInteger((uint32_t)Entry.DieOffset, OS, IsLittleEndian); 222 if (IsGNUPubSec) 223 writeInteger((uint8_t)Entry.Descriptor, OS, IsLittleEndian); 224 OS.write(Entry.Name.data(), Entry.Name.size()); 225 OS.write('\0'); 226 } 227 228 return Error::success(); 229 } 230 231 Error DWARFYAML::emitDebugPubnames(raw_ostream &OS, const Data &DI) { 232 assert(DI.PubNames && "unexpected emitDebugPubnames() call"); 233 return emitPubSection(OS, *DI.PubNames, DI.IsLittleEndian); 234 } 235 236 Error DWARFYAML::emitDebugPubtypes(raw_ostream &OS, const Data &DI) { 237 assert(DI.PubTypes && "unexpected emitDebugPubtypes() call"); 238 return emitPubSection(OS, *DI.PubTypes, DI.IsLittleEndian); 239 } 240 241 Error DWARFYAML::emitDebugGNUPubnames(raw_ostream &OS, const Data &DI) { 242 assert(DI.GNUPubNames && "unexpected emitDebugGNUPubnames() call"); 243 return emitPubSection(OS, *DI.GNUPubNames, DI.IsLittleEndian, 244 /*IsGNUStyle=*/true); 245 } 246 247 Error DWARFYAML::emitDebugGNUPubtypes(raw_ostream &OS, const Data &DI) { 248 assert(DI.GNUPubTypes && "unexpected emitDebugGNUPubtypes() call"); 249 return emitPubSection(OS, *DI.GNUPubTypes, DI.IsLittleEndian, 250 /*IsGNUStyle=*/true); 251 } 252 253 static Expected<uint64_t> writeDIE(ArrayRef<DWARFYAML::Abbrev> AbbrevDecls, 254 const dwarf::FormParams &Params, 255 const DWARFYAML::Entry &Entry, 256 raw_ostream &OS, bool IsLittleEndian) { 257 uint64_t EntryBegin = OS.tell(); 258 encodeULEB128(Entry.AbbrCode, OS); 259 uint32_t AbbrCode = Entry.AbbrCode; 260 if (AbbrCode == 0 || Entry.Values.empty()) 261 return OS.tell() - EntryBegin; 262 263 if (AbbrCode > AbbrevDecls.size()) 264 return createStringError( 265 errc::invalid_argument, 266 "abbrev code must be less than or equal to the number of " 267 "entries in abbreviation table"); 268 const DWARFYAML::Abbrev &Abbrev = AbbrevDecls[AbbrCode - 1]; 269 auto FormVal = Entry.Values.begin(); 270 auto AbbrForm = Abbrev.Attributes.begin(); 271 for (; FormVal != Entry.Values.end() && AbbrForm != Abbrev.Attributes.end(); 272 ++FormVal, ++AbbrForm) { 273 dwarf::Form Form = AbbrForm->Form; 274 bool Indirect; 275 do { 276 Indirect = false; 277 switch (Form) { 278 case dwarf::DW_FORM_addr: 279 // TODO: Test this error. 280 if (Error Err = writeVariableSizedInteger( 281 FormVal->Value, Params.AddrSize, OS, IsLittleEndian)) 282 return std::move(Err); 283 break; 284 case dwarf::DW_FORM_ref_addr: 285 // TODO: Test this error. 286 if (Error Err = writeVariableSizedInteger(FormVal->Value, 287 Params.getRefAddrByteSize(), 288 OS, IsLittleEndian)) 289 return std::move(Err); 290 break; 291 case dwarf::DW_FORM_exprloc: 292 case dwarf::DW_FORM_block: 293 encodeULEB128(FormVal->BlockData.size(), OS); 294 OS.write((const char *)FormVal->BlockData.data(), 295 FormVal->BlockData.size()); 296 break; 297 case dwarf::DW_FORM_block1: { 298 writeInteger((uint8_t)FormVal->BlockData.size(), OS, IsLittleEndian); 299 OS.write((const char *)FormVal->BlockData.data(), 300 FormVal->BlockData.size()); 301 break; 302 } 303 case dwarf::DW_FORM_block2: { 304 writeInteger((uint16_t)FormVal->BlockData.size(), OS, IsLittleEndian); 305 OS.write((const char *)FormVal->BlockData.data(), 306 FormVal->BlockData.size()); 307 break; 308 } 309 case dwarf::DW_FORM_block4: { 310 writeInteger((uint32_t)FormVal->BlockData.size(), OS, IsLittleEndian); 311 OS.write((const char *)FormVal->BlockData.data(), 312 FormVal->BlockData.size()); 313 break; 314 } 315 case dwarf::DW_FORM_strx: 316 case dwarf::DW_FORM_addrx: 317 case dwarf::DW_FORM_rnglistx: 318 case dwarf::DW_FORM_loclistx: 319 case dwarf::DW_FORM_udata: 320 case dwarf::DW_FORM_ref_udata: 321 case dwarf::DW_FORM_GNU_addr_index: 322 case dwarf::DW_FORM_GNU_str_index: 323 encodeULEB128(FormVal->Value, OS); 324 break; 325 case dwarf::DW_FORM_data1: 326 case dwarf::DW_FORM_ref1: 327 case dwarf::DW_FORM_flag: 328 case dwarf::DW_FORM_strx1: 329 case dwarf::DW_FORM_addrx1: 330 writeInteger((uint8_t)FormVal->Value, OS, IsLittleEndian); 331 break; 332 case dwarf::DW_FORM_data2: 333 case dwarf::DW_FORM_ref2: 334 case dwarf::DW_FORM_strx2: 335 case dwarf::DW_FORM_addrx2: 336 writeInteger((uint16_t)FormVal->Value, OS, IsLittleEndian); 337 break; 338 case dwarf::DW_FORM_data4: 339 case dwarf::DW_FORM_ref4: 340 case dwarf::DW_FORM_ref_sup4: 341 case dwarf::DW_FORM_strx4: 342 case dwarf::DW_FORM_addrx4: 343 writeInteger((uint32_t)FormVal->Value, OS, IsLittleEndian); 344 break; 345 case dwarf::DW_FORM_data8: 346 case dwarf::DW_FORM_ref8: 347 case dwarf::DW_FORM_ref_sup8: 348 case dwarf::DW_FORM_ref_sig8: 349 writeInteger((uint64_t)FormVal->Value, OS, IsLittleEndian); 350 break; 351 case dwarf::DW_FORM_sdata: 352 encodeSLEB128(FormVal->Value, OS); 353 break; 354 case dwarf::DW_FORM_string: 355 OS.write(FormVal->CStr.data(), FormVal->CStr.size()); 356 OS.write('\0'); 357 break; 358 case dwarf::DW_FORM_indirect: 359 encodeULEB128(FormVal->Value, OS); 360 Indirect = true; 361 Form = static_cast<dwarf::Form>((uint64_t)FormVal->Value); 362 ++FormVal; 363 break; 364 case dwarf::DW_FORM_strp: 365 case dwarf::DW_FORM_sec_offset: 366 case dwarf::DW_FORM_GNU_ref_alt: 367 case dwarf::DW_FORM_GNU_strp_alt: 368 case dwarf::DW_FORM_line_strp: 369 case dwarf::DW_FORM_strp_sup: 370 cantFail(writeVariableSizedInteger(FormVal->Value, 371 Params.getDwarfOffsetByteSize(), OS, 372 IsLittleEndian)); 373 break; 374 default: 375 break; 376 } 377 } while (Indirect); 378 } 379 380 return OS.tell() - EntryBegin; 381 } 382 383 Error DWARFYAML::emitDebugInfo(raw_ostream &OS, const DWARFYAML::Data &DI) { 384 for (const DWARFYAML::Unit &Unit : DI.CompileUnits) { 385 dwarf::FormParams Params = {Unit.Version, Unit.AddrSize, Unit.Format}; 386 uint64_t Length = 3; // sizeof(version) + sizeof(address_size) 387 Length += Unit.Version >= 5 ? 1 : 0; // sizeof(unit_type) 388 Length += Params.getDwarfOffsetByteSize(); // sizeof(debug_abbrev_offset) 389 390 // Since the length of the current compilation unit is undetermined yet, we 391 // firstly write the content of the compilation unit to a buffer to 392 // calculate it and then serialize the buffer content to the actual output 393 // stream. 394 std::string EntryBuffer; 395 raw_string_ostream EntryBufferOS(EntryBuffer); 396 397 for (const DWARFYAML::Entry &Entry : Unit.Entries) { 398 if (Expected<uint64_t> EntryLength = writeDIE( 399 DI.AbbrevDecls, Params, Entry, EntryBufferOS, DI.IsLittleEndian)) 400 Length += *EntryLength; 401 else 402 return EntryLength.takeError(); 403 } 404 405 // If the length is specified in the YAML description, we use it instead of 406 // the actual length. 407 if (Unit.Length) 408 Length = *Unit.Length; 409 410 writeInitialLength(Unit.Format, Length, OS, DI.IsLittleEndian); 411 writeInteger((uint16_t)Unit.Version, OS, DI.IsLittleEndian); 412 if (Unit.Version >= 5) { 413 writeInteger((uint8_t)Unit.Type, OS, DI.IsLittleEndian); 414 writeInteger((uint8_t)Unit.AddrSize, OS, DI.IsLittleEndian); 415 writeDWARFOffset(Unit.AbbrOffset, Unit.Format, OS, DI.IsLittleEndian); 416 } else { 417 writeDWARFOffset(Unit.AbbrOffset, Unit.Format, OS, DI.IsLittleEndian); 418 writeInteger((uint8_t)Unit.AddrSize, OS, DI.IsLittleEndian); 419 } 420 421 OS.write(EntryBuffer.data(), EntryBuffer.size()); 422 } 423 424 return Error::success(); 425 } 426 427 static void emitFileEntry(raw_ostream &OS, const DWARFYAML::File &File) { 428 OS.write(File.Name.data(), File.Name.size()); 429 OS.write('\0'); 430 encodeULEB128(File.DirIdx, OS); 431 encodeULEB128(File.ModTime, OS); 432 encodeULEB128(File.Length, OS); 433 } 434 435 Error DWARFYAML::emitDebugLine(raw_ostream &OS, const DWARFYAML::Data &DI) { 436 for (const auto &LineTable : DI.DebugLines) { 437 writeInitialLength(LineTable.Format, LineTable.Length, OS, 438 DI.IsLittleEndian); 439 uint64_t SizeOfPrologueLength = LineTable.Format == dwarf::DWARF64 ? 8 : 4; 440 writeInteger((uint16_t)LineTable.Version, OS, DI.IsLittleEndian); 441 cantFail(writeVariableSizedInteger( 442 LineTable.PrologueLength, SizeOfPrologueLength, OS, DI.IsLittleEndian)); 443 writeInteger((uint8_t)LineTable.MinInstLength, OS, DI.IsLittleEndian); 444 if (LineTable.Version >= 4) 445 writeInteger((uint8_t)LineTable.MaxOpsPerInst, OS, DI.IsLittleEndian); 446 writeInteger((uint8_t)LineTable.DefaultIsStmt, OS, DI.IsLittleEndian); 447 writeInteger((uint8_t)LineTable.LineBase, OS, DI.IsLittleEndian); 448 writeInteger((uint8_t)LineTable.LineRange, OS, DI.IsLittleEndian); 449 writeInteger((uint8_t)LineTable.OpcodeBase, OS, DI.IsLittleEndian); 450 451 for (auto OpcodeLength : LineTable.StandardOpcodeLengths) 452 writeInteger((uint8_t)OpcodeLength, OS, DI.IsLittleEndian); 453 454 for (auto IncludeDir : LineTable.IncludeDirs) { 455 OS.write(IncludeDir.data(), IncludeDir.size()); 456 OS.write('\0'); 457 } 458 OS.write('\0'); 459 460 for (auto File : LineTable.Files) 461 emitFileEntry(OS, File); 462 OS.write('\0'); 463 464 for (auto Op : LineTable.Opcodes) { 465 writeInteger((uint8_t)Op.Opcode, OS, DI.IsLittleEndian); 466 if (Op.Opcode == 0) { 467 encodeULEB128(Op.ExtLen, OS); 468 writeInteger((uint8_t)Op.SubOpcode, OS, DI.IsLittleEndian); 469 switch (Op.SubOpcode) { 470 case dwarf::DW_LNE_set_address: 471 case dwarf::DW_LNE_set_discriminator: 472 // TODO: Test this error. 473 if (Error Err = writeVariableSizedInteger( 474 Op.Data, DI.CompileUnits[0].AddrSize, OS, DI.IsLittleEndian)) 475 return Err; 476 break; 477 case dwarf::DW_LNE_define_file: 478 emitFileEntry(OS, Op.FileEntry); 479 break; 480 case dwarf::DW_LNE_end_sequence: 481 break; 482 default: 483 for (auto OpByte : Op.UnknownOpcodeData) 484 writeInteger((uint8_t)OpByte, OS, DI.IsLittleEndian); 485 } 486 } else if (Op.Opcode < LineTable.OpcodeBase) { 487 switch (Op.Opcode) { 488 case dwarf::DW_LNS_copy: 489 case dwarf::DW_LNS_negate_stmt: 490 case dwarf::DW_LNS_set_basic_block: 491 case dwarf::DW_LNS_const_add_pc: 492 case dwarf::DW_LNS_set_prologue_end: 493 case dwarf::DW_LNS_set_epilogue_begin: 494 break; 495 496 case dwarf::DW_LNS_advance_pc: 497 case dwarf::DW_LNS_set_file: 498 case dwarf::DW_LNS_set_column: 499 case dwarf::DW_LNS_set_isa: 500 encodeULEB128(Op.Data, OS); 501 break; 502 503 case dwarf::DW_LNS_advance_line: 504 encodeSLEB128(Op.SData, OS); 505 break; 506 507 case dwarf::DW_LNS_fixed_advance_pc: 508 writeInteger((uint16_t)Op.Data, OS, DI.IsLittleEndian); 509 break; 510 511 default: 512 for (auto OpData : Op.StandardOpcodeData) { 513 encodeULEB128(OpData, OS); 514 } 515 } 516 } 517 } 518 } 519 520 return Error::success(); 521 } 522 523 Error DWARFYAML::emitDebugAddr(raw_ostream &OS, const Data &DI) { 524 for (const AddrTableEntry &TableEntry : DI.DebugAddr) { 525 uint8_t AddrSize; 526 if (TableEntry.AddrSize) 527 AddrSize = *TableEntry.AddrSize; 528 else 529 AddrSize = DI.Is64BitAddrSize ? 8 : 4; 530 531 uint64_t Length; 532 if (TableEntry.Length) 533 Length = (uint64_t)*TableEntry.Length; 534 else 535 // 2 (version) + 1 (address_size) + 1 (segment_selector_size) = 4 536 Length = 4 + (AddrSize + TableEntry.SegSelectorSize) * 537 TableEntry.SegAddrPairs.size(); 538 539 writeInitialLength(TableEntry.Format, Length, OS, DI.IsLittleEndian); 540 writeInteger((uint16_t)TableEntry.Version, OS, DI.IsLittleEndian); 541 writeInteger((uint8_t)AddrSize, OS, DI.IsLittleEndian); 542 writeInteger((uint8_t)TableEntry.SegSelectorSize, OS, DI.IsLittleEndian); 543 544 for (const SegAddrPair &Pair : TableEntry.SegAddrPairs) { 545 if (TableEntry.SegSelectorSize != 0) 546 if (Error Err = writeVariableSizedInteger(Pair.Segment, 547 TableEntry.SegSelectorSize, 548 OS, DI.IsLittleEndian)) 549 return createStringError(errc::not_supported, 550 "unable to write debug_addr segment: %s", 551 toString(std::move(Err)).c_str()); 552 if (AddrSize != 0) 553 if (Error Err = writeVariableSizedInteger(Pair.Address, AddrSize, OS, 554 DI.IsLittleEndian)) 555 return createStringError(errc::not_supported, 556 "unable to write debug_addr address: %s", 557 toString(std::move(Err)).c_str()); 558 } 559 } 560 561 return Error::success(); 562 } 563 564 Error DWARFYAML::emitDebugStrOffsets(raw_ostream &OS, const Data &DI) { 565 assert(DI.DebugStrOffsets && "unexpected emitDebugStrOffsets() call"); 566 for (const DWARFYAML::StringOffsetsTable &Table : *DI.DebugStrOffsets) { 567 uint64_t Length; 568 if (Table.Length) 569 Length = *Table.Length; 570 else 571 // sizeof(version) + sizeof(padding) = 4 572 Length = 573 4 + Table.Offsets.size() * (Table.Format == dwarf::DWARF64 ? 8 : 4); 574 575 writeInitialLength(Table.Format, Length, OS, DI.IsLittleEndian); 576 writeInteger((uint16_t)Table.Version, OS, DI.IsLittleEndian); 577 writeInteger((uint16_t)Table.Padding, OS, DI.IsLittleEndian); 578 579 for (uint64_t Offset : Table.Offsets) 580 writeDWARFOffset(Offset, Table.Format, OS, DI.IsLittleEndian); 581 } 582 583 return Error::success(); 584 } 585 586 static Error checkOperandCount(StringRef EncodingString, 587 ArrayRef<yaml::Hex64> Values, 588 uint64_t ExpectedOperands) { 589 if (Values.size() != ExpectedOperands) 590 return createStringError( 591 errc::invalid_argument, 592 "invalid number (%zu) of operands for the operator: %s, %" PRIu64 593 " expected", 594 Values.size(), EncodingString.str().c_str(), ExpectedOperands); 595 596 return Error::success(); 597 } 598 599 static Error writeListEntryAddress(StringRef EncodingName, raw_ostream &OS, 600 uint64_t Addr, uint8_t AddrSize, 601 bool IsLittleEndian) { 602 if (Error Err = writeVariableSizedInteger(Addr, AddrSize, OS, IsLittleEndian)) 603 return createStringError(errc::invalid_argument, 604 "unable to write address for the operator %s: %s", 605 EncodingName.str().c_str(), 606 toString(std::move(Err)).c_str()); 607 608 return Error::success(); 609 } 610 611 static Expected<uint64_t> 612 writeDWARFExpression(raw_ostream &OS, 613 const DWARFYAML::DWARFOperation &Operation, 614 uint8_t AddrSize, bool IsLittleEndian) { 615 auto CheckOperands = [&](uint64_t ExpectedOperands) -> Error { 616 return checkOperandCount(dwarf::OperationEncodingString(Operation.Operator), 617 Operation.Values, ExpectedOperands); 618 }; 619 620 uint64_t ExpressionBegin = OS.tell(); 621 writeInteger((uint8_t)Operation.Operator, OS, IsLittleEndian); 622 switch (Operation.Operator) { 623 case dwarf::DW_OP_consts: 624 if (Error Err = CheckOperands(1)) 625 return std::move(Err); 626 encodeSLEB128(Operation.Values[0], OS); 627 break; 628 case dwarf::DW_OP_stack_value: 629 if (Error Err = CheckOperands(0)) 630 return std::move(Err); 631 break; 632 default: 633 StringRef EncodingStr = dwarf::OperationEncodingString(Operation.Operator); 634 return createStringError(errc::not_supported, 635 "DWARF expression: " + 636 (EncodingStr.empty() 637 ? "0x" + utohexstr(Operation.Operator) 638 : EncodingStr) + 639 " is not supported"); 640 } 641 return OS.tell() - ExpressionBegin; 642 } 643 644 static Expected<uint64_t> writeListEntry(raw_ostream &OS, 645 const DWARFYAML::RnglistEntry &Entry, 646 uint8_t AddrSize, 647 bool IsLittleEndian) { 648 uint64_t BeginOffset = OS.tell(); 649 writeInteger((uint8_t)Entry.Operator, OS, IsLittleEndian); 650 651 StringRef EncodingName = dwarf::RangeListEncodingString(Entry.Operator); 652 653 auto CheckOperands = [&](uint64_t ExpectedOperands) -> Error { 654 return checkOperandCount(EncodingName, Entry.Values, ExpectedOperands); 655 }; 656 657 auto WriteAddress = [&](uint64_t Addr) -> Error { 658 return writeListEntryAddress(EncodingName, OS, Addr, AddrSize, 659 IsLittleEndian); 660 }; 661 662 switch (Entry.Operator) { 663 case dwarf::DW_RLE_end_of_list: 664 if (Error Err = CheckOperands(0)) 665 return std::move(Err); 666 break; 667 case dwarf::DW_RLE_base_addressx: 668 if (Error Err = CheckOperands(1)) 669 return std::move(Err); 670 encodeULEB128(Entry.Values[0], OS); 671 break; 672 case dwarf::DW_RLE_startx_endx: 673 case dwarf::DW_RLE_startx_length: 674 case dwarf::DW_RLE_offset_pair: 675 if (Error Err = CheckOperands(2)) 676 return std::move(Err); 677 encodeULEB128(Entry.Values[0], OS); 678 encodeULEB128(Entry.Values[1], OS); 679 break; 680 case dwarf::DW_RLE_base_address: 681 if (Error Err = CheckOperands(1)) 682 return std::move(Err); 683 if (Error Err = WriteAddress(Entry.Values[0])) 684 return std::move(Err); 685 break; 686 case dwarf::DW_RLE_start_end: 687 if (Error Err = CheckOperands(2)) 688 return std::move(Err); 689 if (Error Err = WriteAddress(Entry.Values[0])) 690 return std::move(Err); 691 cantFail(WriteAddress(Entry.Values[1])); 692 break; 693 case dwarf::DW_RLE_start_length: 694 if (Error Err = CheckOperands(2)) 695 return std::move(Err); 696 if (Error Err = WriteAddress(Entry.Values[0])) 697 return std::move(Err); 698 encodeULEB128(Entry.Values[1], OS); 699 break; 700 } 701 702 return OS.tell() - BeginOffset; 703 } 704 705 static Expected<uint64_t> writeListEntry(raw_ostream &OS, 706 const DWARFYAML::LoclistEntry &Entry, 707 uint8_t AddrSize, 708 bool IsLittleEndian) { 709 uint64_t BeginOffset = OS.tell(); 710 writeInteger((uint8_t)Entry.Operator, OS, IsLittleEndian); 711 712 StringRef EncodingName = dwarf::LocListEncodingString(Entry.Operator); 713 714 auto CheckOperands = [&](uint64_t ExpectedOperands) -> Error { 715 return checkOperandCount(EncodingName, Entry.Values, ExpectedOperands); 716 }; 717 718 auto WriteAddress = [&](uint64_t Addr) -> Error { 719 return writeListEntryAddress(EncodingName, OS, Addr, AddrSize, 720 IsLittleEndian); 721 }; 722 723 auto WriteDWARFOperations = [&]() -> Error { 724 std::string OpBuffer; 725 raw_string_ostream OpBufferOS(OpBuffer); 726 uint64_t DescriptionsLength = 0; 727 728 for (const DWARFYAML::DWARFOperation &Op : Entry.Descriptions) { 729 if (Expected<uint64_t> OpSize = 730 writeDWARFExpression(OpBufferOS, Op, AddrSize, IsLittleEndian)) 731 DescriptionsLength += *OpSize; 732 else 733 return OpSize.takeError(); 734 } 735 736 if (Entry.DescriptionsLength) 737 DescriptionsLength = *Entry.DescriptionsLength; 738 else 739 DescriptionsLength = OpBuffer.size(); 740 741 encodeULEB128(DescriptionsLength, OS); 742 OS.write(OpBuffer.data(), OpBuffer.size()); 743 744 return Error::success(); 745 }; 746 747 switch (Entry.Operator) { 748 case dwarf::DW_LLE_end_of_list: 749 if (Error Err = CheckOperands(0)) 750 return std::move(Err); 751 break; 752 case dwarf::DW_LLE_base_addressx: 753 if (Error Err = CheckOperands(1)) 754 return std::move(Err); 755 encodeULEB128(Entry.Values[0], OS); 756 break; 757 case dwarf::DW_LLE_startx_endx: 758 case dwarf::DW_LLE_startx_length: 759 case dwarf::DW_LLE_offset_pair: 760 if (Error Err = CheckOperands(2)) 761 return std::move(Err); 762 encodeULEB128(Entry.Values[0], OS); 763 encodeULEB128(Entry.Values[1], OS); 764 if (Error Err = WriteDWARFOperations()) 765 return std::move(Err); 766 break; 767 case dwarf::DW_LLE_default_location: 768 if (Error Err = CheckOperands(0)) 769 return std::move(Err); 770 if (Error Err = WriteDWARFOperations()) 771 return std::move(Err); 772 break; 773 case dwarf::DW_LLE_base_address: 774 if (Error Err = CheckOperands(1)) 775 return std::move(Err); 776 if (Error Err = WriteAddress(Entry.Values[0])) 777 return std::move(Err); 778 break; 779 case dwarf::DW_LLE_start_end: 780 if (Error Err = CheckOperands(2)) 781 return std::move(Err); 782 if (Error Err = WriteAddress(Entry.Values[0])) 783 return std::move(Err); 784 cantFail(WriteAddress(Entry.Values[1])); 785 if (Error Err = WriteDWARFOperations()) 786 return std::move(Err); 787 break; 788 case dwarf::DW_LLE_start_length: 789 if (Error Err = CheckOperands(2)) 790 return std::move(Err); 791 if (Error Err = WriteAddress(Entry.Values[0])) 792 return std::move(Err); 793 encodeULEB128(Entry.Values[1], OS); 794 if (Error Err = WriteDWARFOperations()) 795 return std::move(Err); 796 break; 797 } 798 799 return OS.tell() - BeginOffset; 800 } 801 802 template <typename EntryType> 803 Error writeDWARFLists(raw_ostream &OS, 804 ArrayRef<DWARFYAML::ListTable<EntryType>> Tables, 805 bool IsLittleEndian, bool Is64BitAddrSize) { 806 for (const DWARFYAML::ListTable<EntryType> &Table : Tables) { 807 // sizeof(version) + sizeof(address_size) + sizeof(segment_selector_size) + 808 // sizeof(offset_entry_count) = 8 809 uint64_t Length = 8; 810 811 uint8_t AddrSize; 812 if (Table.AddrSize) 813 AddrSize = *Table.AddrSize; 814 else 815 AddrSize = Is64BitAddrSize ? 8 : 4; 816 817 // Since the length of the current range/location lists entry is 818 // undetermined yet, we firstly write the content of the range/location 819 // lists to a buffer to calculate the length and then serialize the buffer 820 // content to the actual output stream. 821 std::string ListBuffer; 822 raw_string_ostream ListBufferOS(ListBuffer); 823 824 // Offsets holds offsets for each range/location list. The i-th element is 825 // the offset from the beginning of the first range/location list to the 826 // location of the i-th range list. 827 std::vector<uint64_t> Offsets; 828 829 for (const DWARFYAML::ListEntries<EntryType> &List : Table.Lists) { 830 Offsets.push_back(ListBufferOS.tell()); 831 if (List.Content) { 832 List.Content->writeAsBinary(ListBufferOS, UINT64_MAX); 833 Length += List.Content->binary_size(); 834 } else if (List.Entries) { 835 for (const EntryType &Entry : *List.Entries) { 836 Expected<uint64_t> EntrySize = 837 writeListEntry(ListBufferOS, Entry, AddrSize, IsLittleEndian); 838 if (!EntrySize) 839 return EntrySize.takeError(); 840 Length += *EntrySize; 841 } 842 } 843 } 844 845 // If the offset_entry_count field isn't specified, yaml2obj will infer it 846 // from the 'Offsets' field in the YAML description. If the 'Offsets' field 847 // isn't specified either, yaml2obj will infer it from the auto-generated 848 // offsets. 849 uint32_t OffsetEntryCount; 850 if (Table.OffsetEntryCount) 851 OffsetEntryCount = *Table.OffsetEntryCount; 852 else 853 OffsetEntryCount = Table.Offsets ? Table.Offsets->size() : Offsets.size(); 854 uint64_t OffsetsSize = 855 OffsetEntryCount * (Table.Format == dwarf::DWARF64 ? 8 : 4); 856 Length += OffsetsSize; 857 858 // If the length is specified in the YAML description, we use it instead of 859 // the actual length. 860 if (Table.Length) 861 Length = *Table.Length; 862 863 writeInitialLength(Table.Format, Length, OS, IsLittleEndian); 864 writeInteger((uint16_t)Table.Version, OS, IsLittleEndian); 865 writeInteger((uint8_t)AddrSize, OS, IsLittleEndian); 866 writeInteger((uint8_t)Table.SegSelectorSize, OS, IsLittleEndian); 867 writeInteger((uint32_t)OffsetEntryCount, OS, IsLittleEndian); 868 869 auto EmitOffsets = [&](ArrayRef<uint64_t> Offsets, uint64_t OffsetsSize) { 870 for (uint64_t Offset : Offsets) 871 writeDWARFOffset(OffsetsSize + Offset, Table.Format, OS, 872 IsLittleEndian); 873 }; 874 875 if (Table.Offsets) 876 EmitOffsets(ArrayRef<uint64_t>((const uint64_t *)Table.Offsets->data(), 877 Table.Offsets->size()), 878 0); 879 else if (OffsetEntryCount != 0) 880 EmitOffsets(Offsets, OffsetsSize); 881 882 OS.write(ListBuffer.data(), ListBuffer.size()); 883 } 884 885 return Error::success(); 886 } 887 888 Error DWARFYAML::emitDebugRnglists(raw_ostream &OS, const Data &DI) { 889 assert(DI.DebugRnglists && "unexpected emitDebugRnglists() call"); 890 return writeDWARFLists<DWARFYAML::RnglistEntry>( 891 OS, *DI.DebugRnglists, DI.IsLittleEndian, DI.Is64BitAddrSize); 892 } 893 894 Error DWARFYAML::emitDebugLoclists(raw_ostream &OS, const Data &DI) { 895 assert(DI.DebugLoclists && "unexpected emitDebugRnglists() call"); 896 return writeDWARFLists<DWARFYAML::LoclistEntry>( 897 OS, *DI.DebugLoclists, DI.IsLittleEndian, DI.Is64BitAddrSize); 898 } 899 900 std::function<Error(raw_ostream &, const DWARFYAML::Data &)> 901 DWARFYAML::getDWARFEmitterByName(StringRef SecName) { 902 auto EmitFunc = 903 StringSwitch< 904 std::function<Error(raw_ostream &, const DWARFYAML::Data &)>>(SecName) 905 .Case("debug_abbrev", DWARFYAML::emitDebugAbbrev) 906 .Case("debug_addr", DWARFYAML::emitDebugAddr) 907 .Case("debug_aranges", DWARFYAML::emitDebugAranges) 908 .Case("debug_gnu_pubnames", DWARFYAML::emitDebugGNUPubnames) 909 .Case("debug_gnu_pubtypes", DWARFYAML::emitDebugGNUPubtypes) 910 .Case("debug_info", DWARFYAML::emitDebugInfo) 911 .Case("debug_line", DWARFYAML::emitDebugLine) 912 .Case("debug_loclists", DWARFYAML::emitDebugLoclists) 913 .Case("debug_pubnames", DWARFYAML::emitDebugPubnames) 914 .Case("debug_pubtypes", DWARFYAML::emitDebugPubtypes) 915 .Case("debug_ranges", DWARFYAML::emitDebugRanges) 916 .Case("debug_rnglists", DWARFYAML::emitDebugRnglists) 917 .Case("debug_str", DWARFYAML::emitDebugStr) 918 .Case("debug_str_offsets", DWARFYAML::emitDebugStrOffsets) 919 .Default([&](raw_ostream &, const DWARFYAML::Data &) { 920 return createStringError(errc::not_supported, 921 SecName + " is not supported"); 922 }); 923 924 return EmitFunc; 925 } 926 927 static Error 928 emitDebugSectionImpl(const DWARFYAML::Data &DI, StringRef Sec, 929 StringMap<std::unique_ptr<MemoryBuffer>> &OutputBuffers) { 930 std::string Data; 931 raw_string_ostream DebugInfoStream(Data); 932 933 auto EmitFunc = DWARFYAML::getDWARFEmitterByName(Sec); 934 935 if (Error Err = EmitFunc(DebugInfoStream, DI)) 936 return Err; 937 DebugInfoStream.flush(); 938 if (!Data.empty()) 939 OutputBuffers[Sec] = MemoryBuffer::getMemBufferCopy(Data); 940 941 return Error::success(); 942 } 943 944 Expected<StringMap<std::unique_ptr<MemoryBuffer>>> 945 DWARFYAML::emitDebugSections(StringRef YAMLString, bool IsLittleEndian, 946 bool Is64BitAddrSize) { 947 auto CollectDiagnostic = [](const SMDiagnostic &Diag, void *DiagContext) { 948 *static_cast<SMDiagnostic *>(DiagContext) = Diag; 949 }; 950 951 SMDiagnostic GeneratedDiag; 952 yaml::Input YIn(YAMLString, /*Ctxt=*/nullptr, CollectDiagnostic, 953 &GeneratedDiag); 954 955 DWARFYAML::Data DI; 956 DI.IsLittleEndian = IsLittleEndian; 957 DI.Is64BitAddrSize = Is64BitAddrSize; 958 959 YIn >> DI; 960 if (YIn.error()) 961 return createStringError(YIn.error(), GeneratedDiag.getMessage()); 962 963 StringMap<std::unique_ptr<MemoryBuffer>> DebugSections; 964 Error Err = Error::success(); 965 cantFail(std::move(Err)); 966 967 for (StringRef SecName : DI.getNonEmptySectionNames()) 968 Err = joinErrors(std::move(Err), 969 emitDebugSectionImpl(DI, SecName, DebugSections)); 970 971 if (Err) 972 return std::move(Err); 973 return std::move(DebugSections); 974 } 975