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