1 //===--------------------------- DwarfParser.hpp --------------------------===//
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 //  Parses DWARF CFIs (FDEs and CIEs).
9 //
10 //===----------------------------------------------------------------------===//
11 
12 #ifndef __DWARF_PARSER_HPP__
13 #define __DWARF_PARSER_HPP__
14 
15 #include <inttypes.h>
16 #include <stdint.h>
17 #include <stdio.h>
18 #include <stdlib.h>
19 
20 #include "libunwind.h"
21 #include "dwarf2.h"
22 #include "Registers.hpp"
23 
24 #include "config.h"
25 
26 namespace libunwind {
27 
28 /// CFI_Parser does basic parsing of a CFI (Call Frame Information) records.
29 /// See DWARF Spec for details:
30 ///    http://refspecs.linuxbase.org/LSB_3.1.0/LSB-Core-generic/LSB-Core-generic/ehframechpt.html
31 ///
32 template <typename A>
33 class CFI_Parser {
34 public:
35   typedef typename A::pint_t pint_t;
36 
37   /// Information encoded in a CIE (Common Information Entry)
38   struct CIE_Info {
39     pint_t    cieStart;
40     pint_t    cieLength;
41     pint_t    cieInstructions;
42     uint8_t   pointerEncoding;
43     uint8_t   lsdaEncoding;
44     uint8_t   personalityEncoding;
45     uint8_t   personalityOffsetInCIE;
46     pint_t    personality;
47     uint32_t  codeAlignFactor;
48     int       dataAlignFactor;
49     bool      isSignalFrame;
50     bool      fdesHaveAugmentationData;
51     uint8_t   returnAddressRegister;
52 #if defined(_LIBUNWIND_TARGET_AARCH64)
53     bool      addressesSignedWithBKey;
54 #endif
55   };
56 
57   /// Information about an FDE (Frame Description Entry)
58   struct FDE_Info {
59     pint_t  fdeStart;
60     pint_t  fdeLength;
61     pint_t  fdeInstructions;
62     pint_t  pcStart;
63     pint_t  pcEnd;
64     pint_t  lsda;
65   };
66 
67   enum {
68     kMaxRegisterNumber = _LIBUNWIND_HIGHEST_DWARF_REGISTER
69   };
70   enum RegisterSavedWhere {
71     kRegisterUnused,
72     kRegisterInCFA,
73     kRegisterOffsetFromCFA,
74     kRegisterInRegister,
75     kRegisterAtExpression,
76     kRegisterIsExpression
77   };
78   struct RegisterLocation {
79     RegisterSavedWhere location;
80     bool initialStateSaved;
81     int64_t value;
82   };
83   /// Information about a frame layout and registers saved determined
84   /// by "running" the DWARF FDE "instructions"
85   struct PrologInfo {
86     uint32_t          cfaRegister;
87     int32_t           cfaRegisterOffset;  // CFA = (cfaRegister)+cfaRegisterOffset
88     int64_t           cfaExpression;      // CFA = expression
89     uint32_t          spExtraArgSize;
90     uint32_t          codeOffsetAtStackDecrement;
91     bool              registersInOtherRegisters;
92     bool              sameValueUsed;
93     RegisterLocation  savedRegisters[kMaxRegisterNumber + 1];
94     enum class InitializeTime { kLazy, kNormal };
95 
96     // When saving registers, this data structure is lazily initialized.
97     PrologInfo(InitializeTime IT = InitializeTime::kNormal) {
98       if (IT == InitializeTime::kNormal)
99         memset(this, 0, sizeof(*this));
100     }
101     void checkSaveRegister(uint64_t reg, PrologInfo &initialState) {
102       if (!savedRegisters[reg].initialStateSaved) {
103         initialState.savedRegisters[reg] = savedRegisters[reg];
104         savedRegisters[reg].initialStateSaved = true;
105       }
106     }
107     void setRegister(uint64_t reg, RegisterSavedWhere newLocation,
108                      int64_t newValue, PrologInfo &initialState) {
109       checkSaveRegister(reg, initialState);
110       savedRegisters[reg].location = newLocation;
111       savedRegisters[reg].value = newValue;
112     }
113     void setRegisterLocation(uint64_t reg, RegisterSavedWhere newLocation,
114                              PrologInfo &initialState) {
115       checkSaveRegister(reg, initialState);
116       savedRegisters[reg].location = newLocation;
117     }
118     void setRegisterValue(uint64_t reg, int64_t newValue,
119                           PrologInfo &initialState) {
120       checkSaveRegister(reg, initialState);
121       savedRegisters[reg].value = newValue;
122     }
123     void restoreRegisterToInitialState(uint64_t reg, PrologInfo &initialState) {
124       if (savedRegisters[reg].initialStateSaved)
125         savedRegisters[reg] = initialState.savedRegisters[reg];
126       // else the register still holds its initial state
127     }
128   };
129 
130   struct PrologInfoStackEntry {
131     PrologInfoStackEntry(PrologInfoStackEntry *n, const PrologInfo &i)
132         : next(n), info(i) {}
133     PrologInfoStackEntry *next;
134     PrologInfo info;
135   };
136 
137   static bool findFDE(A &addressSpace, pint_t pc, pint_t ehSectionStart,
138                       uint32_t sectionLength, pint_t fdeHint, FDE_Info *fdeInfo,
139                       CIE_Info *cieInfo);
140   static const char *decodeFDE(A &addressSpace, pint_t fdeStart,
141                                FDE_Info *fdeInfo, CIE_Info *cieInfo);
142   static bool parseFDEInstructions(A &addressSpace, const FDE_Info &fdeInfo,
143                                    const CIE_Info &cieInfo, pint_t upToPC,
144                                    int arch, PrologInfo *results);
145 
146   static const char *parseCIE(A &addressSpace, pint_t cie, CIE_Info *cieInfo);
147 
148 private:
149   static bool parseInstructions(A &addressSpace, pint_t instructions,
150                                 pint_t instructionsEnd, const CIE_Info &cieInfo,
151                                 pint_t pcoffset,
152                                 PrologInfoStackEntry *&rememberStack, int arch,
153                                 PrologInfo *results);
154 };
155 
156 /// Parse a FDE into a CIE_Info and an FDE_Info
157 template <typename A>
158 const char *CFI_Parser<A>::decodeFDE(A &addressSpace, pint_t fdeStart,
159                                      FDE_Info *fdeInfo, CIE_Info *cieInfo) {
160   pint_t p = fdeStart;
161   pint_t cfiLength = (pint_t)addressSpace.get32(p);
162   p += 4;
163   if (cfiLength == 0xffffffff) {
164     // 0xffffffff means length is really next 8 bytes
165     cfiLength = (pint_t)addressSpace.get64(p);
166     p += 8;
167   }
168   if (cfiLength == 0)
169     return "FDE has zero length"; // end marker
170   uint32_t ciePointer = addressSpace.get32(p);
171   if (ciePointer == 0)
172     return "FDE is really a CIE"; // this is a CIE not an FDE
173   pint_t nextCFI = p + cfiLength;
174   pint_t cieStart = p - ciePointer;
175   const char *err = parseCIE(addressSpace, cieStart, cieInfo);
176   if (err != NULL)
177     return err;
178   p += 4;
179   // Parse pc begin and range.
180   pint_t pcStart =
181       addressSpace.getEncodedP(p, nextCFI, cieInfo->pointerEncoding);
182   pint_t pcRange =
183       addressSpace.getEncodedP(p, nextCFI, cieInfo->pointerEncoding & 0x0F);
184   // Parse rest of info.
185   fdeInfo->lsda = 0;
186   // Check for augmentation length.
187   if (cieInfo->fdesHaveAugmentationData) {
188     pint_t augLen = (pint_t)addressSpace.getULEB128(p, nextCFI);
189     pint_t endOfAug = p + augLen;
190     if (cieInfo->lsdaEncoding != DW_EH_PE_omit) {
191       // Peek at value (without indirection).  Zero means no LSDA.
192       pint_t lsdaStart = p;
193       if (addressSpace.getEncodedP(p, nextCFI, cieInfo->lsdaEncoding & 0x0F) !=
194           0) {
195         // Reset pointer and re-parse LSDA address.
196         p = lsdaStart;
197         fdeInfo->lsda =
198             addressSpace.getEncodedP(p, nextCFI, cieInfo->lsdaEncoding);
199       }
200     }
201     p = endOfAug;
202   }
203   fdeInfo->fdeStart = fdeStart;
204   fdeInfo->fdeLength = nextCFI - fdeStart;
205   fdeInfo->fdeInstructions = p;
206   fdeInfo->pcStart = pcStart;
207   fdeInfo->pcEnd = pcStart + pcRange;
208   return NULL; // success
209 }
210 
211 /// Scan an eh_frame section to find an FDE for a pc
212 template <typename A>
213 bool CFI_Parser<A>::findFDE(A &addressSpace, pint_t pc, pint_t ehSectionStart,
214                             uint32_t sectionLength, pint_t fdeHint,
215                             FDE_Info *fdeInfo, CIE_Info *cieInfo) {
216   //fprintf(stderr, "findFDE(0x%llX)\n", (long long)pc);
217   pint_t p = (fdeHint != 0) ? fdeHint : ehSectionStart;
218   const pint_t ehSectionEnd = p + sectionLength;
219   while (p < ehSectionEnd) {
220     pint_t currentCFI = p;
221     //fprintf(stderr, "findFDE() CFI at 0x%llX\n", (long long)p);
222     pint_t cfiLength = addressSpace.get32(p);
223     p += 4;
224     if (cfiLength == 0xffffffff) {
225       // 0xffffffff means length is really next 8 bytes
226       cfiLength = (pint_t)addressSpace.get64(p);
227       p += 8;
228     }
229     if (cfiLength == 0)
230       return false; // end marker
231     uint32_t id = addressSpace.get32(p);
232     if (id == 0) {
233       // Skip over CIEs.
234       p += cfiLength;
235     } else {
236       // Process FDE to see if it covers pc.
237       pint_t nextCFI = p + cfiLength;
238       uint32_t ciePointer = addressSpace.get32(p);
239       pint_t cieStart = p - ciePointer;
240       // Validate pointer to CIE is within section.
241       if ((ehSectionStart <= cieStart) && (cieStart < ehSectionEnd)) {
242         if (parseCIE(addressSpace, cieStart, cieInfo) == NULL) {
243           p += 4;
244           // Parse pc begin and range.
245           pint_t pcStart =
246               addressSpace.getEncodedP(p, nextCFI, cieInfo->pointerEncoding);
247           pint_t pcRange = addressSpace.getEncodedP(
248               p, nextCFI, cieInfo->pointerEncoding & 0x0F);
249           // Test if pc is within the function this FDE covers.
250           if ((pcStart < pc) && (pc <= pcStart + pcRange)) {
251             // parse rest of info
252             fdeInfo->lsda = 0;
253             // check for augmentation length
254             if (cieInfo->fdesHaveAugmentationData) {
255               pint_t augLen = (pint_t)addressSpace.getULEB128(p, nextCFI);
256               pint_t endOfAug = p + augLen;
257               if (cieInfo->lsdaEncoding != DW_EH_PE_omit) {
258                 // Peek at value (without indirection).  Zero means no LSDA.
259                 pint_t lsdaStart = p;
260                 if (addressSpace.getEncodedP(
261                         p, nextCFI, cieInfo->lsdaEncoding & 0x0F) != 0) {
262                   // Reset pointer and re-parse LSDA address.
263                   p = lsdaStart;
264                   fdeInfo->lsda = addressSpace
265                       .getEncodedP(p, nextCFI, cieInfo->lsdaEncoding);
266                 }
267               }
268               p = endOfAug;
269             }
270             fdeInfo->fdeStart = currentCFI;
271             fdeInfo->fdeLength = nextCFI - currentCFI;
272             fdeInfo->fdeInstructions = p;
273             fdeInfo->pcStart = pcStart;
274             fdeInfo->pcEnd = pcStart + pcRange;
275             return true;
276           } else {
277             // pc is not in begin/range, skip this FDE
278           }
279         } else {
280           // Malformed CIE, now augmentation describing pc range encoding.
281         }
282       } else {
283         // malformed FDE.  CIE is bad
284       }
285       p = nextCFI;
286     }
287   }
288   return false;
289 }
290 
291 /// Extract info from a CIE
292 template <typename A>
293 const char *CFI_Parser<A>::parseCIE(A &addressSpace, pint_t cie,
294                                     CIE_Info *cieInfo) {
295   cieInfo->pointerEncoding = 0;
296   cieInfo->lsdaEncoding = DW_EH_PE_omit;
297   cieInfo->personalityEncoding = 0;
298   cieInfo->personalityOffsetInCIE = 0;
299   cieInfo->personality = 0;
300   cieInfo->codeAlignFactor = 0;
301   cieInfo->dataAlignFactor = 0;
302   cieInfo->isSignalFrame = false;
303   cieInfo->fdesHaveAugmentationData = false;
304 #if defined(_LIBUNWIND_TARGET_AARCH64)
305   cieInfo->addressesSignedWithBKey = false;
306 #endif
307   cieInfo->cieStart = cie;
308   pint_t p = cie;
309   pint_t cieLength = (pint_t)addressSpace.get32(p);
310   p += 4;
311   pint_t cieContentEnd = p + cieLength;
312   if (cieLength == 0xffffffff) {
313     // 0xffffffff means length is really next 8 bytes
314     cieLength = (pint_t)addressSpace.get64(p);
315     p += 8;
316     cieContentEnd = p + cieLength;
317   }
318   if (cieLength == 0)
319     return NULL;
320   // CIE ID is always 0
321   if (addressSpace.get32(p) != 0)
322     return "CIE ID is not zero";
323   p += 4;
324   // Version is always 1 or 3
325   uint8_t version = addressSpace.get8(p);
326   if ((version != 1) && (version != 3))
327     return "CIE version is not 1 or 3";
328   ++p;
329   // save start of augmentation string and find end
330   pint_t strStart = p;
331   while (addressSpace.get8(p) != 0)
332     ++p;
333   ++p;
334   // parse code aligment factor
335   cieInfo->codeAlignFactor = (uint32_t)addressSpace.getULEB128(p, cieContentEnd);
336   // parse data alignment factor
337   cieInfo->dataAlignFactor = (int)addressSpace.getSLEB128(p, cieContentEnd);
338   // parse return address register
339   uint64_t raReg = addressSpace.getULEB128(p, cieContentEnd);
340   assert(raReg < 255 && "return address register too large");
341   cieInfo->returnAddressRegister = (uint8_t)raReg;
342   // parse augmentation data based on augmentation string
343   const char *result = NULL;
344   if (addressSpace.get8(strStart) == 'z') {
345     // parse augmentation data length
346     addressSpace.getULEB128(p, cieContentEnd);
347     for (pint_t s = strStart; addressSpace.get8(s) != '\0'; ++s) {
348       switch (addressSpace.get8(s)) {
349       case 'z':
350         cieInfo->fdesHaveAugmentationData = true;
351         break;
352       case 'P':
353         cieInfo->personalityEncoding = addressSpace.get8(p);
354         ++p;
355         cieInfo->personalityOffsetInCIE = (uint8_t)(p - cie);
356         cieInfo->personality = addressSpace
357             .getEncodedP(p, cieContentEnd, cieInfo->personalityEncoding);
358         break;
359       case 'L':
360         cieInfo->lsdaEncoding = addressSpace.get8(p);
361         ++p;
362         break;
363       case 'R':
364         cieInfo->pointerEncoding = addressSpace.get8(p);
365         ++p;
366         break;
367       case 'S':
368         cieInfo->isSignalFrame = true;
369         break;
370 #if defined(_LIBUNWIND_TARGET_AARCH64)
371       case 'B':
372         cieInfo->addressesSignedWithBKey = true;
373         break;
374 #endif
375       default:
376         // ignore unknown letters
377         break;
378       }
379     }
380   }
381   cieInfo->cieLength = cieContentEnd - cieInfo->cieStart;
382   cieInfo->cieInstructions = p;
383   return result;
384 }
385 
386 
387 /// "run" the DWARF instructions and create the abstact PrologInfo for an FDE
388 template <typename A>
389 bool CFI_Parser<A>::parseFDEInstructions(A &addressSpace,
390                                          const FDE_Info &fdeInfo,
391                                          const CIE_Info &cieInfo, pint_t upToPC,
392                                          int arch, PrologInfo *results) {
393   PrologInfoStackEntry *rememberStack = NULL;
394 
395   // parse CIE then FDE instructions
396   bool returnValue =
397       parseInstructions(addressSpace, cieInfo.cieInstructions,
398                         cieInfo.cieStart + cieInfo.cieLength, cieInfo,
399                         (pint_t)(-1), rememberStack, arch, results) &&
400       parseInstructions(addressSpace, fdeInfo.fdeInstructions,
401                         fdeInfo.fdeStart + fdeInfo.fdeLength, cieInfo,
402                         upToPC - fdeInfo.pcStart, rememberStack, arch, results);
403 
404   // Clean up rememberStack. Even in the case where every DW_CFA_remember_state
405   // is paired with a DW_CFA_restore_state, parseInstructions can skip restore
406   // opcodes if it reaches the target PC and stops interpreting, so we have to
407   // make sure we don't leak memory.
408   while (rememberStack) {
409     PrologInfoStackEntry *next = rememberStack->next;
410     free(rememberStack);
411     rememberStack = next;
412   }
413 
414   return returnValue;
415 }
416 
417 /// "run" the DWARF instructions
418 template <typename A>
419 bool CFI_Parser<A>::parseInstructions(A &addressSpace, pint_t instructions,
420                                       pint_t instructionsEnd,
421                                       const CIE_Info &cieInfo, pint_t pcoffset,
422                                       PrologInfoStackEntry *&rememberStack,
423                                       int arch, PrologInfo *results) {
424   pint_t p = instructions;
425   pint_t codeOffset = 0;
426   // initialState initialized as registers in results are modified. Use
427   // PrologInfo accessor functions to avoid reading uninitialized data.
428   PrologInfo initialState(PrologInfo::InitializeTime::kLazy);
429 
430   _LIBUNWIND_TRACE_DWARF("parseInstructions(instructions=0x%0" PRIx64 ")\n",
431                          static_cast<uint64_t>(instructionsEnd));
432 
433   // see DWARF Spec, section 6.4.2 for details on unwind opcodes
434   while ((p < instructionsEnd) && (codeOffset < pcoffset)) {
435     uint64_t reg;
436     uint64_t reg2;
437     int64_t offset;
438     uint64_t length;
439     uint8_t opcode = addressSpace.get8(p);
440     uint8_t operand;
441 #if !defined(_LIBUNWIND_NO_HEAP)
442     PrologInfoStackEntry *entry;
443 #endif
444     ++p;
445     switch (opcode) {
446     case DW_CFA_nop:
447       _LIBUNWIND_TRACE_DWARF("DW_CFA_nop\n");
448       break;
449     case DW_CFA_set_loc:
450       codeOffset =
451           addressSpace.getEncodedP(p, instructionsEnd, cieInfo.pointerEncoding);
452       _LIBUNWIND_TRACE_DWARF("DW_CFA_set_loc\n");
453       break;
454     case DW_CFA_advance_loc1:
455       codeOffset += (addressSpace.get8(p) * cieInfo.codeAlignFactor);
456       p += 1;
457       _LIBUNWIND_TRACE_DWARF("DW_CFA_advance_loc1: new offset=%" PRIu64 "\n",
458                              static_cast<uint64_t>(codeOffset));
459       break;
460     case DW_CFA_advance_loc2:
461       codeOffset += (addressSpace.get16(p) * cieInfo.codeAlignFactor);
462       p += 2;
463       _LIBUNWIND_TRACE_DWARF("DW_CFA_advance_loc2: new offset=%" PRIu64 "\n",
464                              static_cast<uint64_t>(codeOffset));
465       break;
466     case DW_CFA_advance_loc4:
467       codeOffset += (addressSpace.get32(p) * cieInfo.codeAlignFactor);
468       p += 4;
469       _LIBUNWIND_TRACE_DWARF("DW_CFA_advance_loc4: new offset=%" PRIu64 "\n",
470                              static_cast<uint64_t>(codeOffset));
471       break;
472     case DW_CFA_offset_extended:
473       reg = addressSpace.getULEB128(p, instructionsEnd);
474       offset = (int64_t)addressSpace.getULEB128(p, instructionsEnd)
475                                                   * cieInfo.dataAlignFactor;
476       if (reg > kMaxRegisterNumber) {
477         _LIBUNWIND_LOG0(
478                 "malformed DW_CFA_offset_extended DWARF unwind, reg too big");
479         return false;
480       }
481       results->setRegister(reg, kRegisterInCFA, offset, initialState);
482       _LIBUNWIND_TRACE_DWARF("DW_CFA_offset_extended(reg=%" PRIu64 ", "
483                              "offset=%" PRId64 ")\n",
484                              reg, offset);
485       break;
486     case DW_CFA_restore_extended:
487       reg = addressSpace.getULEB128(p, instructionsEnd);
488       if (reg > kMaxRegisterNumber) {
489         _LIBUNWIND_LOG0(
490             "malformed DW_CFA_restore_extended DWARF unwind, reg too big");
491         return false;
492       }
493       results->restoreRegisterToInitialState(reg, initialState);
494       _LIBUNWIND_TRACE_DWARF("DW_CFA_restore_extended(reg=%" PRIu64 ")\n", reg);
495       break;
496     case DW_CFA_undefined:
497       reg = addressSpace.getULEB128(p, instructionsEnd);
498       if (reg > kMaxRegisterNumber) {
499         _LIBUNWIND_LOG0(
500                 "malformed DW_CFA_undefined DWARF unwind, reg too big");
501         return false;
502       }
503       results->setRegisterLocation(reg, kRegisterUnused, initialState);
504       _LIBUNWIND_TRACE_DWARF("DW_CFA_undefined(reg=%" PRIu64 ")\n", reg);
505       break;
506     case DW_CFA_same_value:
507       reg = addressSpace.getULEB128(p, instructionsEnd);
508       if (reg > kMaxRegisterNumber) {
509         _LIBUNWIND_LOG0(
510                 "malformed DW_CFA_same_value DWARF unwind, reg too big");
511         return false;
512       }
513       // <rdar://problem/8456377> DW_CFA_same_value unsupported
514       // "same value" means register was stored in frame, but its current
515       // value has not changed, so no need to restore from frame.
516       // We model this as if the register was never saved.
517       results->setRegisterLocation(reg, kRegisterUnused, initialState);
518       // set flag to disable conversion to compact unwind
519       results->sameValueUsed = true;
520       _LIBUNWIND_TRACE_DWARF("DW_CFA_same_value(reg=%" PRIu64 ")\n", reg);
521       break;
522     case DW_CFA_register:
523       reg = addressSpace.getULEB128(p, instructionsEnd);
524       reg2 = addressSpace.getULEB128(p, instructionsEnd);
525       if (reg > kMaxRegisterNumber) {
526         _LIBUNWIND_LOG0(
527                 "malformed DW_CFA_register DWARF unwind, reg too big");
528         return false;
529       }
530       if (reg2 > kMaxRegisterNumber) {
531         _LIBUNWIND_LOG0(
532                 "malformed DW_CFA_register DWARF unwind, reg2 too big");
533         return false;
534       }
535       results->setRegister(reg, kRegisterInRegister, (int64_t)reg2,
536                            initialState);
537       // set flag to disable conversion to compact unwind
538       results->registersInOtherRegisters = true;
539       _LIBUNWIND_TRACE_DWARF(
540           "DW_CFA_register(reg=%" PRIu64 ", reg2=%" PRIu64 ")\n", reg, reg2);
541       break;
542 #if !defined(_LIBUNWIND_NO_HEAP)
543     case DW_CFA_remember_state:
544       // avoid operator new, because that would be an upward dependency
545       entry = (PrologInfoStackEntry *)malloc(sizeof(PrologInfoStackEntry));
546       if (entry != NULL) {
547         entry->next = rememberStack;
548         entry->info = *results;
549         rememberStack = entry;
550       } else {
551         return false;
552       }
553       _LIBUNWIND_TRACE_DWARF("DW_CFA_remember_state\n");
554       break;
555     case DW_CFA_restore_state:
556       if (rememberStack != NULL) {
557         PrologInfoStackEntry *top = rememberStack;
558         *results = top->info;
559         rememberStack = top->next;
560         free((char *)top);
561       } else {
562         return false;
563       }
564       _LIBUNWIND_TRACE_DWARF("DW_CFA_restore_state\n");
565       break;
566 #endif
567     case DW_CFA_def_cfa:
568       reg = addressSpace.getULEB128(p, instructionsEnd);
569       offset = (int64_t)addressSpace.getULEB128(p, instructionsEnd);
570       if (reg > kMaxRegisterNumber) {
571         _LIBUNWIND_LOG0("malformed DW_CFA_def_cfa DWARF unwind, reg too big");
572         return false;
573       }
574       results->cfaRegister = (uint32_t)reg;
575       results->cfaRegisterOffset = (int32_t)offset;
576       _LIBUNWIND_TRACE_DWARF(
577           "DW_CFA_def_cfa(reg=%" PRIu64 ", offset=%" PRIu64 ")\n", reg, offset);
578       break;
579     case DW_CFA_def_cfa_register:
580       reg = addressSpace.getULEB128(p, instructionsEnd);
581       if (reg > kMaxRegisterNumber) {
582         _LIBUNWIND_LOG0(
583             "malformed DW_CFA_def_cfa_register DWARF unwind, reg too big");
584         return false;
585       }
586       results->cfaRegister = (uint32_t)reg;
587       _LIBUNWIND_TRACE_DWARF("DW_CFA_def_cfa_register(%" PRIu64 ")\n", reg);
588       break;
589     case DW_CFA_def_cfa_offset:
590       results->cfaRegisterOffset = (int32_t)
591                                   addressSpace.getULEB128(p, instructionsEnd);
592       results->codeOffsetAtStackDecrement = (uint32_t)codeOffset;
593       _LIBUNWIND_TRACE_DWARF("DW_CFA_def_cfa_offset(%d)\n",
594                              results->cfaRegisterOffset);
595       break;
596     case DW_CFA_def_cfa_expression:
597       results->cfaRegister = 0;
598       results->cfaExpression = (int64_t)p;
599       length = addressSpace.getULEB128(p, instructionsEnd);
600       assert(length < static_cast<pint_t>(~0) && "pointer overflow");
601       p += static_cast<pint_t>(length);
602       _LIBUNWIND_TRACE_DWARF("DW_CFA_def_cfa_expression(expression=0x%" PRIx64
603                              ", length=%" PRIu64 ")\n",
604                              results->cfaExpression, length);
605       break;
606     case DW_CFA_expression:
607       reg = addressSpace.getULEB128(p, instructionsEnd);
608       if (reg > kMaxRegisterNumber) {
609         _LIBUNWIND_LOG0(
610                 "malformed DW_CFA_expression DWARF unwind, reg too big");
611         return false;
612       }
613       results->setRegister(reg, kRegisterAtExpression, (int64_t)p,
614                            initialState);
615       length = addressSpace.getULEB128(p, instructionsEnd);
616       assert(length < static_cast<pint_t>(~0) && "pointer overflow");
617       p += static_cast<pint_t>(length);
618       _LIBUNWIND_TRACE_DWARF("DW_CFA_expression(reg=%" PRIu64 ", "
619                              "expression=0x%" PRIx64 ", "
620                              "length=%" PRIu64 ")\n",
621                              reg, results->savedRegisters[reg].value, length);
622       break;
623     case DW_CFA_offset_extended_sf:
624       reg = addressSpace.getULEB128(p, instructionsEnd);
625       if (reg > kMaxRegisterNumber) {
626         _LIBUNWIND_LOG0(
627             "malformed DW_CFA_offset_extended_sf DWARF unwind, reg too big");
628         return false;
629       }
630       offset =
631           addressSpace.getSLEB128(p, instructionsEnd) * cieInfo.dataAlignFactor;
632       results->setRegister(reg, kRegisterInCFA, offset, initialState);
633       _LIBUNWIND_TRACE_DWARF("DW_CFA_offset_extended_sf(reg=%" PRIu64 ", "
634                              "offset=%" PRId64 ")\n",
635                              reg, offset);
636       break;
637     case DW_CFA_def_cfa_sf:
638       reg = addressSpace.getULEB128(p, instructionsEnd);
639       offset =
640           addressSpace.getSLEB128(p, instructionsEnd) * cieInfo.dataAlignFactor;
641       if (reg > kMaxRegisterNumber) {
642         _LIBUNWIND_LOG0(
643                 "malformed DW_CFA_def_cfa_sf DWARF unwind, reg too big");
644         return false;
645       }
646       results->cfaRegister = (uint32_t)reg;
647       results->cfaRegisterOffset = (int32_t)offset;
648       _LIBUNWIND_TRACE_DWARF("DW_CFA_def_cfa_sf(reg=%" PRIu64 ", "
649                              "offset=%" PRId64 ")\n",
650                              reg, offset);
651       break;
652     case DW_CFA_def_cfa_offset_sf:
653       results->cfaRegisterOffset = (int32_t)
654         (addressSpace.getSLEB128(p, instructionsEnd) * cieInfo.dataAlignFactor);
655       results->codeOffsetAtStackDecrement = (uint32_t)codeOffset;
656       _LIBUNWIND_TRACE_DWARF("DW_CFA_def_cfa_offset_sf(%d)\n",
657                              results->cfaRegisterOffset);
658       break;
659     case DW_CFA_val_offset:
660       reg = addressSpace.getULEB128(p, instructionsEnd);
661       if (reg > kMaxRegisterNumber) {
662         _LIBUNWIND_LOG(
663                 "malformed DW_CFA_val_offset DWARF unwind, reg (%" PRIu64
664                 ") out of range\n",
665                 reg);
666         return false;
667       }
668       offset = (int64_t)addressSpace.getULEB128(p, instructionsEnd)
669                                                     * cieInfo.dataAlignFactor;
670       results->setRegister(reg, kRegisterOffsetFromCFA, offset, initialState);
671       _LIBUNWIND_TRACE_DWARF("DW_CFA_val_offset(reg=%" PRIu64 ", "
672                              "offset=%" PRId64 "\n",
673                              reg, offset);
674       break;
675     case DW_CFA_val_offset_sf:
676       reg = addressSpace.getULEB128(p, instructionsEnd);
677       if (reg > kMaxRegisterNumber) {
678         _LIBUNWIND_LOG0(
679                 "malformed DW_CFA_val_offset_sf DWARF unwind, reg too big");
680         return false;
681       }
682       offset =
683           addressSpace.getSLEB128(p, instructionsEnd) * cieInfo.dataAlignFactor;
684       results->setRegister(reg, kRegisterOffsetFromCFA, offset, initialState);
685       _LIBUNWIND_TRACE_DWARF("DW_CFA_val_offset_sf(reg=%" PRIu64 ", "
686                              "offset=%" PRId64 "\n",
687                              reg, offset);
688       break;
689     case DW_CFA_val_expression:
690       reg = addressSpace.getULEB128(p, instructionsEnd);
691       if (reg > kMaxRegisterNumber) {
692         _LIBUNWIND_LOG0(
693                 "malformed DW_CFA_val_expression DWARF unwind, reg too big");
694         return false;
695       }
696       results->setRegister(reg, kRegisterIsExpression, (int64_t)p,
697                            initialState);
698       length = addressSpace.getULEB128(p, instructionsEnd);
699       assert(length < static_cast<pint_t>(~0) && "pointer overflow");
700       p += static_cast<pint_t>(length);
701       _LIBUNWIND_TRACE_DWARF("DW_CFA_val_expression(reg=%" PRIu64 ", "
702                              "expression=0x%" PRIx64 ", length=%" PRIu64 ")\n",
703                              reg, results->savedRegisters[reg].value, length);
704       break;
705     case DW_CFA_GNU_args_size:
706       length = addressSpace.getULEB128(p, instructionsEnd);
707       results->spExtraArgSize = (uint32_t)length;
708       _LIBUNWIND_TRACE_DWARF("DW_CFA_GNU_args_size(%" PRIu64 ")\n", length);
709       break;
710     case DW_CFA_GNU_negative_offset_extended:
711       reg = addressSpace.getULEB128(p, instructionsEnd);
712       if (reg > kMaxRegisterNumber) {
713         _LIBUNWIND_LOG0("malformed DW_CFA_GNU_negative_offset_extended DWARF "
714                         "unwind, reg too big");
715         return false;
716       }
717       offset = (int64_t)addressSpace.getULEB128(p, instructionsEnd)
718                                                     * cieInfo.dataAlignFactor;
719       results->setRegister(reg, kRegisterInCFA, -offset, initialState);
720       _LIBUNWIND_TRACE_DWARF(
721           "DW_CFA_GNU_negative_offset_extended(%" PRId64 ")\n", offset);
722       break;
723 
724 #if defined(_LIBUNWIND_TARGET_AARCH64) || defined(_LIBUNWIND_TARGET_SPARC)
725     // The same constant is used to represent different instructions on
726     // AArch64 (negate_ra_state) and SPARC (window_save).
727     static_assert(DW_CFA_AARCH64_negate_ra_state == DW_CFA_GNU_window_save,
728                   "uses the same constant");
729     case DW_CFA_AARCH64_negate_ra_state:
730       switch (arch) {
731 #if defined(_LIBUNWIND_TARGET_AARCH64)
732         case REGISTERS_ARM64: {
733           int64_t value =
734               results->savedRegisters[UNW_ARM64_RA_SIGN_STATE].value ^ 0x1;
735           results->setRegisterValue(UNW_ARM64_RA_SIGN_STATE, value, initialState);
736           _LIBUNWIND_TRACE_DWARF("DW_CFA_AARCH64_negate_ra_state\n");
737         } break;
738 #endif
739 
740 #if defined(_LIBUNWIND_TARGET_SPARC)
741       // case DW_CFA_GNU_window_save:
742       case REGISTERS_SPARC:
743         _LIBUNWIND_TRACE_DWARF("DW_CFA_GNU_window_save()\n");
744         for (reg = UNW_SPARC_O0; reg <= UNW_SPARC_O7; reg++) {
745           results->setRegister(reg, kRegisterInRegister,
746                                ((int64_t)reg - UNW_SPARC_O0) + UNW_SPARC_I0,
747                                initialState);
748         }
749 
750         for (reg = UNW_SPARC_L0; reg <= UNW_SPARC_I7; reg++) {
751           results->setRegister(reg, kRegisterInCFA,
752                                ((int64_t)reg - UNW_SPARC_L0) * 4, initialState);
753         }
754         break;
755 #endif
756       }
757       break;
758 #else
759       (void)arch;
760 #endif
761 
762     default:
763       operand = opcode & 0x3F;
764       switch (opcode & 0xC0) {
765       case DW_CFA_offset:
766         reg = operand;
767         if (reg > kMaxRegisterNumber) {
768           _LIBUNWIND_LOG("malformed DW_CFA_offset DWARF unwind, reg (%" PRIu64
769                          ") out of range",
770                   reg);
771           return false;
772         }
773         offset = (int64_t)addressSpace.getULEB128(p, instructionsEnd)
774                                                     * cieInfo.dataAlignFactor;
775         results->setRegister(reg, kRegisterInCFA, offset, initialState);
776         _LIBUNWIND_TRACE_DWARF("DW_CFA_offset(reg=%d, offset=%" PRId64 ")\n",
777                                operand, offset);
778         break;
779       case DW_CFA_advance_loc:
780         codeOffset += operand * cieInfo.codeAlignFactor;
781         _LIBUNWIND_TRACE_DWARF("DW_CFA_advance_loc: new offset=%" PRIu64 "\n",
782                                static_cast<uint64_t>(codeOffset));
783         break;
784       case DW_CFA_restore:
785         reg = operand;
786         if (reg > kMaxRegisterNumber) {
787           _LIBUNWIND_LOG("malformed DW_CFA_restore DWARF unwind, reg (%" PRIu64
788                          ") out of range",
789                   reg);
790           return false;
791         }
792         results->restoreRegisterToInitialState(reg, initialState);
793         _LIBUNWIND_TRACE_DWARF("DW_CFA_restore(reg=%" PRIu64 ")\n",
794                                static_cast<uint64_t>(operand));
795         break;
796       default:
797         _LIBUNWIND_TRACE_DWARF("unknown CFA opcode 0x%02X\n", opcode);
798         return false;
799       }
800     }
801   }
802 
803   return true;
804 }
805 
806 } // namespace libunwind
807 
808 #endif // __DWARF_PARSER_HPP__
809