DWARFDebugFrame.cpp 45 KB

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