1 //===-- UnwindAssemblyInstEmulation.cpp -----------------------------------===//
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 "UnwindAssemblyInstEmulation.h"
10 
11 #include "lldb/Core/Address.h"
12 #include "lldb/Core/Disassembler.h"
13 #include "lldb/Core/DumpDataExtractor.h"
14 #include "lldb/Core/DumpRegisterValue.h"
15 #include "lldb/Core/FormatEntity.h"
16 #include "lldb/Core/PluginManager.h"
17 #include "lldb/Target/ExecutionContext.h"
18 #include "lldb/Target/Process.h"
19 #include "lldb/Target/Target.h"
20 #include "lldb/Target/Thread.h"
21 #include "lldb/Utility/ArchSpec.h"
22 #include "lldb/Utility/DataBufferHeap.h"
23 #include "lldb/Utility/DataExtractor.h"
24 #include "lldb/Utility/LLDBLog.h"
25 #include "lldb/Utility/Log.h"
26 #include "lldb/Utility/Status.h"
27 #include "lldb/Utility/StreamString.h"
28 
29 using namespace lldb;
30 using namespace lldb_private;
31 
32 LLDB_PLUGIN_DEFINE(UnwindAssemblyInstEmulation)
33 
34 //  UnwindAssemblyInstEmulation method definitions
35 
36 bool UnwindAssemblyInstEmulation::GetNonCallSiteUnwindPlanFromAssembly(
37     AddressRange &range, Thread &thread, UnwindPlan &unwind_plan) {
38   std::vector<uint8_t> function_text(range.GetByteSize());
39   ProcessSP process_sp(thread.GetProcess());
40   if (process_sp) {
41     Status error;
42     const bool force_live_memory = true;
43     if (process_sp->GetTarget().ReadMemory(
44             range.GetBaseAddress(), function_text.data(), range.GetByteSize(),
45             error, force_live_memory) != range.GetByteSize()) {
46       return false;
47     }
48   }
49   return GetNonCallSiteUnwindPlanFromAssembly(
50       range, function_text.data(), function_text.size(), unwind_plan);
51 }
52 
53 bool UnwindAssemblyInstEmulation::GetNonCallSiteUnwindPlanFromAssembly(
54     AddressRange &range, uint8_t *opcode_data, size_t opcode_size,
55     UnwindPlan &unwind_plan) {
56   if (opcode_data == nullptr || opcode_size == 0)
57     return false;
58 
59   if (range.GetByteSize() > 0 && range.GetBaseAddress().IsValid() &&
60       m_inst_emulator_up.get()) {
61 
62     // The instruction emulation subclass setup the unwind plan for the first
63     // instruction.
64     m_inst_emulator_up->CreateFunctionEntryUnwind(unwind_plan);
65 
66     // CreateFunctionEntryUnwind should have created the first row. If it
67     // doesn't, then we are done.
68     if (unwind_plan.GetRowCount() == 0)
69       return false;
70 
71     const bool prefer_file_cache = true;
72     DisassemblerSP disasm_sp(Disassembler::DisassembleBytes(
73         m_arch, nullptr, nullptr, range.GetBaseAddress(), opcode_data,
74         opcode_size, 99999, prefer_file_cache));
75 
76     Log *log = GetLog(LLDBLog::Unwind);
77 
78     if (disasm_sp) {
79 
80       m_range_ptr = &range;
81       m_unwind_plan_ptr = &unwind_plan;
82 
83       const uint32_t addr_byte_size = m_arch.GetAddressByteSize();
84       const bool show_address = true;
85       const bool show_bytes = true;
86       const bool show_control_flow_kind = true;
87       m_inst_emulator_up->GetRegisterInfo(unwind_plan.GetRegisterKind(),
88                                           unwind_plan.GetInitialCFARegister(),
89                                           m_cfa_reg_info);
90 
91       m_fp_is_cfa = false;
92       m_register_values.clear();
93       m_pushed_regs.clear();
94 
95       // Initialize the CFA with a known value. In the 32 bit case it will be
96       // 0x80000000, and in the 64 bit case 0x8000000000000000. We use the
97       // address byte size to be safe for any future address sizes
98       m_initial_sp = (1ull << ((addr_byte_size * 8) - 1));
99       RegisterValue cfa_reg_value;
100       cfa_reg_value.SetUInt(m_initial_sp, m_cfa_reg_info.byte_size);
101       SetRegisterValue(m_cfa_reg_info, cfa_reg_value);
102 
103       const InstructionList &inst_list = disasm_sp->GetInstructionList();
104       const size_t num_instructions = inst_list.GetSize();
105 
106       if (num_instructions > 0) {
107         Instruction *inst = inst_list.GetInstructionAtIndex(0).get();
108         const lldb::addr_t base_addr = inst->GetAddress().GetFileAddress();
109 
110         // Map for storing the unwind plan row and the value of the registers
111         // at a given offset. When we see a forward branch we add a new entry
112         // to this map with the actual unwind plan row and register context for
113         // the target address of the branch as the current data have to be
114         // valid for the target address of the branch too if we are in the same
115         // function.
116         std::map<lldb::addr_t, std::pair<UnwindPlan::RowSP, RegisterValueMap>>
117             saved_unwind_states;
118 
119         // Make a copy of the current instruction Row and save it in m_curr_row
120         // so we can add updates as we process the instructions.
121         UnwindPlan::RowSP last_row = unwind_plan.GetLastRow();
122         UnwindPlan::Row *newrow = new UnwindPlan::Row;
123         if (last_row.get())
124           *newrow = *last_row.get();
125         m_curr_row.reset(newrow);
126 
127         // Add the initial state to the save list with offset 0.
128         saved_unwind_states.insert({0, {last_row, m_register_values}});
129 
130         // cache the stack pointer register number (in whatever register
131         // numbering this UnwindPlan uses) for quick reference during
132         // instruction parsing.
133         RegisterInfo sp_reg_info;
134         m_inst_emulator_up->GetRegisterInfo(
135             eRegisterKindGeneric, LLDB_REGNUM_GENERIC_SP, sp_reg_info);
136 
137         // The architecture dependent condition code of the last processed
138         // instruction.
139         EmulateInstruction::InstructionCondition last_condition =
140             EmulateInstruction::UnconditionalCondition;
141         lldb::addr_t condition_block_start_offset = 0;
142 
143         for (size_t idx = 0; idx < num_instructions; ++idx) {
144           m_curr_row_modified = false;
145           m_forward_branch_offset = 0;
146 
147           inst = inst_list.GetInstructionAtIndex(idx).get();
148           if (inst) {
149             lldb::addr_t current_offset =
150                 inst->GetAddress().GetFileAddress() - base_addr;
151             auto it = saved_unwind_states.upper_bound(current_offset);
152             assert(it != saved_unwind_states.begin() &&
153                    "Unwind row for the function entry missing");
154             --it; // Move it to the row corresponding to the current offset
155 
156             // If the offset of m_curr_row don't match with the offset we see
157             // in saved_unwind_states then we have to update m_curr_row and
158             // m_register_values based on the saved values. It is happening
159             // after we processed an epilogue and a return to caller
160             // instruction.
161             if (it->second.first->GetOffset() != m_curr_row->GetOffset()) {
162               UnwindPlan::Row *newrow = new UnwindPlan::Row;
163               *newrow = *it->second.first;
164               m_curr_row.reset(newrow);
165               m_register_values = it->second.second;
166               // re-set the CFA register ivars to match the
167               // new m_curr_row.
168               if (sp_reg_info.name &&
169                   m_curr_row->GetCFAValue().IsRegisterPlusOffset()) {
170                 uint32_t row_cfa_regnum =
171                     m_curr_row->GetCFAValue().GetRegisterNumber();
172                 lldb::RegisterKind row_kind =
173                     m_unwind_plan_ptr->GetRegisterKind();
174                 // set m_cfa_reg_info to the row's CFA reg.
175                 m_inst_emulator_up->GetRegisterInfo(row_kind, row_cfa_regnum,
176                                                     m_cfa_reg_info);
177                 // set m_fp_is_cfa.
178                 if (sp_reg_info.kinds[row_kind] == row_cfa_regnum)
179                   m_fp_is_cfa = false;
180                 else
181                   m_fp_is_cfa = true;
182               }
183             }
184 
185             m_inst_emulator_up->SetInstruction(inst->GetOpcode(),
186                                                inst->GetAddress(), nullptr);
187 
188             if (last_condition !=
189                 m_inst_emulator_up->GetInstructionCondition()) {
190               if (m_inst_emulator_up->GetInstructionCondition() !=
191                       EmulateInstruction::UnconditionalCondition &&
192                   saved_unwind_states.count(current_offset) == 0) {
193                 // If we don't have a saved row for the current offset then
194                 // save our current state because we will have to restore it
195                 // after the conditional block.
196                 auto new_row =
197                     std::make_shared<UnwindPlan::Row>(*m_curr_row.get());
198                 saved_unwind_states.insert(
199                     {current_offset, {new_row, m_register_values}});
200               }
201 
202               // If the last instruction was conditional with a different
203               // condition then the then current condition then restore the
204               // condition.
205               if (last_condition !=
206                   EmulateInstruction::UnconditionalCondition) {
207                 const auto &saved_state =
208                     saved_unwind_states.at(condition_block_start_offset);
209                 m_curr_row =
210                     std::make_shared<UnwindPlan::Row>(*saved_state.first);
211                 m_curr_row->SetOffset(current_offset);
212                 m_register_values = saved_state.second;
213                 // re-set the CFA register ivars to match the
214                 // new m_curr_row.
215                 if (sp_reg_info.name &&
216                     m_curr_row->GetCFAValue().IsRegisterPlusOffset()) {
217                   uint32_t row_cfa_regnum =
218                       m_curr_row->GetCFAValue().GetRegisterNumber();
219                   lldb::RegisterKind row_kind =
220                       m_unwind_plan_ptr->GetRegisterKind();
221                   // set m_cfa_reg_info to the row's CFA reg.
222                   m_inst_emulator_up->GetRegisterInfo(row_kind, row_cfa_regnum,
223                                                       m_cfa_reg_info);
224                   // set m_fp_is_cfa.
225                   if (sp_reg_info.kinds[row_kind] == row_cfa_regnum)
226                     m_fp_is_cfa = false;
227                   else
228                     m_fp_is_cfa = true;
229                 }
230                 bool replace_existing =
231                     true; // The last instruction might already
232                           // created a row for this offset and
233                           // we want to overwrite it.
234                 unwind_plan.InsertRow(
235                     std::make_shared<UnwindPlan::Row>(*m_curr_row),
236                     replace_existing);
237               }
238 
239               // We are starting a new conditional block at the actual offset
240               condition_block_start_offset = current_offset;
241             }
242 
243             if (log && log->GetVerbose()) {
244               StreamString strm;
245               lldb_private::FormatEntity::Entry format;
246               FormatEntity::Parse("${frame.pc}: ", format);
247               inst->Dump(&strm, inst_list.GetMaxOpcocdeByteSize(), show_address,
248                          show_bytes, show_control_flow_kind, nullptr, nullptr,
249                          nullptr, &format, 0);
250               log->PutString(strm.GetString());
251             }
252 
253             last_condition = m_inst_emulator_up->GetInstructionCondition();
254 
255             m_inst_emulator_up->EvaluateInstruction(
256                 eEmulateInstructionOptionIgnoreConditions);
257 
258             // If the current instruction is a branch forward then save the
259             // current CFI information for the offset where we are branching.
260             if (m_forward_branch_offset != 0 &&
261                 range.ContainsFileAddress(inst->GetAddress().GetFileAddress() +
262                                           m_forward_branch_offset)) {
263               auto newrow =
264                   std::make_shared<UnwindPlan::Row>(*m_curr_row.get());
265               newrow->SetOffset(current_offset + m_forward_branch_offset);
266               saved_unwind_states.insert(
267                   {current_offset + m_forward_branch_offset,
268                    {newrow, m_register_values}});
269               unwind_plan.InsertRow(newrow);
270             }
271 
272             // Were there any changes to the CFI while evaluating this
273             // instruction?
274             if (m_curr_row_modified) {
275               // Save the modified row if we don't already have a CFI row in
276               // the current address
277               if (saved_unwind_states.count(
278                       current_offset + inst->GetOpcode().GetByteSize()) == 0) {
279                 m_curr_row->SetOffset(current_offset +
280                                       inst->GetOpcode().GetByteSize());
281                 unwind_plan.InsertRow(m_curr_row);
282                 saved_unwind_states.insert(
283                     {current_offset + inst->GetOpcode().GetByteSize(),
284                      {m_curr_row, m_register_values}});
285 
286                 // Allocate a new Row for m_curr_row, copy the current state
287                 // into it
288                 UnwindPlan::Row *newrow = new UnwindPlan::Row;
289                 *newrow = *m_curr_row.get();
290                 m_curr_row.reset(newrow);
291               }
292             }
293           }
294         }
295       }
296     }
297 
298     if (log && log->GetVerbose()) {
299       StreamString strm;
300       lldb::addr_t base_addr = range.GetBaseAddress().GetFileAddress();
301       strm.Printf("Resulting unwind rows for [0x%" PRIx64 " - 0x%" PRIx64 "):",
302                   base_addr, base_addr + range.GetByteSize());
303       unwind_plan.Dump(strm, nullptr, base_addr);
304       log->PutString(strm.GetString());
305     }
306     return unwind_plan.GetRowCount() > 0;
307   }
308   return false;
309 }
310 
311 bool UnwindAssemblyInstEmulation::AugmentUnwindPlanFromCallSite(
312     AddressRange &func, Thread &thread, UnwindPlan &unwind_plan) {
313   return false;
314 }
315 
316 bool UnwindAssemblyInstEmulation::GetFastUnwindPlan(AddressRange &func,
317                                                     Thread &thread,
318                                                     UnwindPlan &unwind_plan) {
319   return false;
320 }
321 
322 bool UnwindAssemblyInstEmulation::FirstNonPrologueInsn(
323     AddressRange &func, const ExecutionContext &exe_ctx,
324     Address &first_non_prologue_insn) {
325   return false;
326 }
327 
328 UnwindAssembly *
329 UnwindAssemblyInstEmulation::CreateInstance(const ArchSpec &arch) {
330   std::unique_ptr<EmulateInstruction> inst_emulator_up(
331       EmulateInstruction::FindPlugin(arch, eInstructionTypePrologueEpilogue,
332                                      nullptr));
333   // Make sure that all prologue instructions are handled
334   if (inst_emulator_up)
335     return new UnwindAssemblyInstEmulation(arch, inst_emulator_up.release());
336   return nullptr;
337 }
338 
339 void UnwindAssemblyInstEmulation::Initialize() {
340   PluginManager::RegisterPlugin(GetPluginNameStatic(),
341                                 GetPluginDescriptionStatic(), CreateInstance);
342 }
343 
344 void UnwindAssemblyInstEmulation::Terminate() {
345   PluginManager::UnregisterPlugin(CreateInstance);
346 }
347 
348 llvm::StringRef UnwindAssemblyInstEmulation::GetPluginDescriptionStatic() {
349   return "Instruction emulation based unwind information.";
350 }
351 
352 uint64_t UnwindAssemblyInstEmulation::MakeRegisterKindValuePair(
353     const RegisterInfo &reg_info) {
354   lldb::RegisterKind reg_kind;
355   uint32_t reg_num;
356   if (EmulateInstruction::GetBestRegisterKindAndNumber(&reg_info, reg_kind,
357                                                        reg_num))
358     return (uint64_t)reg_kind << 24 | reg_num;
359   return 0ull;
360 }
361 
362 void UnwindAssemblyInstEmulation::SetRegisterValue(
363     const RegisterInfo &reg_info, const RegisterValue &reg_value) {
364   m_register_values[MakeRegisterKindValuePair(reg_info)] = reg_value;
365 }
366 
367 bool UnwindAssemblyInstEmulation::GetRegisterValue(const RegisterInfo &reg_info,
368                                                    RegisterValue &reg_value) {
369   const uint64_t reg_id = MakeRegisterKindValuePair(reg_info);
370   RegisterValueMap::const_iterator pos = m_register_values.find(reg_id);
371   if (pos != m_register_values.end()) {
372     reg_value = pos->second;
373     return true; // We had a real value that comes from an opcode that wrote
374                  // to it...
375   }
376   // We are making up a value that is recognizable...
377   reg_value.SetUInt(reg_id, reg_info.byte_size);
378   return false;
379 }
380 
381 size_t UnwindAssemblyInstEmulation::ReadMemory(
382     EmulateInstruction *instruction, void *baton,
383     const EmulateInstruction::Context &context, lldb::addr_t addr, void *dst,
384     size_t dst_len) {
385   Log *log = GetLog(LLDBLog::Unwind);
386 
387   if (log && log->GetVerbose()) {
388     StreamString strm;
389     strm.Printf(
390         "UnwindAssemblyInstEmulation::ReadMemory    (addr = 0x%16.16" PRIx64
391         ", dst = %p, dst_len = %" PRIu64 ", context = ",
392         addr, dst, (uint64_t)dst_len);
393     context.Dump(strm, instruction);
394     log->PutString(strm.GetString());
395   }
396   memset(dst, 0, dst_len);
397   return dst_len;
398 }
399 
400 size_t UnwindAssemblyInstEmulation::WriteMemory(
401     EmulateInstruction *instruction, void *baton,
402     const EmulateInstruction::Context &context, lldb::addr_t addr,
403     const void *dst, size_t dst_len) {
404   if (baton && dst && dst_len)
405     return ((UnwindAssemblyInstEmulation *)baton)
406         ->WriteMemory(instruction, context, addr, dst, dst_len);
407   return 0;
408 }
409 
410 size_t UnwindAssemblyInstEmulation::WriteMemory(
411     EmulateInstruction *instruction, const EmulateInstruction::Context &context,
412     lldb::addr_t addr, const void *dst, size_t dst_len) {
413   DataExtractor data(dst, dst_len,
414                      instruction->GetArchitecture().GetByteOrder(),
415                      instruction->GetArchitecture().GetAddressByteSize());
416 
417   Log *log = GetLog(LLDBLog::Unwind);
418 
419   if (log && log->GetVerbose()) {
420     StreamString strm;
421 
422     strm.PutCString("UnwindAssemblyInstEmulation::WriteMemory   (");
423     DumpDataExtractor(data, &strm, 0, eFormatBytes, 1, dst_len, UINT32_MAX,
424                       addr, 0, 0);
425     strm.PutCString(", context = ");
426     context.Dump(strm, instruction);
427     log->PutString(strm.GetString());
428   }
429 
430   const bool cant_replace = false;
431 
432   switch (context.type) {
433   default:
434   case EmulateInstruction::eContextInvalid:
435   case EmulateInstruction::eContextReadOpcode:
436   case EmulateInstruction::eContextImmediate:
437   case EmulateInstruction::eContextAdjustBaseRegister:
438   case EmulateInstruction::eContextRegisterPlusOffset:
439   case EmulateInstruction::eContextAdjustPC:
440   case EmulateInstruction::eContextRegisterStore:
441   case EmulateInstruction::eContextRegisterLoad:
442   case EmulateInstruction::eContextRelativeBranchImmediate:
443   case EmulateInstruction::eContextAbsoluteBranchRegister:
444   case EmulateInstruction::eContextSupervisorCall:
445   case EmulateInstruction::eContextTableBranchReadMemory:
446   case EmulateInstruction::eContextWriteRegisterRandomBits:
447   case EmulateInstruction::eContextWriteMemoryRandomBits:
448   case EmulateInstruction::eContextArithmetic:
449   case EmulateInstruction::eContextAdvancePC:
450   case EmulateInstruction::eContextReturnFromException:
451   case EmulateInstruction::eContextPopRegisterOffStack:
452   case EmulateInstruction::eContextAdjustStackPointer:
453     break;
454 
455   case EmulateInstruction::eContextPushRegisterOnStack: {
456     uint32_t reg_num = LLDB_INVALID_REGNUM;
457     uint32_t generic_regnum = LLDB_INVALID_REGNUM;
458     assert(context.info_type ==
459                EmulateInstruction::eInfoTypeRegisterToRegisterPlusOffset &&
460            "unhandled case, add code to handle this!");
461     const uint32_t unwind_reg_kind = m_unwind_plan_ptr->GetRegisterKind();
462     reg_num = context.info.RegisterToRegisterPlusOffset.data_reg
463                   .kinds[unwind_reg_kind];
464     generic_regnum = context.info.RegisterToRegisterPlusOffset.data_reg
465                          .kinds[eRegisterKindGeneric];
466 
467     if (reg_num != LLDB_INVALID_REGNUM &&
468         generic_regnum != LLDB_REGNUM_GENERIC_SP) {
469       if (m_pushed_regs.find(reg_num) == m_pushed_regs.end()) {
470         m_pushed_regs[reg_num] = addr;
471         const int32_t offset = addr - m_initial_sp;
472         m_curr_row->SetRegisterLocationToAtCFAPlusOffset(reg_num, offset,
473                                                          cant_replace);
474         m_curr_row_modified = true;
475       }
476     }
477   } break;
478   }
479 
480   return dst_len;
481 }
482 
483 bool UnwindAssemblyInstEmulation::ReadRegister(EmulateInstruction *instruction,
484                                                void *baton,
485                                                const RegisterInfo *reg_info,
486                                                RegisterValue &reg_value) {
487 
488   if (baton && reg_info)
489     return ((UnwindAssemblyInstEmulation *)baton)
490         ->ReadRegister(instruction, reg_info, reg_value);
491   return false;
492 }
493 bool UnwindAssemblyInstEmulation::ReadRegister(EmulateInstruction *instruction,
494                                                const RegisterInfo *reg_info,
495                                                RegisterValue &reg_value) {
496   bool synthetic = GetRegisterValue(*reg_info, reg_value);
497 
498   Log *log = GetLog(LLDBLog::Unwind);
499 
500   if (log && log->GetVerbose()) {
501 
502     StreamString strm;
503     strm.Printf("UnwindAssemblyInstEmulation::ReadRegister  (name = \"%s\") => "
504                 "synthetic_value = %i, value = ",
505                 reg_info->name, synthetic);
506     DumpRegisterValue(reg_value, &strm, reg_info, false, false, eFormatDefault);
507     log->PutString(strm.GetString());
508   }
509   return true;
510 }
511 
512 bool UnwindAssemblyInstEmulation::WriteRegister(
513     EmulateInstruction *instruction, void *baton,
514     const EmulateInstruction::Context &context, const RegisterInfo *reg_info,
515     const RegisterValue &reg_value) {
516   if (baton && reg_info)
517     return ((UnwindAssemblyInstEmulation *)baton)
518         ->WriteRegister(instruction, context, reg_info, reg_value);
519   return false;
520 }
521 bool UnwindAssemblyInstEmulation::WriteRegister(
522     EmulateInstruction *instruction, const EmulateInstruction::Context &context,
523     const RegisterInfo *reg_info, const RegisterValue &reg_value) {
524   Log *log = GetLog(LLDBLog::Unwind);
525 
526   if (log && log->GetVerbose()) {
527 
528     StreamString strm;
529     strm.Printf(
530         "UnwindAssemblyInstEmulation::WriteRegister (name = \"%s\", value = ",
531         reg_info->name);
532     DumpRegisterValue(reg_value, &strm, reg_info, false, false, eFormatDefault);
533     strm.PutCString(", context = ");
534     context.Dump(strm, instruction);
535     log->PutString(strm.GetString());
536   }
537 
538   SetRegisterValue(*reg_info, reg_value);
539 
540   switch (context.type) {
541   case EmulateInstruction::eContextInvalid:
542   case EmulateInstruction::eContextReadOpcode:
543   case EmulateInstruction::eContextImmediate:
544   case EmulateInstruction::eContextAdjustBaseRegister:
545   case EmulateInstruction::eContextRegisterPlusOffset:
546   case EmulateInstruction::eContextAdjustPC:
547   case EmulateInstruction::eContextRegisterStore:
548   case EmulateInstruction::eContextSupervisorCall:
549   case EmulateInstruction::eContextTableBranchReadMemory:
550   case EmulateInstruction::eContextWriteRegisterRandomBits:
551   case EmulateInstruction::eContextWriteMemoryRandomBits:
552   case EmulateInstruction::eContextAdvancePC:
553   case EmulateInstruction::eContextReturnFromException:
554   case EmulateInstruction::eContextPushRegisterOnStack:
555   case EmulateInstruction::eContextRegisterLoad:
556     //            {
557     //                const uint32_t reg_num =
558     //                reg_info->kinds[m_unwind_plan_ptr->GetRegisterKind()];
559     //                if (reg_num != LLDB_INVALID_REGNUM)
560     //                {
561     //                    const bool can_replace_only_if_unspecified = true;
562     //
563     //                    m_curr_row.SetRegisterLocationToUndefined (reg_num,
564     //                                                               can_replace_only_if_unspecified,
565     //                                                               can_replace_only_if_unspecified);
566     //                    m_curr_row_modified = true;
567     //                }
568     //            }
569     break;
570 
571   case EmulateInstruction::eContextArithmetic: {
572     // If we adjusted the current frame pointer by a constant then adjust the
573     // CFA offset
574     // with the same amount.
575     lldb::RegisterKind kind = m_unwind_plan_ptr->GetRegisterKind();
576     if (m_fp_is_cfa && reg_info->kinds[kind] == m_cfa_reg_info.kinds[kind] &&
577         context.info_type == EmulateInstruction::eInfoTypeRegisterPlusOffset &&
578         context.info.RegisterPlusOffset.reg.kinds[kind] ==
579             m_cfa_reg_info.kinds[kind]) {
580       const int64_t offset = context.info.RegisterPlusOffset.signed_offset;
581       m_curr_row->GetCFAValue().IncOffset(-1 * offset);
582       m_curr_row_modified = true;
583     }
584   } break;
585 
586   case EmulateInstruction::eContextAbsoluteBranchRegister:
587   case EmulateInstruction::eContextRelativeBranchImmediate: {
588     if (context.info_type == EmulateInstruction::eInfoTypeISAAndImmediate &&
589         context.info.ISAAndImmediate.unsigned_data32 > 0) {
590       m_forward_branch_offset =
591           context.info.ISAAndImmediateSigned.signed_data32;
592     } else if (context.info_type ==
593                    EmulateInstruction::eInfoTypeISAAndImmediateSigned &&
594                context.info.ISAAndImmediateSigned.signed_data32 > 0) {
595       m_forward_branch_offset = context.info.ISAAndImmediate.unsigned_data32;
596     } else if (context.info_type == EmulateInstruction::eInfoTypeImmediate &&
597                context.info.unsigned_immediate > 0) {
598       m_forward_branch_offset = context.info.unsigned_immediate;
599     } else if (context.info_type ==
600                    EmulateInstruction::eInfoTypeImmediateSigned &&
601                context.info.signed_immediate > 0) {
602       m_forward_branch_offset = context.info.signed_immediate;
603     }
604   } break;
605 
606   case EmulateInstruction::eContextPopRegisterOffStack: {
607     const uint32_t reg_num =
608         reg_info->kinds[m_unwind_plan_ptr->GetRegisterKind()];
609     const uint32_t generic_regnum = reg_info->kinds[eRegisterKindGeneric];
610     if (reg_num != LLDB_INVALID_REGNUM &&
611         generic_regnum != LLDB_REGNUM_GENERIC_SP) {
612       switch (context.info_type) {
613       case EmulateInstruction::eInfoTypeAddress:
614         if (m_pushed_regs.find(reg_num) != m_pushed_regs.end() &&
615             context.info.address == m_pushed_regs[reg_num]) {
616           m_curr_row->SetRegisterLocationToSame(reg_num,
617                                                 false /*must_replace*/);
618           m_curr_row_modified = true;
619 
620           // FP has been restored to its original value, we are back
621           // to using SP to calculate the CFA.
622           if (m_fp_is_cfa) {
623             m_fp_is_cfa = false;
624             RegisterInfo sp_reg_info;
625             lldb::RegisterKind sp_reg_kind = eRegisterKindGeneric;
626             uint32_t sp_reg_num = LLDB_REGNUM_GENERIC_SP;
627             m_inst_emulator_up->GetRegisterInfo(sp_reg_kind, sp_reg_num,
628                                                 sp_reg_info);
629             RegisterValue sp_reg_val;
630             if (GetRegisterValue(sp_reg_info, sp_reg_val)) {
631               m_cfa_reg_info = sp_reg_info;
632               const uint32_t cfa_reg_num =
633                   sp_reg_info.kinds[m_unwind_plan_ptr->GetRegisterKind()];
634               assert(cfa_reg_num != LLDB_INVALID_REGNUM);
635               m_curr_row->GetCFAValue().SetIsRegisterPlusOffset(
636                   cfa_reg_num, m_initial_sp - sp_reg_val.GetAsUInt64());
637             }
638           }
639         }
640         break;
641       case EmulateInstruction::eInfoTypeISA:
642         assert(
643             (generic_regnum == LLDB_REGNUM_GENERIC_PC ||
644              generic_regnum == LLDB_REGNUM_GENERIC_FLAGS) &&
645             "eInfoTypeISA used for popping a register other the PC/FLAGS");
646         if (generic_regnum != LLDB_REGNUM_GENERIC_FLAGS) {
647           m_curr_row->SetRegisterLocationToSame(reg_num,
648                                                 false /*must_replace*/);
649           m_curr_row_modified = true;
650         }
651         break;
652       default:
653         assert(false && "unhandled case, add code to handle this!");
654         break;
655       }
656     }
657   } break;
658 
659   case EmulateInstruction::eContextSetFramePointer:
660     if (!m_fp_is_cfa) {
661       m_fp_is_cfa = true;
662       m_cfa_reg_info = *reg_info;
663       const uint32_t cfa_reg_num =
664           reg_info->kinds[m_unwind_plan_ptr->GetRegisterKind()];
665       assert(cfa_reg_num != LLDB_INVALID_REGNUM);
666       m_curr_row->GetCFAValue().SetIsRegisterPlusOffset(
667           cfa_reg_num, m_initial_sp - reg_value.GetAsUInt64());
668       m_curr_row_modified = true;
669     }
670     break;
671 
672   case EmulateInstruction::eContextRestoreStackPointer:
673     if (m_fp_is_cfa) {
674       m_fp_is_cfa = false;
675       m_cfa_reg_info = *reg_info;
676       const uint32_t cfa_reg_num =
677           reg_info->kinds[m_unwind_plan_ptr->GetRegisterKind()];
678       assert(cfa_reg_num != LLDB_INVALID_REGNUM);
679       m_curr_row->GetCFAValue().SetIsRegisterPlusOffset(
680           cfa_reg_num, m_initial_sp - reg_value.GetAsUInt64());
681       m_curr_row_modified = true;
682     }
683     break;
684 
685   case EmulateInstruction::eContextAdjustStackPointer:
686     // If we have created a frame using the frame pointer, don't follow
687     // subsequent adjustments to the stack pointer.
688     if (!m_fp_is_cfa) {
689       m_curr_row->GetCFAValue().SetIsRegisterPlusOffset(
690           m_curr_row->GetCFAValue().GetRegisterNumber(),
691           m_initial_sp - reg_value.GetAsUInt64());
692       m_curr_row_modified = true;
693     }
694     break;
695   }
696   return true;
697 }
698