DWARFDebugFrame.cpp 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251
  1. //===- DWARFDebugFrame.h - Parsing of .debug_frame ------------------------===//
  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 "llvm/DebugInfo/DWARF/DWARFDebugFrame.h"
  9. #include "llvm/ADT/DenseMap.h"
  10. #include "llvm/ADT/Optional.h"
  11. #include "llvm/ADT/StringExtras.h"
  12. #include "llvm/ADT/StringRef.h"
  13. #include "llvm/BinaryFormat/Dwarf.h"
  14. #include "llvm/MC/MCRegisterInfo.h"
  15. #include "llvm/Support/Casting.h"
  16. #include "llvm/Support/Compiler.h"
  17. #include "llvm/Support/DataExtractor.h"
  18. #include "llvm/Support/Errc.h"
  19. #include "llvm/Support/ErrorHandling.h"
  20. #include "llvm/Support/Format.h"
  21. #include "llvm/Support/raw_ostream.h"
  22. #include <algorithm>
  23. #include <cassert>
  24. #include <cinttypes>
  25. #include <cstdint>
  26. using namespace llvm;
  27. using namespace dwarf;
  28. static void printRegister(raw_ostream &OS, const MCRegisterInfo *MRI, bool IsEH,
  29. unsigned RegNum) {
  30. if (MRI) {
  31. if (Optional<unsigned> LLVMRegNum = MRI->getLLVMRegNum(RegNum, IsEH)) {
  32. if (const char *RegName = MRI->getName(*LLVMRegNum)) {
  33. OS << RegName;
  34. return;
  35. }
  36. }
  37. }
  38. OS << "reg" << RegNum;
  39. }
  40. UnwindLocation UnwindLocation::createUnspecified() { return {Unspecified}; }
  41. UnwindLocation UnwindLocation::createUndefined() { return {Undefined}; }
  42. UnwindLocation UnwindLocation::createSame() { return {Same}; }
  43. UnwindLocation UnwindLocation::createIsConstant(int32_t Value) {
  44. return {Constant, InvalidRegisterNumber, Value, None, false};
  45. }
  46. UnwindLocation UnwindLocation::createIsCFAPlusOffset(int32_t Offset) {
  47. return {CFAPlusOffset, InvalidRegisterNumber, Offset, None, false};
  48. }
  49. UnwindLocation UnwindLocation::createAtCFAPlusOffset(int32_t Offset) {
  50. return {CFAPlusOffset, InvalidRegisterNumber, Offset, None, true};
  51. }
  52. UnwindLocation
  53. UnwindLocation::createIsRegisterPlusOffset(uint32_t RegNum, int32_t Offset,
  54. Optional<uint32_t> AddrSpace) {
  55. return {RegPlusOffset, RegNum, Offset, AddrSpace, false};
  56. }
  57. UnwindLocation
  58. UnwindLocation::createAtRegisterPlusOffset(uint32_t RegNum, int32_t Offset,
  59. Optional<uint32_t> AddrSpace) {
  60. return {RegPlusOffset, RegNum, Offset, AddrSpace, true};
  61. }
  62. UnwindLocation UnwindLocation::createIsDWARFExpression(DWARFExpression Expr) {
  63. return {Expr, false};
  64. }
  65. UnwindLocation UnwindLocation::createAtDWARFExpression(DWARFExpression Expr) {
  66. return {Expr, true};
  67. }
  68. void UnwindLocation::dump(raw_ostream &OS, const MCRegisterInfo *MRI,
  69. bool IsEH) const {
  70. if (Dereference)
  71. OS << '[';
  72. switch (Kind) {
  73. case Unspecified:
  74. OS << "unspecified";
  75. break;
  76. case Undefined:
  77. OS << "undefined";
  78. break;
  79. case Same:
  80. OS << "same";
  81. break;
  82. case CFAPlusOffset:
  83. OS << "CFA";
  84. if (Offset == 0)
  85. break;
  86. if (Offset > 0)
  87. OS << "+";
  88. OS << Offset;
  89. break;
  90. case RegPlusOffset:
  91. printRegister(OS, MRI, IsEH, RegNum);
  92. if (Offset == 0 && !AddrSpace)
  93. break;
  94. if (Offset >= 0)
  95. OS << "+";
  96. OS << Offset;
  97. if (AddrSpace)
  98. OS << " in addrspace" << *AddrSpace;
  99. break;
  100. case DWARFExpr:
  101. Expr->print(OS, DIDumpOptions(), MRI, nullptr, IsEH);
  102. break;
  103. case Constant:
  104. OS << Offset;
  105. break;
  106. }
  107. if (Dereference)
  108. OS << ']';
  109. }
  110. raw_ostream &llvm::dwarf::operator<<(raw_ostream &OS,
  111. const UnwindLocation &UL) {
  112. UL.dump(OS, nullptr, false);
  113. return OS;
  114. }
  115. bool UnwindLocation::operator==(const UnwindLocation &RHS) const {
  116. if (Kind != RHS.Kind)
  117. return false;
  118. switch (Kind) {
  119. case Unspecified:
  120. case Undefined:
  121. case Same:
  122. return true;
  123. case CFAPlusOffset:
  124. return Offset == RHS.Offset && Dereference == RHS.Dereference;
  125. case RegPlusOffset:
  126. return RegNum == RHS.RegNum && Offset == RHS.Offset &&
  127. Dereference == RHS.Dereference;
  128. case DWARFExpr:
  129. return *Expr == *RHS.Expr && Dereference == RHS.Dereference;
  130. case Constant:
  131. return Offset == RHS.Offset;
  132. }
  133. return false;
  134. }
  135. void RegisterLocations::dump(raw_ostream &OS, const MCRegisterInfo *MRI,
  136. bool IsEH) const {
  137. bool First = true;
  138. for (const auto &RegLocPair : Locations) {
  139. if (First)
  140. First = false;
  141. else
  142. OS << ", ";
  143. printRegister(OS, MRI, IsEH, RegLocPair.first);
  144. OS << '=';
  145. RegLocPair.second.dump(OS, MRI, IsEH);
  146. }
  147. }
  148. raw_ostream &llvm::dwarf::operator<<(raw_ostream &OS,
  149. const RegisterLocations &RL) {
  150. RL.dump(OS, nullptr, false);
  151. return OS;
  152. }
  153. void UnwindRow::dump(raw_ostream &OS, const MCRegisterInfo *MRI, bool IsEH,
  154. unsigned IndentLevel) const {
  155. OS.indent(2 * IndentLevel);
  156. if (hasAddress())
  157. OS << format("0x%" PRIx64 ": ", *Address);
  158. OS << "CFA=";
  159. CFAValue.dump(OS, MRI, IsEH);
  160. if (RegLocs.hasLocations()) {
  161. OS << ": ";
  162. RegLocs.dump(OS, MRI, IsEH);
  163. }
  164. OS << "\n";
  165. }
  166. raw_ostream &llvm::dwarf::operator<<(raw_ostream &OS, const UnwindRow &Row) {
  167. Row.dump(OS, nullptr, false, 0);
  168. return OS;
  169. }
  170. void UnwindTable::dump(raw_ostream &OS, const MCRegisterInfo *MRI, bool IsEH,
  171. unsigned IndentLevel) const {
  172. for (const UnwindRow &Row : Rows)
  173. Row.dump(OS, MRI, IsEH, IndentLevel);
  174. }
  175. raw_ostream &llvm::dwarf::operator<<(raw_ostream &OS, const UnwindTable &Rows) {
  176. Rows.dump(OS, nullptr, false, 0);
  177. return OS;
  178. }
  179. Expected<UnwindTable> UnwindTable::create(const FDE *Fde) {
  180. const CIE *Cie = Fde->getLinkedCIE();
  181. if (Cie == nullptr)
  182. return createStringError(errc::invalid_argument,
  183. "unable to get CIE for FDE at offset 0x%" PRIx64,
  184. Fde->getOffset());
  185. // Rows will be empty if there are no CFI instructions.
  186. if (Cie->cfis().empty() && Fde->cfis().empty())
  187. return UnwindTable();
  188. UnwindTable UT;
  189. UnwindRow Row;
  190. Row.setAddress(Fde->getInitialLocation());
  191. UT.EndAddress = Fde->getInitialLocation() + Fde->getAddressRange();
  192. if (Error CieError = UT.parseRows(Cie->cfis(), Row, nullptr))
  193. return std::move(CieError);
  194. // We need to save the initial locations of registers from the CIE parsing
  195. // in case we run into DW_CFA_restore or DW_CFA_restore_extended opcodes.
  196. const RegisterLocations InitialLocs = Row.getRegisterLocations();
  197. if (Error FdeError = UT.parseRows(Fde->cfis(), Row, &InitialLocs))
  198. return std::move(FdeError);
  199. // May be all the CFI instructions were DW_CFA_nop amd Row becomes empty.
  200. // Do not add that to the unwind table.
  201. if (Row.getRegisterLocations().hasLocations() ||
  202. Row.getCFAValue().getLocation() != UnwindLocation::Unspecified)
  203. UT.Rows.push_back(Row);
  204. return UT;
  205. }
  206. Expected<UnwindTable> UnwindTable::create(const CIE *Cie) {
  207. // Rows will be empty if there are no CFI instructions.
  208. if (Cie->cfis().empty())
  209. return UnwindTable();
  210. UnwindTable UT;
  211. UnwindRow Row;
  212. if (Error CieError = UT.parseRows(Cie->cfis(), Row, nullptr))
  213. return std::move(CieError);
  214. // May be all the CFI instructions were DW_CFA_nop amd Row becomes empty.
  215. // Do not add that to the unwind table.
  216. if (Row.getRegisterLocations().hasLocations() ||
  217. Row.getCFAValue().getLocation() != UnwindLocation::Unspecified)
  218. UT.Rows.push_back(Row);
  219. return UT;
  220. }
  221. // See DWARF standard v3, section 7.23
  222. const uint8_t DWARF_CFI_PRIMARY_OPCODE_MASK = 0xc0;
  223. const uint8_t DWARF_CFI_PRIMARY_OPERAND_MASK = 0x3f;
  224. Error CFIProgram::parse(DWARFDataExtractor Data, uint64_t *Offset,
  225. uint64_t EndOffset) {
  226. DataExtractor::Cursor C(*Offset);
  227. while (C && C.tell() < EndOffset) {
  228. uint8_t Opcode = Data.getRelocatedValue(C, 1);
  229. if (!C)
  230. break;
  231. // Some instructions have a primary opcode encoded in the top bits.
  232. if (uint8_t Primary = Opcode & DWARF_CFI_PRIMARY_OPCODE_MASK) {
  233. // If it's a primary opcode, the first operand is encoded in the bottom
  234. // bits of the opcode itself.
  235. uint64_t Op1 = Opcode & DWARF_CFI_PRIMARY_OPERAND_MASK;
  236. switch (Primary) {
  237. case DW_CFA_advance_loc:
  238. case DW_CFA_restore:
  239. addInstruction(Primary, Op1);
  240. break;
  241. case DW_CFA_offset:
  242. addInstruction(Primary, Op1, Data.getULEB128(C));
  243. break;
  244. default:
  245. llvm_unreachable("invalid primary CFI opcode");
  246. }
  247. continue;
  248. }
  249. // Extended opcode - its value is Opcode itself.
  250. switch (Opcode) {
  251. default:
  252. return createStringError(errc::illegal_byte_sequence,
  253. "invalid extended CFI opcode 0x%" PRIx8, Opcode);
  254. case DW_CFA_nop:
  255. case DW_CFA_remember_state:
  256. case DW_CFA_restore_state:
  257. case DW_CFA_GNU_window_save:
  258. // No operands
  259. addInstruction(Opcode);
  260. break;
  261. case DW_CFA_set_loc:
  262. // Operands: Address
  263. addInstruction(Opcode, Data.getRelocatedAddress(C));
  264. break;
  265. case DW_CFA_advance_loc1:
  266. // Operands: 1-byte delta
  267. addInstruction(Opcode, Data.getRelocatedValue(C, 1));
  268. break;
  269. case DW_CFA_advance_loc2:
  270. // Operands: 2-byte delta
  271. addInstruction(Opcode, Data.getRelocatedValue(C, 2));
  272. break;
  273. case DW_CFA_advance_loc4:
  274. // Operands: 4-byte delta
  275. addInstruction(Opcode, Data.getRelocatedValue(C, 4));
  276. break;
  277. case DW_CFA_restore_extended:
  278. case DW_CFA_undefined:
  279. case DW_CFA_same_value:
  280. case DW_CFA_def_cfa_register:
  281. case DW_CFA_def_cfa_offset:
  282. case DW_CFA_GNU_args_size:
  283. // Operands: ULEB128
  284. addInstruction(Opcode, Data.getULEB128(C));
  285. break;
  286. case DW_CFA_def_cfa_offset_sf:
  287. // Operands: SLEB128
  288. addInstruction(Opcode, Data.getSLEB128(C));
  289. break;
  290. case DW_CFA_LLVM_def_aspace_cfa:
  291. case DW_CFA_LLVM_def_aspace_cfa_sf: {
  292. auto RegNum = Data.getULEB128(C);
  293. auto CfaOffset = Opcode == DW_CFA_LLVM_def_aspace_cfa
  294. ? Data.getULEB128(C)
  295. : Data.getSLEB128(C);
  296. auto AddressSpace = Data.getULEB128(C);
  297. addInstruction(Opcode, RegNum, CfaOffset, AddressSpace);
  298. break;
  299. }
  300. case DW_CFA_offset_extended:
  301. case DW_CFA_register:
  302. case DW_CFA_def_cfa:
  303. case DW_CFA_val_offset: {
  304. // Operands: ULEB128, ULEB128
  305. // Note: We can not embed getULEB128 directly into function
  306. // argument list. getULEB128 changes Offset and order of evaluation
  307. // for arguments is unspecified.
  308. uint64_t op1 = Data.getULEB128(C);
  309. uint64_t op2 = Data.getULEB128(C);
  310. addInstruction(Opcode, op1, op2);
  311. break;
  312. }
  313. case DW_CFA_offset_extended_sf:
  314. case DW_CFA_def_cfa_sf:
  315. case DW_CFA_val_offset_sf: {
  316. // Operands: ULEB128, SLEB128
  317. // Note: see comment for the previous case
  318. uint64_t op1 = Data.getULEB128(C);
  319. uint64_t op2 = (uint64_t)Data.getSLEB128(C);
  320. addInstruction(Opcode, op1, op2);
  321. break;
  322. }
  323. case DW_CFA_def_cfa_expression: {
  324. uint64_t ExprLength = Data.getULEB128(C);
  325. addInstruction(Opcode, 0);
  326. StringRef Expression = Data.getBytes(C, ExprLength);
  327. DataExtractor Extractor(Expression, Data.isLittleEndian(),
  328. Data.getAddressSize());
  329. // Note. We do not pass the DWARF format to DWARFExpression, because
  330. // DW_OP_call_ref, the only operation which depends on the format, is
  331. // prohibited in call frame instructions, see sec. 6.4.2 in DWARFv5.
  332. Instructions.back().Expression =
  333. DWARFExpression(Extractor, Data.getAddressSize());
  334. break;
  335. }
  336. case DW_CFA_expression:
  337. case DW_CFA_val_expression: {
  338. uint64_t RegNum = Data.getULEB128(C);
  339. addInstruction(Opcode, RegNum, 0);
  340. uint64_t BlockLength = Data.getULEB128(C);
  341. StringRef Expression = Data.getBytes(C, BlockLength);
  342. DataExtractor Extractor(Expression, Data.isLittleEndian(),
  343. Data.getAddressSize());
  344. // Note. We do not pass the DWARF format to DWARFExpression, because
  345. // DW_OP_call_ref, the only operation which depends on the format, is
  346. // prohibited in call frame instructions, see sec. 6.4.2 in DWARFv5.
  347. Instructions.back().Expression =
  348. DWARFExpression(Extractor, Data.getAddressSize());
  349. break;
  350. }
  351. }
  352. }
  353. *Offset = C.tell();
  354. return C.takeError();
  355. }
  356. StringRef CFIProgram::callFrameString(unsigned Opcode) const {
  357. return dwarf::CallFrameString(Opcode, Arch);
  358. }
  359. const char *CFIProgram::operandTypeString(CFIProgram::OperandType OT) {
  360. #define ENUM_TO_CSTR(e) \
  361. case e: \
  362. return #e;
  363. switch (OT) {
  364. ENUM_TO_CSTR(OT_Unset);
  365. ENUM_TO_CSTR(OT_None);
  366. ENUM_TO_CSTR(OT_Address);
  367. ENUM_TO_CSTR(OT_Offset);
  368. ENUM_TO_CSTR(OT_FactoredCodeOffset);
  369. ENUM_TO_CSTR(OT_SignedFactDataOffset);
  370. ENUM_TO_CSTR(OT_UnsignedFactDataOffset);
  371. ENUM_TO_CSTR(OT_Register);
  372. ENUM_TO_CSTR(OT_AddressSpace);
  373. ENUM_TO_CSTR(OT_Expression);
  374. }
  375. return "<unknown CFIProgram::OperandType>";
  376. }
  377. llvm::Expected<uint64_t>
  378. CFIProgram::Instruction::getOperandAsUnsigned(const CFIProgram &CFIP,
  379. uint32_t OperandIdx) const {
  380. if (OperandIdx >= MaxOperands)
  381. return createStringError(errc::invalid_argument,
  382. "operand index %" PRIu32 " is not valid",
  383. OperandIdx);
  384. OperandType Type = CFIP.getOperandTypes()[Opcode][OperandIdx];
  385. uint64_t Operand = Ops[OperandIdx];
  386. switch (Type) {
  387. case OT_Unset:
  388. case OT_None:
  389. case OT_Expression:
  390. return createStringError(errc::invalid_argument,
  391. "op[%" PRIu32 "] has type %s which has no value",
  392. OperandIdx, CFIProgram::operandTypeString(Type));
  393. case OT_Offset:
  394. case OT_SignedFactDataOffset:
  395. case OT_UnsignedFactDataOffset:
  396. return createStringError(
  397. errc::invalid_argument,
  398. "op[%" PRIu32 "] has OperandType OT_Offset which produces a signed "
  399. "result, call getOperandAsSigned instead",
  400. OperandIdx);
  401. case OT_Address:
  402. case OT_Register:
  403. case OT_AddressSpace:
  404. return Operand;
  405. case OT_FactoredCodeOffset: {
  406. const uint64_t CodeAlignmentFactor = CFIP.codeAlign();
  407. if (CodeAlignmentFactor == 0)
  408. return createStringError(
  409. errc::invalid_argument,
  410. "op[%" PRIu32 "] has type OT_FactoredCodeOffset but code alignment "
  411. "is zero",
  412. OperandIdx);
  413. return Operand * CodeAlignmentFactor;
  414. }
  415. }
  416. llvm_unreachable("invalid operand type");
  417. }
  418. llvm::Expected<int64_t>
  419. CFIProgram::Instruction::getOperandAsSigned(const CFIProgram &CFIP,
  420. uint32_t OperandIdx) const {
  421. if (OperandIdx >= MaxOperands)
  422. return createStringError(errc::invalid_argument,
  423. "operand index %" PRIu32 " is not valid",
  424. OperandIdx);
  425. OperandType Type = CFIP.getOperandTypes()[Opcode][OperandIdx];
  426. uint64_t Operand = Ops[OperandIdx];
  427. switch (Type) {
  428. case OT_Unset:
  429. case OT_None:
  430. case OT_Expression:
  431. return createStringError(errc::invalid_argument,
  432. "op[%" PRIu32 "] has type %s which has no value",
  433. OperandIdx, CFIProgram::operandTypeString(Type));
  434. case OT_Address:
  435. case OT_Register:
  436. case OT_AddressSpace:
  437. return createStringError(
  438. errc::invalid_argument,
  439. "op[%" PRIu32 "] has OperandType %s which produces an unsigned result, "
  440. "call getOperandAsUnsigned instead",
  441. OperandIdx, CFIProgram::operandTypeString(Type));
  442. case OT_Offset:
  443. return (int64_t)Operand;
  444. case OT_FactoredCodeOffset:
  445. case OT_SignedFactDataOffset: {
  446. const int64_t DataAlignmentFactor = CFIP.dataAlign();
  447. if (DataAlignmentFactor == 0)
  448. return createStringError(errc::invalid_argument,
  449. "op[%" PRIu32 "] has type %s but data "
  450. "alignment is zero",
  451. OperandIdx, CFIProgram::operandTypeString(Type));
  452. return int64_t(Operand) * DataAlignmentFactor;
  453. }
  454. case OT_UnsignedFactDataOffset: {
  455. const int64_t DataAlignmentFactor = CFIP.dataAlign();
  456. if (DataAlignmentFactor == 0)
  457. return createStringError(errc::invalid_argument,
  458. "op[%" PRIu32
  459. "] has type OT_UnsignedFactDataOffset but data "
  460. "alignment is zero",
  461. OperandIdx);
  462. return Operand * DataAlignmentFactor;
  463. }
  464. }
  465. llvm_unreachable("invalid operand type");
  466. }
  467. Error UnwindTable::parseRows(const CFIProgram &CFIP, UnwindRow &Row,
  468. const RegisterLocations *InitialLocs) {
  469. std::vector<RegisterLocations> RegisterStates;
  470. for (const CFIProgram::Instruction &Inst : CFIP) {
  471. switch (Inst.Opcode) {
  472. case dwarf::DW_CFA_set_loc: {
  473. // The DW_CFA_set_loc instruction takes a single operand that
  474. // represents a target address. The required action is to create a new
  475. // table row using the specified address as the location. All other
  476. // values in the new row are initially identical to the current row.
  477. // The new location value is always greater than the current one. If
  478. // the segment_size field of this FDE's CIE is non- zero, the initial
  479. // location is preceded by a segment selector of the given length
  480. llvm::Expected<uint64_t> NewAddress = Inst.getOperandAsUnsigned(CFIP, 0);
  481. if (!NewAddress)
  482. return NewAddress.takeError();
  483. if (*NewAddress <= Row.getAddress())
  484. return createStringError(
  485. errc::invalid_argument,
  486. "%s with adrress 0x%" PRIx64 " which must be greater than the "
  487. "current row address 0x%" PRIx64,
  488. CFIP.callFrameString(Inst.Opcode).str().c_str(), *NewAddress,
  489. Row.getAddress());
  490. Rows.push_back(Row);
  491. Row.setAddress(*NewAddress);
  492. break;
  493. }
  494. case dwarf::DW_CFA_advance_loc:
  495. case dwarf::DW_CFA_advance_loc1:
  496. case dwarf::DW_CFA_advance_loc2:
  497. case dwarf::DW_CFA_advance_loc4: {
  498. // The DW_CFA_advance instruction takes a single operand that
  499. // represents a constant delta. The required action is to create a new
  500. // table row with a location value that is computed by taking the
  501. // current entry’s location value and adding the value of delta *
  502. // code_alignment_factor. All other values in the new row are initially
  503. // identical to the current row.
  504. Rows.push_back(Row);
  505. llvm::Expected<uint64_t> Offset = Inst.getOperandAsUnsigned(CFIP, 0);
  506. if (!Offset)
  507. return Offset.takeError();
  508. Row.slideAddress(*Offset);
  509. break;
  510. }
  511. case dwarf::DW_CFA_restore:
  512. case dwarf::DW_CFA_restore_extended: {
  513. // The DW_CFA_restore instruction takes a single operand (encoded with
  514. // the opcode) that represents a register number. The required action
  515. // is to change the rule for the indicated register to the rule
  516. // assigned it by the initial_instructions in the CIE.
  517. if (InitialLocs == nullptr)
  518. return createStringError(
  519. errc::invalid_argument, "%s encountered while parsing a CIE",
  520. CFIP.callFrameString(Inst.Opcode).str().c_str());
  521. llvm::Expected<uint64_t> RegNum = Inst.getOperandAsUnsigned(CFIP, 0);
  522. if (!RegNum)
  523. return RegNum.takeError();
  524. if (Optional<UnwindLocation> O =
  525. InitialLocs->getRegisterLocation(*RegNum))
  526. Row.getRegisterLocations().setRegisterLocation(*RegNum, *O);
  527. else
  528. Row.getRegisterLocations().removeRegisterLocation(*RegNum);
  529. break;
  530. }
  531. case dwarf::DW_CFA_offset:
  532. case dwarf::DW_CFA_offset_extended:
  533. case dwarf::DW_CFA_offset_extended_sf: {
  534. llvm::Expected<uint64_t> RegNum = Inst.getOperandAsUnsigned(CFIP, 0);
  535. if (!RegNum)
  536. return RegNum.takeError();
  537. llvm::Expected<int64_t> Offset = Inst.getOperandAsSigned(CFIP, 1);
  538. if (!Offset)
  539. return Offset.takeError();
  540. Row.getRegisterLocations().setRegisterLocation(
  541. *RegNum, UnwindLocation::createAtCFAPlusOffset(*Offset));
  542. break;
  543. }
  544. case dwarf::DW_CFA_nop:
  545. break;
  546. case dwarf::DW_CFA_remember_state:
  547. RegisterStates.push_back(Row.getRegisterLocations());
  548. break;
  549. case dwarf::DW_CFA_restore_state:
  550. if (RegisterStates.empty())
  551. return createStringError(errc::invalid_argument,
  552. "DW_CFA_restore_state without a matching "
  553. "previous DW_CFA_remember_state");
  554. Row.getRegisterLocations() = RegisterStates.back();
  555. RegisterStates.pop_back();
  556. break;
  557. case dwarf::DW_CFA_GNU_window_save:
  558. switch (CFIP.triple()) {
  559. case Triple::aarch64:
  560. case Triple::aarch64_be:
  561. case Triple::aarch64_32: {
  562. // DW_CFA_GNU_window_save is used for different things on different
  563. // architectures. For aarch64 it is known as
  564. // DW_CFA_AARCH64_negate_ra_state. The action is to toggle the
  565. // value of the return address state between 1 and 0. If there is
  566. // no rule for the AARCH64_DWARF_PAUTH_RA_STATE register, then it
  567. // should be initially set to 1.
  568. constexpr uint32_t AArch64DWARFPAuthRaState = 34;
  569. auto LRLoc = Row.getRegisterLocations().getRegisterLocation(
  570. AArch64DWARFPAuthRaState);
  571. if (LRLoc) {
  572. if (LRLoc->getLocation() == UnwindLocation::Constant) {
  573. // Toggle the constant value from 0 to 1 or 1 to 0.
  574. LRLoc->setConstant(LRLoc->getConstant() ^ 1);
  575. } else {
  576. return createStringError(
  577. errc::invalid_argument,
  578. "%s encountered when existing rule for this register is not "
  579. "a constant",
  580. CFIP.callFrameString(Inst.Opcode).str().c_str());
  581. }
  582. } else {
  583. Row.getRegisterLocations().setRegisterLocation(
  584. AArch64DWARFPAuthRaState, UnwindLocation::createIsConstant(1));
  585. }
  586. break;
  587. }
  588. case Triple::sparc:
  589. case Triple::sparcv9:
  590. case Triple::sparcel:
  591. for (uint32_t RegNum = 16; RegNum < 32; ++RegNum) {
  592. Row.getRegisterLocations().setRegisterLocation(
  593. RegNum, UnwindLocation::createAtCFAPlusOffset((RegNum - 16) * 8));
  594. }
  595. break;
  596. default: {
  597. return createStringError(
  598. errc::not_supported,
  599. "DW_CFA opcode %#x is not supported for architecture %s",
  600. Inst.Opcode, Triple::getArchTypeName(CFIP.triple()).str().c_str());
  601. break;
  602. }
  603. }
  604. break;
  605. case dwarf::DW_CFA_undefined: {
  606. llvm::Expected<uint64_t> RegNum = Inst.getOperandAsUnsigned(CFIP, 0);
  607. if (!RegNum)
  608. return RegNum.takeError();
  609. Row.getRegisterLocations().setRegisterLocation(
  610. *RegNum, UnwindLocation::createUndefined());
  611. break;
  612. }
  613. case dwarf::DW_CFA_same_value: {
  614. llvm::Expected<uint64_t> RegNum = Inst.getOperandAsUnsigned(CFIP, 0);
  615. if (!RegNum)
  616. return RegNum.takeError();
  617. Row.getRegisterLocations().setRegisterLocation(
  618. *RegNum, UnwindLocation::createSame());
  619. break;
  620. }
  621. case dwarf::DW_CFA_GNU_args_size:
  622. break;
  623. case dwarf::DW_CFA_register: {
  624. llvm::Expected<uint64_t> RegNum = Inst.getOperandAsUnsigned(CFIP, 0);
  625. if (!RegNum)
  626. return RegNum.takeError();
  627. llvm::Expected<uint64_t> NewRegNum = Inst.getOperandAsUnsigned(CFIP, 1);
  628. if (!NewRegNum)
  629. return NewRegNum.takeError();
  630. Row.getRegisterLocations().setRegisterLocation(
  631. *RegNum, UnwindLocation::createIsRegisterPlusOffset(*NewRegNum, 0));
  632. break;
  633. }
  634. case dwarf::DW_CFA_val_offset:
  635. case dwarf::DW_CFA_val_offset_sf: {
  636. llvm::Expected<uint64_t> RegNum = Inst.getOperandAsUnsigned(CFIP, 0);
  637. if (!RegNum)
  638. return RegNum.takeError();
  639. llvm::Expected<int64_t> Offset = Inst.getOperandAsSigned(CFIP, 1);
  640. if (!Offset)
  641. return Offset.takeError();
  642. Row.getRegisterLocations().setRegisterLocation(
  643. *RegNum, UnwindLocation::createIsCFAPlusOffset(*Offset));
  644. break;
  645. }
  646. case dwarf::DW_CFA_expression: {
  647. llvm::Expected<uint64_t> RegNum = Inst.getOperandAsUnsigned(CFIP, 0);
  648. if (!RegNum)
  649. return RegNum.takeError();
  650. Row.getRegisterLocations().setRegisterLocation(
  651. *RegNum, UnwindLocation::createAtDWARFExpression(*Inst.Expression));
  652. break;
  653. }
  654. case dwarf::DW_CFA_val_expression: {
  655. llvm::Expected<uint64_t> RegNum = Inst.getOperandAsUnsigned(CFIP, 0);
  656. if (!RegNum)
  657. return RegNum.takeError();
  658. Row.getRegisterLocations().setRegisterLocation(
  659. *RegNum, UnwindLocation::createIsDWARFExpression(*Inst.Expression));
  660. break;
  661. }
  662. case dwarf::DW_CFA_def_cfa_register: {
  663. llvm::Expected<uint64_t> RegNum = Inst.getOperandAsUnsigned(CFIP, 0);
  664. if (!RegNum)
  665. return RegNum.takeError();
  666. if (Row.getCFAValue().getLocation() != UnwindLocation::RegPlusOffset)
  667. Row.getCFAValue() =
  668. UnwindLocation::createIsRegisterPlusOffset(*RegNum, 0);
  669. else
  670. Row.getCFAValue().setRegister(*RegNum);
  671. break;
  672. }
  673. case dwarf::DW_CFA_def_cfa_offset:
  674. case dwarf::DW_CFA_def_cfa_offset_sf: {
  675. llvm::Expected<int64_t> Offset = Inst.getOperandAsSigned(CFIP, 0);
  676. if (!Offset)
  677. return Offset.takeError();
  678. if (Row.getCFAValue().getLocation() != UnwindLocation::RegPlusOffset) {
  679. return createStringError(
  680. errc::invalid_argument,
  681. "%s found when CFA rule was not RegPlusOffset",
  682. CFIP.callFrameString(Inst.Opcode).str().c_str());
  683. }
  684. Row.getCFAValue().setOffset(*Offset);
  685. break;
  686. }
  687. case dwarf::DW_CFA_def_cfa:
  688. case dwarf::DW_CFA_def_cfa_sf: {
  689. llvm::Expected<uint64_t> RegNum = Inst.getOperandAsUnsigned(CFIP, 0);
  690. if (!RegNum)
  691. return RegNum.takeError();
  692. llvm::Expected<int64_t> Offset = Inst.getOperandAsSigned(CFIP, 1);
  693. if (!Offset)
  694. return Offset.takeError();
  695. Row.getCFAValue() =
  696. UnwindLocation::createIsRegisterPlusOffset(*RegNum, *Offset);
  697. break;
  698. }
  699. case dwarf::DW_CFA_LLVM_def_aspace_cfa:
  700. case dwarf::DW_CFA_LLVM_def_aspace_cfa_sf: {
  701. llvm::Expected<uint64_t> RegNum = Inst.getOperandAsUnsigned(CFIP, 0);
  702. if (!RegNum)
  703. return RegNum.takeError();
  704. llvm::Expected<int64_t> Offset = Inst.getOperandAsSigned(CFIP, 1);
  705. if (!Offset)
  706. return Offset.takeError();
  707. llvm::Expected<uint32_t> CFAAddrSpace =
  708. Inst.getOperandAsUnsigned(CFIP, 2);
  709. if (!CFAAddrSpace)
  710. return CFAAddrSpace.takeError();
  711. Row.getCFAValue() = UnwindLocation::createIsRegisterPlusOffset(
  712. *RegNum, *Offset, *CFAAddrSpace);
  713. break;
  714. }
  715. case dwarf::DW_CFA_def_cfa_expression:
  716. Row.getCFAValue() =
  717. UnwindLocation::createIsDWARFExpression(*Inst.Expression);
  718. break;
  719. }
  720. }
  721. return Error::success();
  722. }
  723. ArrayRef<CFIProgram::OperandType[CFIProgram::MaxOperands]>
  724. CFIProgram::getOperandTypes() {
  725. static OperandType OpTypes[DW_CFA_restore + 1][MaxOperands];
  726. static bool Initialized = false;
  727. if (Initialized) {
  728. return ArrayRef<OperandType[MaxOperands]>(&OpTypes[0], DW_CFA_restore + 1);
  729. }
  730. Initialized = true;
  731. #define DECLARE_OP3(OP, OPTYPE0, OPTYPE1, OPTYPE2) \
  732. do { \
  733. OpTypes[OP][0] = OPTYPE0; \
  734. OpTypes[OP][1] = OPTYPE1; \
  735. OpTypes[OP][2] = OPTYPE2; \
  736. } while (false)
  737. #define DECLARE_OP2(OP, OPTYPE0, OPTYPE1) \
  738. DECLARE_OP3(OP, OPTYPE0, OPTYPE1, OT_None)
  739. #define DECLARE_OP1(OP, OPTYPE0) DECLARE_OP2(OP, OPTYPE0, OT_None)
  740. #define DECLARE_OP0(OP) DECLARE_OP1(OP, OT_None)
  741. DECLARE_OP1(DW_CFA_set_loc, OT_Address);
  742. DECLARE_OP1(DW_CFA_advance_loc, OT_FactoredCodeOffset);
  743. DECLARE_OP1(DW_CFA_advance_loc1, OT_FactoredCodeOffset);
  744. DECLARE_OP1(DW_CFA_advance_loc2, OT_FactoredCodeOffset);
  745. DECLARE_OP1(DW_CFA_advance_loc4, OT_FactoredCodeOffset);
  746. DECLARE_OP1(DW_CFA_MIPS_advance_loc8, OT_FactoredCodeOffset);
  747. DECLARE_OP2(DW_CFA_def_cfa, OT_Register, OT_Offset);
  748. DECLARE_OP2(DW_CFA_def_cfa_sf, OT_Register, OT_SignedFactDataOffset);
  749. DECLARE_OP1(DW_CFA_def_cfa_register, OT_Register);
  750. DECLARE_OP3(DW_CFA_LLVM_def_aspace_cfa, OT_Register, OT_Offset,
  751. OT_AddressSpace);
  752. DECLARE_OP3(DW_CFA_LLVM_def_aspace_cfa_sf, OT_Register,
  753. OT_SignedFactDataOffset, OT_AddressSpace);
  754. DECLARE_OP1(DW_CFA_def_cfa_offset, OT_Offset);
  755. DECLARE_OP1(DW_CFA_def_cfa_offset_sf, OT_SignedFactDataOffset);
  756. DECLARE_OP1(DW_CFA_def_cfa_expression, OT_Expression);
  757. DECLARE_OP1(DW_CFA_undefined, OT_Register);
  758. DECLARE_OP1(DW_CFA_same_value, OT_Register);
  759. DECLARE_OP2(DW_CFA_offset, OT_Register, OT_UnsignedFactDataOffset);
  760. DECLARE_OP2(DW_CFA_offset_extended, OT_Register, OT_UnsignedFactDataOffset);
  761. DECLARE_OP2(DW_CFA_offset_extended_sf, OT_Register, OT_SignedFactDataOffset);
  762. DECLARE_OP2(DW_CFA_val_offset, OT_Register, OT_UnsignedFactDataOffset);
  763. DECLARE_OP2(DW_CFA_val_offset_sf, OT_Register, OT_SignedFactDataOffset);
  764. DECLARE_OP2(DW_CFA_register, OT_Register, OT_Register);
  765. DECLARE_OP2(DW_CFA_expression, OT_Register, OT_Expression);
  766. DECLARE_OP2(DW_CFA_val_expression, OT_Register, OT_Expression);
  767. DECLARE_OP1(DW_CFA_restore, OT_Register);
  768. DECLARE_OP1(DW_CFA_restore_extended, OT_Register);
  769. DECLARE_OP0(DW_CFA_remember_state);
  770. DECLARE_OP0(DW_CFA_restore_state);
  771. DECLARE_OP0(DW_CFA_GNU_window_save);
  772. DECLARE_OP1(DW_CFA_GNU_args_size, OT_Offset);
  773. DECLARE_OP0(DW_CFA_nop);
  774. #undef DECLARE_OP0
  775. #undef DECLARE_OP1
  776. #undef DECLARE_OP2
  777. return ArrayRef<OperandType[MaxOperands]>(&OpTypes[0], DW_CFA_restore + 1);
  778. }
  779. /// Print \p Opcode's operand number \p OperandIdx which has value \p Operand.
  780. void CFIProgram::printOperand(raw_ostream &OS, DIDumpOptions DumpOpts,
  781. const MCRegisterInfo *MRI, bool IsEH,
  782. const Instruction &Instr, unsigned OperandIdx,
  783. uint64_t Operand) const {
  784. assert(OperandIdx < MaxOperands);
  785. uint8_t Opcode = Instr.Opcode;
  786. OperandType Type = getOperandTypes()[Opcode][OperandIdx];
  787. switch (Type) {
  788. case OT_Unset: {
  789. OS << " Unsupported " << (OperandIdx ? "second" : "first") << " operand to";
  790. auto OpcodeName = callFrameString(Opcode);
  791. if (!OpcodeName.empty())
  792. OS << " " << OpcodeName;
  793. else
  794. OS << format(" Opcode %x", Opcode);
  795. break;
  796. }
  797. case OT_None:
  798. break;
  799. case OT_Address:
  800. OS << format(" %" PRIx64, Operand);
  801. break;
  802. case OT_Offset:
  803. // The offsets are all encoded in a unsigned form, but in practice
  804. // consumers use them signed. It's most certainly legacy due to
  805. // the lack of signed variants in the first Dwarf standards.
  806. OS << format(" %+" PRId64, int64_t(Operand));
  807. break;
  808. case OT_FactoredCodeOffset: // Always Unsigned
  809. if (CodeAlignmentFactor)
  810. OS << format(" %" PRId64, Operand * CodeAlignmentFactor);
  811. else
  812. OS << format(" %" PRId64 "*code_alignment_factor" , Operand);
  813. break;
  814. case OT_SignedFactDataOffset:
  815. if (DataAlignmentFactor)
  816. OS << format(" %" PRId64, int64_t(Operand) * DataAlignmentFactor);
  817. else
  818. OS << format(" %" PRId64 "*data_alignment_factor" , int64_t(Operand));
  819. break;
  820. case OT_UnsignedFactDataOffset:
  821. if (DataAlignmentFactor)
  822. OS << format(" %" PRId64, Operand * DataAlignmentFactor);
  823. else
  824. OS << format(" %" PRId64 "*data_alignment_factor" , Operand);
  825. break;
  826. case OT_Register:
  827. OS << ' ';
  828. printRegister(OS, MRI, IsEH, Operand);
  829. break;
  830. case OT_AddressSpace:
  831. OS << format(" in addrspace%" PRId64, Operand);
  832. break;
  833. case OT_Expression:
  834. assert(Instr.Expression && "missing DWARFExpression object");
  835. OS << " ";
  836. Instr.Expression->print(OS, DumpOpts, MRI, nullptr, IsEH);
  837. break;
  838. }
  839. }
  840. void CFIProgram::dump(raw_ostream &OS, DIDumpOptions DumpOpts,
  841. const MCRegisterInfo *MRI, bool IsEH,
  842. unsigned IndentLevel) const {
  843. for (const auto &Instr : Instructions) {
  844. uint8_t Opcode = Instr.Opcode;
  845. OS.indent(2 * IndentLevel);
  846. OS << callFrameString(Opcode) << ":";
  847. for (unsigned i = 0; i < Instr.Ops.size(); ++i)
  848. printOperand(OS, DumpOpts, MRI, IsEH, Instr, i, Instr.Ops[i]);
  849. OS << '\n';
  850. }
  851. }
  852. // Returns the CIE identifier to be used by the requested format.
  853. // CIE ids for .debug_frame sections are defined in Section 7.24 of DWARFv5.
  854. // For CIE ID in .eh_frame sections see
  855. // https://refspecs.linuxfoundation.org/LSB_5.0.0/LSB-Core-generic/LSB-Core-generic/ehframechpt.html
  856. constexpr uint64_t getCIEId(bool IsDWARF64, bool IsEH) {
  857. if (IsEH)
  858. return 0;
  859. if (IsDWARF64)
  860. return DW64_CIE_ID;
  861. return DW_CIE_ID;
  862. }
  863. void CIE::dump(raw_ostream &OS, DIDumpOptions DumpOpts,
  864. const MCRegisterInfo *MRI, bool IsEH) const {
  865. // A CIE with a zero length is a terminator entry in the .eh_frame section.
  866. if (IsEH && Length == 0) {
  867. OS << format("%08" PRIx64, Offset) << " ZERO terminator\n";
  868. return;
  869. }
  870. OS << format("%08" PRIx64, Offset)
  871. << format(" %0*" PRIx64, IsDWARF64 ? 16 : 8, Length)
  872. << format(" %0*" PRIx64, IsDWARF64 && !IsEH ? 16 : 8,
  873. getCIEId(IsDWARF64, IsEH))
  874. << " CIE\n"
  875. << " Format: " << FormatString(IsDWARF64) << "\n";
  876. if (IsEH && Version != 1)
  877. OS << "WARNING: unsupported CIE version\n";
  878. OS << format(" Version: %d\n", Version)
  879. << " Augmentation: \"" << Augmentation << "\"\n";
  880. if (Version >= 4) {
  881. OS << format(" Address size: %u\n", (uint32_t)AddressSize);
  882. OS << format(" Segment desc size: %u\n",
  883. (uint32_t)SegmentDescriptorSize);
  884. }
  885. OS << format(" Code alignment factor: %u\n", (uint32_t)CodeAlignmentFactor);
  886. OS << format(" Data alignment factor: %d\n", (int32_t)DataAlignmentFactor);
  887. OS << format(" Return address column: %d\n", (int32_t)ReturnAddressRegister);
  888. if (Personality)
  889. OS << format(" Personality Address: %016" PRIx64 "\n", *Personality);
  890. if (!AugmentationData.empty()) {
  891. OS << " Augmentation data: ";
  892. for (uint8_t Byte : AugmentationData)
  893. OS << ' ' << hexdigit(Byte >> 4) << hexdigit(Byte & 0xf);
  894. OS << "\n";
  895. }
  896. OS << "\n";
  897. CFIs.dump(OS, DumpOpts, MRI, IsEH);
  898. OS << "\n";
  899. if (Expected<UnwindTable> RowsOrErr = UnwindTable::create(this))
  900. RowsOrErr->dump(OS, MRI, IsEH, 1);
  901. else {
  902. DumpOpts.RecoverableErrorHandler(joinErrors(
  903. createStringError(errc::invalid_argument,
  904. "decoding the CIE opcodes into rows failed"),
  905. RowsOrErr.takeError()));
  906. }
  907. OS << "\n";
  908. }
  909. void FDE::dump(raw_ostream &OS, DIDumpOptions DumpOpts,
  910. const MCRegisterInfo *MRI, bool IsEH) const {
  911. OS << format("%08" PRIx64, Offset)
  912. << format(" %0*" PRIx64, IsDWARF64 ? 16 : 8, Length)
  913. << format(" %0*" PRIx64, IsDWARF64 && !IsEH ? 16 : 8, CIEPointer)
  914. << " FDE cie=";
  915. if (LinkedCIE)
  916. OS << format("%08" PRIx64, LinkedCIE->getOffset());
  917. else
  918. OS << "<invalid offset>";
  919. OS << format(" pc=%08" PRIx64 "...%08" PRIx64 "\n", InitialLocation,
  920. InitialLocation + AddressRange);
  921. OS << " Format: " << FormatString(IsDWARF64) << "\n";
  922. if (LSDAAddress)
  923. OS << format(" LSDA Address: %016" PRIx64 "\n", *LSDAAddress);
  924. CFIs.dump(OS, DumpOpts, MRI, IsEH);
  925. OS << "\n";
  926. if (Expected<UnwindTable> RowsOrErr = UnwindTable::create(this))
  927. RowsOrErr->dump(OS, MRI, IsEH, 1);
  928. else {
  929. DumpOpts.RecoverableErrorHandler(joinErrors(
  930. createStringError(errc::invalid_argument,
  931. "decoding the FDE opcodes into rows failed"),
  932. RowsOrErr.takeError()));
  933. }
  934. OS << "\n";
  935. }
  936. DWARFDebugFrame::DWARFDebugFrame(Triple::ArchType Arch,
  937. bool IsEH, uint64_t EHFrameAddress)
  938. : Arch(Arch), IsEH(IsEH), EHFrameAddress(EHFrameAddress) {}
  939. DWARFDebugFrame::~DWARFDebugFrame() = default;
  940. static void LLVM_ATTRIBUTE_UNUSED dumpDataAux(DataExtractor Data,
  941. uint64_t Offset, int Length) {
  942. errs() << "DUMP: ";
  943. for (int i = 0; i < Length; ++i) {
  944. uint8_t c = Data.getU8(&Offset);
  945. errs().write_hex(c); errs() << " ";
  946. }
  947. errs() << "\n";
  948. }
  949. Error DWARFDebugFrame::parse(DWARFDataExtractor Data) {
  950. uint64_t Offset = 0;
  951. DenseMap<uint64_t, CIE *> CIEs;
  952. while (Data.isValidOffset(Offset)) {
  953. uint64_t StartOffset = Offset;
  954. uint64_t Length;
  955. DwarfFormat Format;
  956. std::tie(Length, Format) = Data.getInitialLength(&Offset);
  957. bool IsDWARF64 = Format == DWARF64;
  958. // If the Length is 0, then this CIE is a terminator. We add it because some
  959. // dumper tools might need it to print something special for such entries
  960. // (e.g. llvm-objdump --dwarf=frames prints "ZERO terminator").
  961. if (Length == 0) {
  962. auto Cie = std::make_unique<CIE>(
  963. IsDWARF64, StartOffset, 0, 0, SmallString<8>(), 0, 0, 0, 0, 0,
  964. SmallString<8>(), 0, 0, None, None, Arch);
  965. CIEs[StartOffset] = Cie.get();
  966. Entries.push_back(std::move(Cie));
  967. break;
  968. }
  969. // At this point, Offset points to the next field after Length.
  970. // Length is the structure size excluding itself. Compute an offset one
  971. // past the end of the structure (needed to know how many instructions to
  972. // read).
  973. uint64_t StartStructureOffset = Offset;
  974. uint64_t EndStructureOffset = Offset + Length;
  975. // The Id field's size depends on the DWARF format
  976. Error Err = Error::success();
  977. uint64_t Id = Data.getRelocatedValue((IsDWARF64 && !IsEH) ? 8 : 4, &Offset,
  978. /*SectionIndex=*/nullptr, &Err);
  979. if (Err)
  980. return Err;
  981. if (Id == getCIEId(IsDWARF64, IsEH)) {
  982. uint8_t Version = Data.getU8(&Offset);
  983. const char *Augmentation = Data.getCStr(&Offset);
  984. StringRef AugmentationString(Augmentation ? Augmentation : "");
  985. uint8_t AddressSize = Version < 4 ? Data.getAddressSize() :
  986. Data.getU8(&Offset);
  987. Data.setAddressSize(AddressSize);
  988. uint8_t SegmentDescriptorSize = Version < 4 ? 0 : Data.getU8(&Offset);
  989. uint64_t CodeAlignmentFactor = Data.getULEB128(&Offset);
  990. int64_t DataAlignmentFactor = Data.getSLEB128(&Offset);
  991. uint64_t ReturnAddressRegister =
  992. Version == 1 ? Data.getU8(&Offset) : Data.getULEB128(&Offset);
  993. // Parse the augmentation data for EH CIEs
  994. StringRef AugmentationData("");
  995. uint32_t FDEPointerEncoding = DW_EH_PE_absptr;
  996. uint32_t LSDAPointerEncoding = DW_EH_PE_omit;
  997. Optional<uint64_t> Personality;
  998. Optional<uint32_t> PersonalityEncoding;
  999. if (IsEH) {
  1000. Optional<uint64_t> AugmentationLength;
  1001. uint64_t StartAugmentationOffset;
  1002. uint64_t EndAugmentationOffset;
  1003. // Walk the augmentation string to get all the augmentation data.
  1004. for (unsigned i = 0, e = AugmentationString.size(); i != e; ++i) {
  1005. switch (AugmentationString[i]) {
  1006. default:
  1007. return createStringError(
  1008. errc::invalid_argument,
  1009. "unknown augmentation character in entry at 0x%" PRIx64,
  1010. StartOffset);
  1011. case 'L':
  1012. LSDAPointerEncoding = Data.getU8(&Offset);
  1013. break;
  1014. case 'P': {
  1015. if (Personality)
  1016. return createStringError(
  1017. errc::invalid_argument,
  1018. "duplicate personality in entry at 0x%" PRIx64, StartOffset);
  1019. PersonalityEncoding = Data.getU8(&Offset);
  1020. Personality = Data.getEncodedPointer(
  1021. &Offset, *PersonalityEncoding,
  1022. EHFrameAddress ? EHFrameAddress + Offset : 0);
  1023. break;
  1024. }
  1025. case 'R':
  1026. FDEPointerEncoding = Data.getU8(&Offset);
  1027. break;
  1028. case 'S':
  1029. // Current frame is a signal trampoline.
  1030. break;
  1031. case 'z':
  1032. if (i)
  1033. return createStringError(
  1034. errc::invalid_argument,
  1035. "'z' must be the first character at 0x%" PRIx64, StartOffset);
  1036. // Parse the augmentation length first. We only parse it if
  1037. // the string contains a 'z'.
  1038. AugmentationLength = Data.getULEB128(&Offset);
  1039. StartAugmentationOffset = Offset;
  1040. EndAugmentationOffset = Offset + *AugmentationLength;
  1041. break;
  1042. case 'B':
  1043. // B-Key is used for signing functions associated with this
  1044. // augmentation string
  1045. break;
  1046. }
  1047. }
  1048. if (AugmentationLength.hasValue()) {
  1049. if (Offset != EndAugmentationOffset)
  1050. return createStringError(errc::invalid_argument,
  1051. "parsing augmentation data at 0x%" PRIx64
  1052. " failed",
  1053. StartOffset);
  1054. AugmentationData = Data.getData().slice(StartAugmentationOffset,
  1055. EndAugmentationOffset);
  1056. }
  1057. }
  1058. auto Cie = std::make_unique<CIE>(
  1059. IsDWARF64, StartOffset, Length, Version, AugmentationString,
  1060. AddressSize, SegmentDescriptorSize, CodeAlignmentFactor,
  1061. DataAlignmentFactor, ReturnAddressRegister, AugmentationData,
  1062. FDEPointerEncoding, LSDAPointerEncoding, Personality,
  1063. PersonalityEncoding, Arch);
  1064. CIEs[StartOffset] = Cie.get();
  1065. Entries.emplace_back(std::move(Cie));
  1066. } else {
  1067. // FDE
  1068. uint64_t CIEPointer = Id;
  1069. uint64_t InitialLocation = 0;
  1070. uint64_t AddressRange = 0;
  1071. Optional<uint64_t> LSDAAddress;
  1072. CIE *Cie = CIEs[IsEH ? (StartStructureOffset - CIEPointer) : CIEPointer];
  1073. if (IsEH) {
  1074. // The address size is encoded in the CIE we reference.
  1075. if (!Cie)
  1076. return createStringError(errc::invalid_argument,
  1077. "parsing FDE data at 0x%" PRIx64
  1078. " failed due to missing CIE",
  1079. StartOffset);
  1080. if (auto Val =
  1081. Data.getEncodedPointer(&Offset, Cie->getFDEPointerEncoding(),
  1082. EHFrameAddress + Offset)) {
  1083. InitialLocation = *Val;
  1084. }
  1085. if (auto Val = Data.getEncodedPointer(
  1086. &Offset, Cie->getFDEPointerEncoding(), 0)) {
  1087. AddressRange = *Val;
  1088. }
  1089. StringRef AugmentationString = Cie->getAugmentationString();
  1090. if (!AugmentationString.empty()) {
  1091. // Parse the augmentation length and data for this FDE.
  1092. uint64_t AugmentationLength = Data.getULEB128(&Offset);
  1093. uint64_t EndAugmentationOffset = Offset + AugmentationLength;
  1094. // Decode the LSDA if the CIE augmentation string said we should.
  1095. if (Cie->getLSDAPointerEncoding() != DW_EH_PE_omit) {
  1096. LSDAAddress = Data.getEncodedPointer(
  1097. &Offset, Cie->getLSDAPointerEncoding(),
  1098. EHFrameAddress ? Offset + EHFrameAddress : 0);
  1099. }
  1100. if (Offset != EndAugmentationOffset)
  1101. return createStringError(errc::invalid_argument,
  1102. "parsing augmentation data at 0x%" PRIx64
  1103. " failed",
  1104. StartOffset);
  1105. }
  1106. } else {
  1107. InitialLocation = Data.getRelocatedAddress(&Offset);
  1108. AddressRange = Data.getRelocatedAddress(&Offset);
  1109. }
  1110. Entries.emplace_back(new FDE(IsDWARF64, StartOffset, Length, CIEPointer,
  1111. InitialLocation, AddressRange, Cie,
  1112. LSDAAddress, Arch));
  1113. }
  1114. if (Error E =
  1115. Entries.back()->cfis().parse(Data, &Offset, EndStructureOffset))
  1116. return E;
  1117. if (Offset != EndStructureOffset)
  1118. return createStringError(
  1119. errc::invalid_argument,
  1120. "parsing entry instructions at 0x%" PRIx64 " failed", StartOffset);
  1121. }
  1122. return Error::success();
  1123. }
  1124. FrameEntry *DWARFDebugFrame::getEntryAtOffset(uint64_t Offset) const {
  1125. auto It = partition_point(Entries, [=](const std::unique_ptr<FrameEntry> &E) {
  1126. return E->getOffset() < Offset;
  1127. });
  1128. if (It != Entries.end() && (*It)->getOffset() == Offset)
  1129. return It->get();
  1130. return nullptr;
  1131. }
  1132. void DWARFDebugFrame::dump(raw_ostream &OS, DIDumpOptions DumpOpts,
  1133. const MCRegisterInfo *MRI,
  1134. Optional<uint64_t> Offset) const {
  1135. if (Offset) {
  1136. if (auto *Entry = getEntryAtOffset(*Offset))
  1137. Entry->dump(OS, DumpOpts, MRI, IsEH);
  1138. return;
  1139. }
  1140. OS << "\n";
  1141. for (const auto &Entry : Entries)
  1142. Entry->dump(OS, DumpOpts, MRI, IsEH);
  1143. }