1 //===-- UnwindAssemblyInstEmulation.cpp --------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "UnwindAssemblyInstEmulation.h"
12 #include "lldb/Core/Address.h"
13 #include "lldb/Core/ArchSpec.h"
14 #include "lldb/Core/DataBufferHeap.h"
15 #include "lldb/Core/DataExtractor.h"
16 #include "lldb/Core/Disassembler.h"
17 #include "lldb/Core/Error.h"
18 #include "lldb/Core/Log.h"
19 #include "lldb/Core/PluginManager.h"
20 #include "lldb/Core/StreamString.h"
21 #include "lldb/Target/ExecutionContext.h"
22 #include "lldb/Target/Process.h"
23 #include "lldb/Target/Thread.h"
24 #include "lldb/Target/Target.h"
27 using namespace lldb_private;
31 //-----------------------------------------------------------------------------------------------
32 // UnwindAssemblyInstEmulation method definitions
33 //-----------------------------------------------------------------------------------------------
36 UnwindAssemblyInstEmulation::GetNonCallSiteUnwindPlanFromAssembly (AddressRange& range,
38 UnwindPlan& unwind_plan)
40 if (range.GetByteSize() > 0 &&
41 range.GetBaseAddress().IsValid() &&
42 m_inst_emulator_ap.get())
45 // The instruction emulation subclass setup the unwind plan for the
47 m_inst_emulator_ap->CreateFunctionEntryUnwind (unwind_plan);
49 // CreateFunctionEntryUnwind should have created the first row. If it
50 // doesn't, then we are done.
51 if (unwind_plan.GetRowCount() == 0)
54 ExecutionContext exe_ctx;
55 thread.CalculateExecutionContext(exe_ctx);
56 const bool prefer_file_cache = true;
57 DisassemblerSP disasm_sp (Disassembler::DisassembleRange (m_arch,
64 Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_UNWIND));
70 m_thread_ptr = &thread;
71 m_unwind_plan_ptr = &unwind_plan;
73 const uint32_t addr_byte_size = m_arch.GetAddressByteSize();
74 const bool show_address = true;
75 const bool show_bytes = true;
76 m_inst_emulator_ap->GetRegisterInfo (unwind_plan.GetRegisterKind(),
77 unwind_plan.GetInitialCFARegister(),
81 m_register_values.clear();
82 m_pushed_regs.clear();
84 // Initialize the CFA with a known value. In the 32 bit case
85 // it will be 0x80000000, and in the 64 bit case 0x8000000000000000.
86 // We use the address byte size to be safe for any future address sizes
87 m_initial_sp = (1ull << ((addr_byte_size * 8) - 1));
88 RegisterValue cfa_reg_value;
89 cfa_reg_value.SetUInt (m_initial_sp, m_cfa_reg_info.byte_size);
90 SetRegisterValue (m_cfa_reg_info, cfa_reg_value);
92 const InstructionList &inst_list = disasm_sp->GetInstructionList ();
93 const size_t num_instructions = inst_list.GetSize();
95 if (num_instructions > 0)
97 Instruction *inst = inst_list.GetInstructionAtIndex (0).get();
98 const addr_t base_addr = inst->GetAddress().GetFileAddress();
100 // Make a copy of the current instruction Row and save it in m_curr_row
101 // so we can add updates as we process the instructions.
102 UnwindPlan::RowSP last_row = unwind_plan.GetLastRow();
103 UnwindPlan::Row *newrow = new UnwindPlan::Row;
105 *newrow = *last_row.get();
106 m_curr_row.reset(newrow);
108 // Once we've seen the initial prologue instructions complete, save a
109 // copy of the CFI at that point into prologue_completed_row for possible
111 int instructions_since_last_prologue_insn = 0; // # of insns since last CFI was update
113 bool reinstate_prologue_next_instruction = false; // Next iteration, re-install the prologue row of CFI
115 bool last_instruction_restored_return_addr_reg = false; // re-install the prologue row of CFI if the next instruction is a branch immediate
117 bool return_address_register_has_been_saved = false; // if we've seen the ra register get saved yet
119 UnwindPlan::RowSP prologue_completed_row; // copy of prologue row of CFI
121 // cache the pc register number (in whatever register numbering this UnwindPlan uses) for
122 // quick reference during instruction parsing.
123 uint32_t pc_reg_num = LLDB_INVALID_REGNUM;
124 RegisterInfo pc_reg_info;
125 if (m_inst_emulator_ap->GetRegisterInfo (eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC, pc_reg_info))
126 pc_reg_num = pc_reg_info.kinds[unwind_plan.GetRegisterKind()];
128 pc_reg_num = LLDB_INVALID_REGNUM;
130 // cache the return address register number (in whatever register numbering this UnwindPlan uses) for
131 // quick reference during instruction parsing.
132 uint32_t ra_reg_num = LLDB_INVALID_REGNUM;
133 RegisterInfo ra_reg_info;
134 if (m_inst_emulator_ap->GetRegisterInfo (eRegisterKindGeneric, LLDB_REGNUM_GENERIC_RA, ra_reg_info))
135 ra_reg_num = ra_reg_info.kinds[unwind_plan.GetRegisterKind()];
137 ra_reg_num = LLDB_INVALID_REGNUM;
139 for (size_t idx=0; idx<num_instructions; ++idx)
141 m_curr_row_modified = false;
142 m_curr_insn_restored_a_register = false;
143 inst = inst_list.GetInstructionAtIndex (idx).get();
146 if (log && log->GetVerbose ())
149 const char *disassemble_format = "${frame.pc}: ";
150 inst->Dump(&strm, inst_list.GetMaxOpcocdeByteSize (), show_address, show_bytes, NULL, NULL, NULL, disassemble_format);
151 log->PutCString (strm.GetData());
154 m_inst_emulator_ap->SetInstruction (inst->GetOpcode(),
156 exe_ctx.GetTargetPtr());
158 m_inst_emulator_ap->EvaluateInstruction (eEmulateInstructionOptionIgnoreConditions);
160 // Were there any changes to the CFI while evaluating this instruction?
161 if (m_curr_row_modified)
163 reinstate_prologue_next_instruction = false;
164 m_curr_row->SetOffset (inst->GetAddress().GetFileAddress() + inst->GetOpcode().GetByteSize() - base_addr);
165 // Append the new row
166 unwind_plan.AppendRow (m_curr_row);
168 // Allocate a new Row for m_curr_row, copy the current state into it
169 UnwindPlan::Row *newrow = new UnwindPlan::Row;
170 *newrow = *m_curr_row.get();
171 m_curr_row.reset(newrow);
173 // If m_curr_insn_restored_a_register == true, we're looking at an epilogue instruction.
174 // Set instructions_since_last_prologue_insn to a very high number so we don't append
175 // any of these epilogue instructions to our prologue_complete row.
176 if (m_curr_insn_restored_a_register == false && instructions_since_last_prologue_insn < 8)
177 instructions_since_last_prologue_insn = 0;
179 instructions_since_last_prologue_insn = 99;
181 UnwindPlan::Row::RegisterLocation pc_regloc;
182 UnwindPlan::Row::RegisterLocation ra_regloc;
184 // While parsing the instructions of this function, if we've ever
185 // seen the return address register (aka lr on arm) in a non-IsSame() state,
186 // it has been saved on the stack. If it's ever back to IsSame(), we've
187 // executed an epilogue.
188 if (ra_reg_num != LLDB_INVALID_REGNUM
189 && m_curr_row->GetRegisterInfo (ra_reg_num, ra_regloc)
190 && !ra_regloc.IsSame())
192 return_address_register_has_been_saved = true;
195 // If the caller's pc is "same", we've just executed an epilogue and we return to the caller
196 // after this instruction completes executing.
197 // If there are any instructions past this, there must have been flow control over this
198 // epilogue so we'll reinstate the original prologue setup instructions.
199 if (prologue_completed_row.get()
200 && pc_reg_num != LLDB_INVALID_REGNUM
201 && m_curr_row->GetRegisterInfo (pc_reg_num, pc_regloc)
202 && pc_regloc.IsSame())
204 if (log && log->GetVerbose())
205 log->Printf("UnwindAssemblyInstEmulation::GetNonCallSiteUnwindPlanFromAssembly -- pc is <same>, restore prologue instructions.");
206 reinstate_prologue_next_instruction = true;
208 else if (prologue_completed_row.get()
209 && return_address_register_has_been_saved
210 && ra_reg_num != LLDB_INVALID_REGNUM
211 && m_curr_row->GetRegisterInfo (ra_reg_num, ra_regloc)
212 && ra_regloc.IsSame())
214 if (log && log->GetVerbose())
215 log->Printf("UnwindAssemblyInstEmulation::GetNonCallSiteUnwindPlanFromAssembly -- lr is <same>, restore prologue instruction if the next instruction is a branch immediate.");
216 last_instruction_restored_return_addr_reg = true;
221 // If the previous instruction was a return-to-caller (epilogue), and we're still executing
222 // instructions in this function, there must be a code path that jumps over that epilogue.
223 // Also detect the case where we epilogue & branch imm to another function (tail-call opt)
224 // instead of a normal pop lr-into-pc exit.
225 // Reinstate the frame setup from the prologue.
226 if (reinstate_prologue_next_instruction
227 || (m_curr_insn_is_branch_immediate && last_instruction_restored_return_addr_reg))
229 if (log && log->GetVerbose())
230 log->Printf("UnwindAssemblyInstEmulation::GetNonCallSiteUnwindPlanFromAssembly -- Reinstating prologue instruction set");
231 UnwindPlan::Row *newrow = new UnwindPlan::Row;
232 *newrow = *prologue_completed_row.get();
233 m_curr_row.reset(newrow);
234 m_curr_row->SetOffset (inst->GetAddress().GetFileAddress() + inst->GetOpcode().GetByteSize() - base_addr);
235 unwind_plan.AppendRow(m_curr_row);
237 newrow = new UnwindPlan::Row;
238 *newrow = *m_curr_row.get();
239 m_curr_row.reset(newrow);
241 reinstate_prologue_next_instruction = false;
242 last_instruction_restored_return_addr_reg = false;
243 m_curr_insn_is_branch_immediate = false;
246 // clear both of these if either one wasn't set
247 if (last_instruction_restored_return_addr_reg)
249 last_instruction_restored_return_addr_reg = false;
251 if (m_curr_insn_is_branch_immediate)
253 m_curr_insn_is_branch_immediate = false;
256 // Stop updating the prologue instructions if we've seen 8 non-prologue instructions
258 if (instructions_since_last_prologue_insn++ < 8)
260 UnwindPlan::Row *newrow = new UnwindPlan::Row;
261 *newrow = *m_curr_row.get();
262 prologue_completed_row.reset(newrow);
263 if (log && log->GetVerbose())
264 log->Printf("UnwindAssemblyInstEmulation::GetNonCallSiteUnwindPlanFromAssembly -- saving a copy of the current row as the prologue row.");
270 // FIXME: The DisassemblerLLVMC has a reference cycle and won't go away if it has any active instructions.
271 // I'll fix that but for now, just clear the list and it will go away nicely.
272 disasm_sp->GetInstructionList().Clear();
275 if (log && log->GetVerbose ())
278 lldb::addr_t base_addr = range.GetBaseAddress().GetLoadAddress(thread.CalculateTarget().get());
279 strm.Printf ("Resulting unwind rows for [0x%" PRIx64 " - 0x%" PRIx64 "):", base_addr, base_addr + range.GetByteSize());
280 unwind_plan.Dump(strm, &thread, base_addr);
281 log->PutCString (strm.GetData());
283 return unwind_plan.GetRowCount() > 0;
289 UnwindAssemblyInstEmulation::AugmentUnwindPlanFromCallSite (AddressRange& func,
291 UnwindPlan& unwind_plan)
297 UnwindAssemblyInstEmulation::GetFastUnwindPlan (AddressRange& func,
299 UnwindPlan &unwind_plan)
305 UnwindAssemblyInstEmulation::FirstNonPrologueInsn (AddressRange& func,
306 const ExecutionContext &exe_ctx,
307 Address& first_non_prologue_insn)
313 UnwindAssemblyInstEmulation::CreateInstance (const ArchSpec &arch)
315 std::unique_ptr<EmulateInstruction> inst_emulator_ap (EmulateInstruction::FindPlugin (arch, eInstructionTypePrologueEpilogue, NULL));
316 // Make sure that all prologue instructions are handled
317 if (inst_emulator_ap.get())
318 return new UnwindAssemblyInstEmulation (arch, inst_emulator_ap.release());
323 //------------------------------------------------------------------
324 // PluginInterface protocol in UnwindAssemblyParser_x86
325 //------------------------------------------------------------------
327 UnwindAssemblyInstEmulation::GetPluginName()
329 return GetPluginNameStatic();
333 UnwindAssemblyInstEmulation::GetPluginVersion()
339 UnwindAssemblyInstEmulation::Initialize()
341 PluginManager::RegisterPlugin (GetPluginNameStatic(),
342 GetPluginDescriptionStatic(),
347 UnwindAssemblyInstEmulation::Terminate()
349 PluginManager::UnregisterPlugin (CreateInstance);
354 UnwindAssemblyInstEmulation::GetPluginNameStatic()
356 static ConstString g_name("inst-emulation");
361 UnwindAssemblyInstEmulation::GetPluginDescriptionStatic()
363 return "Instruction emulation based unwind information.";
368 UnwindAssemblyInstEmulation::MakeRegisterKindValuePair (const RegisterInfo ®_info)
370 lldb::RegisterKind reg_kind;
372 if (EmulateInstruction::GetBestRegisterKindAndNumber (®_info, reg_kind, reg_num))
373 return (uint64_t)reg_kind << 24 | reg_num;
378 UnwindAssemblyInstEmulation::SetRegisterValue (const RegisterInfo ®_info, const RegisterValue ®_value)
380 m_register_values[MakeRegisterKindValuePair (reg_info)] = reg_value;
384 UnwindAssemblyInstEmulation::GetRegisterValue (const RegisterInfo ®_info, RegisterValue ®_value)
386 const uint64_t reg_id = MakeRegisterKindValuePair (reg_info);
387 RegisterValueMap::const_iterator pos = m_register_values.find(reg_id);
388 if (pos != m_register_values.end())
390 reg_value = pos->second;
391 return true; // We had a real value that comes from an opcode that wrote
394 // We are making up a value that is recognizable...
395 reg_value.SetUInt(reg_id, reg_info.byte_size);
401 UnwindAssemblyInstEmulation::ReadMemory (EmulateInstruction *instruction,
403 const EmulateInstruction::Context &context,
408 Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_UNWIND));
410 if (log && log->GetVerbose ())
413 strm.Printf ("UnwindAssemblyInstEmulation::ReadMemory (addr = 0x%16.16" PRIx64 ", dst = %p, dst_len = %" PRIu64 ", context = ",
417 context.Dump(strm, instruction);
418 log->PutCString (strm.GetData ());
420 memset (dst, 0, dst_len);
425 UnwindAssemblyInstEmulation::WriteMemory (EmulateInstruction *instruction,
427 const EmulateInstruction::Context &context,
432 if (baton && dst && dst_len)
433 return ((UnwindAssemblyInstEmulation *)baton)->WriteMemory (instruction, context, addr, dst, dst_len);
438 UnwindAssemblyInstEmulation::WriteMemory (EmulateInstruction *instruction,
439 const EmulateInstruction::Context &context,
444 DataExtractor data (dst,
446 instruction->GetArchitecture ().GetByteOrder(),
447 instruction->GetArchitecture ().GetAddressByteSize());
449 Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_UNWIND));
451 if (log && log->GetVerbose ())
455 strm.PutCString ("UnwindAssemblyInstEmulation::WriteMemory (");
456 data.Dump(&strm, 0, eFormatBytes, 1, dst_len, UINT32_MAX, addr, 0, 0);
457 strm.PutCString (", context = ");
458 context.Dump(strm, instruction);
459 log->PutCString (strm.GetData());
462 const bool can_replace = true;
463 const bool cant_replace = false;
465 switch (context.type)
468 case EmulateInstruction::eContextInvalid:
469 case EmulateInstruction::eContextReadOpcode:
470 case EmulateInstruction::eContextImmediate:
471 case EmulateInstruction::eContextAdjustBaseRegister:
472 case EmulateInstruction::eContextRegisterPlusOffset:
473 case EmulateInstruction::eContextAdjustPC:
474 case EmulateInstruction::eContextRegisterStore:
475 case EmulateInstruction::eContextRegisterLoad:
476 case EmulateInstruction::eContextRelativeBranchImmediate:
477 case EmulateInstruction::eContextAbsoluteBranchRegister:
478 case EmulateInstruction::eContextSupervisorCall:
479 case EmulateInstruction::eContextTableBranchReadMemory:
480 case EmulateInstruction::eContextWriteRegisterRandomBits:
481 case EmulateInstruction::eContextWriteMemoryRandomBits:
482 case EmulateInstruction::eContextArithmetic:
483 case EmulateInstruction::eContextAdvancePC:
484 case EmulateInstruction::eContextReturnFromException:
485 case EmulateInstruction::eContextPopRegisterOffStack:
486 case EmulateInstruction::eContextAdjustStackPointer:
489 case EmulateInstruction::eContextPushRegisterOnStack:
491 uint32_t reg_num = LLDB_INVALID_REGNUM;
492 bool is_return_address_reg = false;
493 const uint32_t unwind_reg_kind = m_unwind_plan_ptr->GetRegisterKind();
494 if (context.info_type == EmulateInstruction::eInfoTypeRegisterToRegisterPlusOffset)
496 reg_num = context.info.RegisterToRegisterPlusOffset.data_reg.kinds[unwind_reg_kind];
497 if (context.info.RegisterToRegisterPlusOffset.data_reg.kinds[eRegisterKindGeneric] == LLDB_REGNUM_GENERIC_RA)
498 is_return_address_reg = true;
502 assert (!"unhandled case, add code to handle this!");
505 if (reg_num != LLDB_INVALID_REGNUM)
507 if (m_pushed_regs.find (reg_num) == m_pushed_regs.end())
509 m_pushed_regs[reg_num] = addr;
510 const int32_t offset = addr - m_initial_sp;
511 m_curr_row->SetRegisterLocationToAtCFAPlusOffset (reg_num, offset, cant_replace);
512 m_curr_row_modified = true;
513 if (is_return_address_reg)
515 // This push was pushing the return address register,
516 // so this is also how we will unwind the PC...
517 RegisterInfo pc_reg_info;
518 if (instruction->GetRegisterInfo (eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC, pc_reg_info))
520 uint32_t pc_reg_num = pc_reg_info.kinds[unwind_reg_kind];
521 if (pc_reg_num != LLDB_INVALID_REGNUM)
523 m_curr_row->SetRegisterLocationToAtCFAPlusOffset (pc_reg_num, offset, can_replace);
524 m_curr_row_modified = true;
539 UnwindAssemblyInstEmulation::ReadRegister (EmulateInstruction *instruction,
541 const RegisterInfo *reg_info,
542 RegisterValue ®_value)
545 if (baton && reg_info)
546 return ((UnwindAssemblyInstEmulation *)baton)->ReadRegister (instruction, reg_info, reg_value);
550 UnwindAssemblyInstEmulation::ReadRegister (EmulateInstruction *instruction,
551 const RegisterInfo *reg_info,
552 RegisterValue ®_value)
554 bool synthetic = GetRegisterValue (*reg_info, reg_value);
556 Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_UNWIND));
558 if (log && log->GetVerbose ())
562 strm.Printf ("UnwindAssemblyInstEmulation::ReadRegister (name = \"%s\") => synthetic_value = %i, value = ", reg_info->name, synthetic);
563 reg_value.Dump(&strm, reg_info, false, false, eFormatDefault);
564 log->PutCString(strm.GetData());
570 UnwindAssemblyInstEmulation::WriteRegister (EmulateInstruction *instruction,
572 const EmulateInstruction::Context &context,
573 const RegisterInfo *reg_info,
574 const RegisterValue ®_value)
576 if (baton && reg_info)
577 return ((UnwindAssemblyInstEmulation *)baton)->WriteRegister (instruction, context, reg_info, reg_value);
581 UnwindAssemblyInstEmulation::WriteRegister (EmulateInstruction *instruction,
582 const EmulateInstruction::Context &context,
583 const RegisterInfo *reg_info,
584 const RegisterValue ®_value)
586 Log *log(GetLogIfAllCategoriesSet (LIBLLDB_LOG_UNWIND));
588 if (log && log->GetVerbose ())
592 strm.Printf ("UnwindAssemblyInstEmulation::WriteRegister (name = \"%s\", value = ", reg_info->name);
593 reg_value.Dump(&strm, reg_info, false, false, eFormatDefault);
594 strm.PutCString (", context = ");
595 context.Dump(strm, instruction);
596 log->PutCString(strm.GetData());
599 const bool must_replace = true;
600 SetRegisterValue (*reg_info, reg_value);
602 switch (context.type)
604 case EmulateInstruction::eContextInvalid:
605 case EmulateInstruction::eContextReadOpcode:
606 case EmulateInstruction::eContextImmediate:
607 case EmulateInstruction::eContextAdjustBaseRegister:
608 case EmulateInstruction::eContextRegisterPlusOffset:
609 case EmulateInstruction::eContextAdjustPC:
610 case EmulateInstruction::eContextRegisterStore:
611 case EmulateInstruction::eContextRegisterLoad:
612 case EmulateInstruction::eContextAbsoluteBranchRegister:
613 case EmulateInstruction::eContextSupervisorCall:
614 case EmulateInstruction::eContextTableBranchReadMemory:
615 case EmulateInstruction::eContextWriteRegisterRandomBits:
616 case EmulateInstruction::eContextWriteMemoryRandomBits:
617 case EmulateInstruction::eContextArithmetic:
618 case EmulateInstruction::eContextAdvancePC:
619 case EmulateInstruction::eContextReturnFromException:
620 case EmulateInstruction::eContextPushRegisterOnStack:
622 // const uint32_t reg_num = reg_info->kinds[m_unwind_plan_ptr->GetRegisterKind()];
623 // if (reg_num != LLDB_INVALID_REGNUM)
625 // const bool can_replace_only_if_unspecified = true;
627 // m_curr_row.SetRegisterLocationToUndefined (reg_num,
628 // can_replace_only_if_unspecified,
629 // can_replace_only_if_unspecified);
630 // m_curr_row_modified = true;
635 case EmulateInstruction::eContextRelativeBranchImmediate:
639 m_curr_insn_is_branch_immediate = true;
644 case EmulateInstruction::eContextPopRegisterOffStack:
646 const uint32_t reg_num = reg_info->kinds[m_unwind_plan_ptr->GetRegisterKind()];
647 if (reg_num != LLDB_INVALID_REGNUM)
649 m_curr_row->SetRegisterLocationToSame (reg_num, must_replace);
650 m_curr_row_modified = true;
651 m_curr_insn_restored_a_register = true;
656 case EmulateInstruction::eContextSetFramePointer:
660 m_cfa_reg_info = *reg_info;
661 const uint32_t cfa_reg_num = reg_info->kinds[m_unwind_plan_ptr->GetRegisterKind()];
662 assert (cfa_reg_num != LLDB_INVALID_REGNUM);
663 m_curr_row->SetCFARegister(cfa_reg_num);
664 m_curr_row->SetCFAOffset(m_initial_sp - reg_value.GetAsUInt64());
665 m_curr_row_modified = true;
669 case EmulateInstruction::eContextAdjustStackPointer:
670 // If we have created a frame using the frame pointer, don't follow
671 // subsequent adjustments to the stack pointer.
674 m_curr_row->SetCFAOffset (m_initial_sp - reg_value.GetAsUInt64());
675 m_curr_row_modified = true;