1 //===-- UnwindAssembly-x86.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 "UnwindAssembly-x86.h"
12 #include "llvm-c/Disassembler.h"
13 #include "llvm/ADT/STLExtras.h"
14 #include "llvm/Support/TargetSelect.h"
16 #include "lldb/Core/Address.h"
17 #include "lldb/Core/Error.h"
18 #include "lldb/Core/ArchSpec.h"
19 #include "lldb/Core/PluginManager.h"
20 #include "lldb/Symbol/UnwindPlan.h"
21 #include "lldb/Target/ABI.h"
22 #include "lldb/Target/ExecutionContext.h"
23 #include "lldb/Target/Process.h"
24 #include "lldb/Target/RegisterContext.h"
25 #include "lldb/Target/Thread.h"
26 #include "lldb/Target/Target.h"
27 #include "lldb/Target/UnwindAssembly.h"
28 #include "lldb/Utility/RegisterNumber.h"
31 using namespace lldb_private;
39 enum i386_register_numbers
52 enum x86_64_register_numbers
80 static struct regmap_ent i386_register_map[] =
82 {"eax", k_machine_eax, -1},
83 {"ecx", k_machine_ecx, -1},
84 {"edx", k_machine_edx, -1},
85 {"ebx", k_machine_ebx, -1},
86 {"esp", k_machine_esp, -1},
87 {"ebp", k_machine_ebp, -1},
88 {"esi", k_machine_esi, -1},
89 {"edi", k_machine_edi, -1},
90 {"eip", k_machine_eip, -1}
93 const int size_of_i386_register_map = llvm::array_lengthof (i386_register_map);
95 static int i386_register_map_initialized = 0;
97 static struct regmap_ent x86_64_register_map[] =
99 {"rax", k_machine_rax, -1},
100 {"rcx", k_machine_rcx, -1},
101 {"rdx", k_machine_rdx, -1},
102 {"rbx", k_machine_rbx, -1},
103 {"rsp", k_machine_rsp, -1},
104 {"rbp", k_machine_rbp, -1},
105 {"rsi", k_machine_rsi, -1},
106 {"rdi", k_machine_rdi, -1},
107 {"r8", k_machine_r8, -1},
108 {"r9", k_machine_r9, -1},
109 {"r10", k_machine_r10, -1},
110 {"r11", k_machine_r11, -1},
111 {"r12", k_machine_r12, -1},
112 {"r13", k_machine_r13, -1},
113 {"r14", k_machine_r14, -1},
114 {"r15", k_machine_r15, -1},
115 {"rip", k_machine_rip, -1}
118 const int size_of_x86_64_register_map = llvm::array_lengthof (x86_64_register_map);
120 static int x86_64_register_map_initialized = 0;
122 //-----------------------------------------------------------------------------------------------
123 // AssemblyParse_x86 local-file class definition & implementation functions
124 //-----------------------------------------------------------------------------------------------
126 class AssemblyParse_x86
130 AssemblyParse_x86 (const ExecutionContext &exe_ctx, int cpu, ArchSpec &arch, AddressRange func);
132 ~AssemblyParse_x86 ();
134 bool get_non_call_site_unwind_plan (UnwindPlan &unwind_plan);
136 bool augment_unwind_plan_from_call_site (AddressRange& func, UnwindPlan &unwind_plan);
138 bool get_fast_unwind_plan (AddressRange& func, UnwindPlan &unwind_plan);
140 bool find_first_non_prologue_insn (Address &address);
143 enum { kMaxInstructionByteSize = 32 };
145 bool nonvolatile_reg_p (int machine_regno);
146 bool push_rbp_pattern_p ();
147 bool push_0_pattern_p ();
148 bool mov_rsp_rbp_pattern_p ();
149 bool sub_rsp_pattern_p (int& amount);
150 bool add_rsp_pattern_p (int& amount);
151 bool lea_rsp_pattern_p (int& amount);
152 bool push_reg_p (int& regno);
153 bool pop_reg_p (int& regno);
154 bool push_imm_pattern_p ();
155 bool mov_reg_to_local_stack_frame_p (int& regno, int& fp_offset);
156 bool ret_pattern_p ();
157 bool pop_rbp_pattern_p ();
158 bool call_next_insn_pattern_p();
159 uint32_t extract_4 (uint8_t *b);
160 bool machine_regno_to_lldb_regno (int machine_regno, uint32_t& lldb_regno);
161 bool instruction_length (Address addr, int &length);
163 const ExecutionContext m_exe_ctx;
165 AddressRange m_func_bounds;
168 uint8_t m_cur_insn_bytes[kMaxInstructionByteSize];
170 uint32_t m_machine_ip_regnum;
171 uint32_t m_machine_sp_regnum;
172 uint32_t m_machine_fp_regnum;
174 uint32_t m_lldb_ip_regnum;
175 uint32_t m_lldb_sp_regnum;
176 uint32_t m_lldb_fp_regnum;
181 ::LLVMDisasmContextRef m_disasm_context;
183 DISALLOW_COPY_AND_ASSIGN (AssemblyParse_x86);
186 AssemblyParse_x86::AssemblyParse_x86 (const ExecutionContext &exe_ctx, int cpu, ArchSpec &arch, AddressRange func) :
190 m_machine_ip_regnum (LLDB_INVALID_REGNUM),
191 m_machine_sp_regnum (LLDB_INVALID_REGNUM),
192 m_machine_fp_regnum (LLDB_INVALID_REGNUM),
193 m_lldb_ip_regnum (LLDB_INVALID_REGNUM),
194 m_lldb_sp_regnum (LLDB_INVALID_REGNUM),
195 m_lldb_fp_regnum (LLDB_INVALID_REGNUM),
200 int *initialized_flag = NULL;
203 m_machine_ip_regnum = k_machine_eip;
204 m_machine_sp_regnum = k_machine_esp;
205 m_machine_fp_regnum = k_machine_ebp;
207 initialized_flag = &i386_register_map_initialized;
211 m_machine_ip_regnum = k_machine_rip;
212 m_machine_sp_regnum = k_machine_rsp;
213 m_machine_fp_regnum = k_machine_rbp;
215 initialized_flag = &x86_64_register_map_initialized;
218 // we only look at prologue - it will be complete earlier than 512 bytes into func
219 if (m_func_bounds.GetByteSize() == 0)
220 m_func_bounds.SetByteSize(512);
222 Thread *thread = m_exe_ctx.GetThreadPtr();
223 if (thread && *initialized_flag == 0)
225 RegisterContext *reg_ctx = thread->GetRegisterContext().get();
228 struct regmap_ent *ent;
232 ent = i386_register_map;
233 count = size_of_i386_register_map;
237 ent = x86_64_register_map;
238 count = size_of_x86_64_register_map;
240 for (i = 0; i < count; i++, ent++)
242 const RegisterInfo *ri = reg_ctx->GetRegisterInfoByName (ent->name);
244 ent->lldb_regno = ri->kinds[eRegisterKindLLDB];
246 *initialized_flag = 1;
250 // on initial construction we may not have a Thread so these have to remain
251 // uninitialized until we can get a RegisterContext to set up the register map table
252 if (*initialized_flag == 1)
255 if (machine_regno_to_lldb_regno (m_machine_sp_regnum, lldb_regno))
256 m_lldb_sp_regnum = lldb_regno;
257 if (machine_regno_to_lldb_regno (m_machine_fp_regnum, lldb_regno))
258 m_lldb_fp_regnum = lldb_regno;
259 if (machine_regno_to_lldb_regno (m_machine_ip_regnum, lldb_regno))
260 m_lldb_ip_regnum = lldb_regno;
263 m_disasm_context = ::LLVMCreateDisasm(m_arch.GetTriple().getTriple().c_str(),
270 AssemblyParse_x86::~AssemblyParse_x86 ()
272 ::LLVMDisasmDispose(m_disasm_context);
275 // This function expects an x86 native register number (i.e. the bits stripped out of the
276 // actual instruction), not an lldb register number.
279 AssemblyParse_x86::nonvolatile_reg_p (int machine_regno)
283 switch (machine_regno)
286 case k_machine_ebp: // not actually a nonvolatile but often treated as such by convention
295 if (m_cpu == k_x86_64)
297 switch (machine_regno)
301 case k_machine_rbp: // not actually a nonvolatile but often treated as such by convention
315 // Macro to detect if this is a REX mode prefix byte.
316 #define REX_W_PREFIX_P(opcode) (((opcode) & (~0x5)) == 0x48)
318 // The high bit which should be added to the source register number (the "R" bit)
319 #define REX_W_SRCREG(opcode) (((opcode) & 0x4) >> 2)
321 // The high bit which should be added to the destination register number (the "B" bit)
322 #define REX_W_DSTREG(opcode) ((opcode) & 0x1)
326 AssemblyParse_x86::push_rbp_pattern_p ()
328 uint8_t *p = m_cur_insn_bytes;
334 // pushq $0 ; the first instruction in start() [0x6a 0x00]
336 AssemblyParse_x86::push_0_pattern_p ()
338 uint8_t *p = m_cur_insn_bytes;
339 if (*p == 0x6a && *(p + 1) == 0x0)
347 AssemblyParse_x86::push_imm_pattern_p ()
349 uint8_t *p = m_cur_insn_bytes;
350 if (*p == 0x68 || *p == 0x6a)
355 // movq %rsp, %rbp [0x48 0x8b 0xec] or [0x48 0x89 0xe5]
356 // movl %esp, %ebp [0x8b 0xec] or [0x89 0xe5]
358 AssemblyParse_x86::mov_rsp_rbp_pattern_p ()
360 uint8_t *p = m_cur_insn_bytes;
361 if (m_wordsize == 8 && *p == 0x48)
363 if (*(p) == 0x8b && *(p + 1) == 0xec)
365 if (*(p) == 0x89 && *(p + 1) == 0xe5)
372 AssemblyParse_x86::sub_rsp_pattern_p (int& amount)
374 uint8_t *p = m_cur_insn_bytes;
375 if (m_wordsize == 8 && *p == 0x48)
377 // 8-bit immediate operand
378 if (*p == 0x83 && *(p + 1) == 0xec)
380 amount = (int8_t) *(p + 2);
383 // 32-bit immediate operand
384 if (*p == 0x81 && *(p + 1) == 0xec)
386 amount = (int32_t) extract_4 (p + 2);
394 AssemblyParse_x86::add_rsp_pattern_p (int& amount)
396 uint8_t *p = m_cur_insn_bytes;
397 if (m_wordsize == 8 && *p == 0x48)
399 // 8-bit immediate operand
400 if (*p == 0x83 && *(p + 1) == 0xc4)
402 amount = (int8_t) *(p + 2);
405 // 32-bit immediate operand
406 if (*p == 0x81 && *(p + 1) == 0xc4)
408 amount = (int32_t) extract_4 (p + 2);
414 // lea esp, [esp - 0x28]
415 // lea esp, [esp + 0x28]
417 AssemblyParse_x86::lea_rsp_pattern_p (int& amount)
419 uint8_t *p = m_cur_insn_bytes;
420 if (m_wordsize == 8 && *p == 0x48)
427 // 8 bit displacement
428 if (*(p + 1) == 0x64 && (*(p + 2) & 0x3f) == 0x24)
430 amount = (int8_t) *(p + 3);
434 // 32 bit displacement
435 if (*(p + 1) == 0xa4 && (*(p + 2) & 0x3f) == 0x24)
437 amount = (int32_t) extract_4 (p + 3);
447 AssemblyParse_x86::push_reg_p (int& regno)
449 uint8_t *p = m_cur_insn_bytes;
450 int regno_prefix_bit = 0;
451 // If we have a rex prefix byte, check to see if a B bit is set
452 if (m_wordsize == 8 && *p == 0x41)
454 regno_prefix_bit = 1 << 3;
457 if (*p >= 0x50 && *p <= 0x57)
459 regno = (*p - 0x50) | regno_prefix_bit;
468 AssemblyParse_x86::pop_reg_p (int& regno)
470 uint8_t *p = m_cur_insn_bytes;
471 int regno_prefix_bit = 0;
472 // If we have a rex prefix byte, check to see if a B bit is set
473 if (m_wordsize == 8 && *p == 0x41)
475 regno_prefix_bit = 1 << 3;
478 if (*p >= 0x58 && *p <= 0x5f)
480 regno = (*p - 0x58) | regno_prefix_bit;
489 AssemblyParse_x86::pop_rbp_pattern_p ()
491 uint8_t *p = m_cur_insn_bytes;
495 // call $0 [0xe8 0x0 0x0 0x0 0x0]
497 AssemblyParse_x86::call_next_insn_pattern_p ()
499 uint8_t *p = m_cur_insn_bytes;
500 return (*p == 0xe8) && (*(p+1) == 0x0) && (*(p+2) == 0x0)
501 && (*(p+3) == 0x0) && (*(p+4) == 0x0);
504 // Look for an instruction sequence storing a nonvolatile register
505 // on to the stack frame.
507 // movq %rax, -0x10(%rbp) [0x48 0x89 0x45 0xf0]
508 // movl %eax, -0xc(%ebp) [0x89 0x45 0xf4]
510 // The offset value returned in rbp_offset will be positive --
511 // but it must be subtraced from the frame base register to get
512 // the actual location. The positive value returned for the offset
513 // is a convention used elsewhere for CFA offsets et al.
516 AssemblyParse_x86::mov_reg_to_local_stack_frame_p (int& regno, int& rbp_offset)
518 uint8_t *p = m_cur_insn_bytes;
519 int src_reg_prefix_bit = 0;
520 int target_reg_prefix_bit = 0;
522 if (m_wordsize == 8 && REX_W_PREFIX_P (*p))
524 src_reg_prefix_bit = REX_W_SRCREG (*p) << 3;
525 target_reg_prefix_bit = REX_W_DSTREG (*p) << 3;
526 if (target_reg_prefix_bit == 1)
528 // rbp/ebp don't need a prefix bit - we know this isn't the
529 // reg we care about.
537 /* Mask off the 3-5 bits which indicate the destination register
538 if this is a ModR/M byte. */
539 int opcode_destreg_masked_out = *(p + 1) & (~0x38);
541 /* Is this a ModR/M byte with Mod bits 01 and R/M bits 101
542 and three bits between them, e.g. 01nnn101
543 We're looking for a destination of ebp-disp8 or ebp-disp32. */
545 if (opcode_destreg_masked_out == 0x45)
547 else if (opcode_destreg_masked_out == 0x85)
554 offset = (int8_t) *(p + 2);
556 offset = (uint32_t) extract_4 (p + 2);
560 regno = ((*(p + 1) >> 3) & 0x7) | src_reg_prefix_bit;
561 rbp_offset = offset > 0 ? offset : -offset;
567 // ret [0xc9] or [0xc2 imm8] or [0xca imm8]
569 AssemblyParse_x86::ret_pattern_p ()
571 uint8_t *p = m_cur_insn_bytes;
572 if (*p == 0xc9 || *p == 0xc2 || *p == 0xca || *p == 0xc3)
578 AssemblyParse_x86::extract_4 (uint8_t *b)
581 for (int i = 3; i >= 0; i--)
587 AssemblyParse_x86::machine_regno_to_lldb_regno (int machine_regno, uint32_t &lldb_regno)
589 struct regmap_ent *ent;
593 ent = i386_register_map;
594 count = size_of_i386_register_map;
598 ent = x86_64_register_map;
599 count = size_of_x86_64_register_map;
601 for (i = 0; i < count; i++, ent++)
603 if (ent->machine_regno == machine_regno)
604 if (ent->lldb_regno != -1)
606 lldb_regno = ent->lldb_regno;
614 AssemblyParse_x86::instruction_length (Address addr, int &length)
616 const uint32_t max_op_byte_size = m_arch.GetMaximumOpcodeByteSize();
617 llvm::SmallVector <uint8_t, 32> opcode_data;
618 opcode_data.resize (max_op_byte_size);
623 const bool prefer_file_cache = true;
625 Target *target = m_exe_ctx.GetTargetPtr();
626 if (target->ReadMemory (addr, prefer_file_cache, opcode_data.data(),
627 max_op_byte_size, error) == static_cast<size_t>(-1))
632 char out_string[512];
633 const addr_t pc = addr.GetFileAddress();
634 const size_t inst_size = ::LLVMDisasmInstruction (m_disasm_context,
647 AssemblyParse_x86::get_non_call_site_unwind_plan (UnwindPlan &unwind_plan)
649 UnwindPlan::RowSP row(new UnwindPlan::Row);
650 m_cur_insn = m_func_bounds.GetBaseAddress ();
651 addr_t current_func_text_offset = 0;
652 int current_sp_bytes_offset_from_cfa = 0;
653 UnwindPlan::Row::RegisterLocation initial_regloc;
656 if (!m_cur_insn.IsValid())
661 unwind_plan.SetPlanValidAddressRange (m_func_bounds);
662 unwind_plan.SetRegisterKind (eRegisterKindLLDB);
664 // At the start of the function, find the CFA by adding wordsize to the SP register
665 row->SetOffset (current_func_text_offset);
666 row->GetCFAValue().SetIsRegisterPlusOffset(m_lldb_sp_regnum, m_wordsize);
668 // caller's stack pointer value before the call insn is the CFA address
669 initial_regloc.SetIsCFAPlusOffset (0);
670 row->SetRegisterInfo (m_lldb_sp_regnum, initial_regloc);
672 // saved instruction pointer can be found at CFA - wordsize.
673 current_sp_bytes_offset_from_cfa = m_wordsize;
674 initial_regloc.SetAtCFAPlusOffset (-current_sp_bytes_offset_from_cfa);
675 row->SetRegisterInfo (m_lldb_ip_regnum, initial_regloc);
677 unwind_plan.AppendRow (row);
679 // Allocate a new Row, populate it with the existing Row contents.
680 UnwindPlan::Row *newrow = new UnwindPlan::Row;
681 *newrow = *row.get();
684 // Track which registers have been saved so far in the prologue.
685 // If we see another push of that register, it's not part of the prologue.
686 // The register numbers used here are the machine register #'s
687 // (i386_register_numbers, x86_64_register_numbers).
688 std::vector<bool> saved_registers(32, false);
690 const bool prefer_file_cache = true;
692 // Once the prologue has completed we'll save a copy of the unwind instructions
693 // If there is an epilogue in the middle of the function, after that epilogue we'll reinstate
694 // the unwind setup -- we assume that some code path jumps over the mid-function epilogue
696 UnwindPlan::RowSP prologue_completed_row; // copy of prologue row of CFI
697 int prologue_completed_sp_bytes_offset_from_cfa; // The sp value before the epilogue started executed
698 std::vector<bool> prologue_completed_saved_registers;
700 Target *target = m_exe_ctx.GetTargetPtr();
701 while (m_func_bounds.ContainsFileAddress (m_cur_insn))
703 int stack_offset, insn_len;
704 int machine_regno; // register numbers masked directly out of instructions
705 uint32_t lldb_regno; // register numbers in lldb's eRegisterKindLLDB numbering scheme
707 bool in_epilogue = false; // we're in the middle of an epilogue sequence
708 bool row_updated = false; // The UnwindPlan::Row 'row' has been updated
710 if (!instruction_length (m_cur_insn, insn_len) || insn_len == 0 || insn_len > kMaxInstructionByteSize)
712 // An unrecognized/junk instruction
716 if (target->ReadMemory (m_cur_insn, prefer_file_cache, m_cur_insn_bytes,
717 insn_len, error) == static_cast<size_t>(-1))
719 // Error reading the instruction out of the file, stop scanning
723 if (push_rbp_pattern_p ())
725 current_sp_bytes_offset_from_cfa += m_wordsize;
726 row->GetCFAValue().SetOffset (current_sp_bytes_offset_from_cfa);
727 UnwindPlan::Row::RegisterLocation regloc;
728 regloc.SetAtCFAPlusOffset (-row->GetCFAValue().GetOffset());
729 row->SetRegisterInfo (m_lldb_fp_regnum, regloc);
730 saved_registers[m_machine_fp_regnum] = true;
734 else if (mov_rsp_rbp_pattern_p ())
736 row->GetCFAValue().SetIsRegisterPlusOffset(m_lldb_fp_regnum, row->GetCFAValue().GetOffset());
740 // This is the start() function (or a pthread equivalent), it starts with a pushl $0x0 which puts the
741 // saved pc value of 0 on the stack. In this case we want to pretend we didn't see a stack movement at all --
742 // normally the saved pc value is already on the stack by the time the function starts executing.
743 else if (push_0_pattern_p ())
747 else if (push_reg_p (machine_regno))
749 current_sp_bytes_offset_from_cfa += m_wordsize;
750 // the PUSH instruction has moved the stack pointer - if the CFA is set in terms of the stack pointer,
751 // we need to add a new row of instructions.
752 if (row->GetCFAValue().GetRegisterNumber() == m_lldb_sp_regnum)
754 row->GetCFAValue().SetOffset (current_sp_bytes_offset_from_cfa);
757 // record where non-volatile (callee-saved, spilled) registers are saved on the stack
758 if (nonvolatile_reg_p (machine_regno)
759 && machine_regno_to_lldb_regno (machine_regno, lldb_regno)
760 && saved_registers[machine_regno] == false)
762 UnwindPlan::Row::RegisterLocation regloc;
763 regloc.SetAtCFAPlusOffset (-current_sp_bytes_offset_from_cfa);
764 row->SetRegisterInfo (lldb_regno, regloc);
765 saved_registers[machine_regno] = true;
770 else if (pop_reg_p (machine_regno))
772 current_sp_bytes_offset_from_cfa -= m_wordsize;
774 if (nonvolatile_reg_p (machine_regno)
775 && machine_regno_to_lldb_regno (machine_regno, lldb_regno)
776 && saved_registers[machine_regno] == true)
778 saved_registers[machine_regno] = false;
779 row->RemoveRegisterInfo (lldb_regno);
781 if (machine_regno == (int)m_machine_fp_regnum)
783 row->GetCFAValue().SetIsRegisterPlusOffset (m_lldb_sp_regnum,
784 row->GetCFAValue().GetOffset());
791 // the POP instruction has moved the stack pointer - if the CFA is set in terms of the stack pointer,
792 // we need to add a new row of instructions.
793 if (row->GetCFAValue().GetRegisterNumber() == m_lldb_sp_regnum)
795 row->GetCFAValue().SetIsRegisterPlusOffset(m_lldb_sp_regnum,
796 current_sp_bytes_offset_from_cfa);
801 else if (mov_reg_to_local_stack_frame_p (machine_regno, stack_offset)
802 && nonvolatile_reg_p (machine_regno)
803 && machine_regno_to_lldb_regno (machine_regno, lldb_regno)
804 && saved_registers[machine_regno] == false)
806 saved_registers[machine_regno] = true;
808 UnwindPlan::Row::RegisterLocation regloc;
810 // stack_offset for 'movq %r15, -80(%rbp)' will be 80.
811 // In the Row, we want to express this as the offset from the CFA. If the frame base
812 // is rbp (like the above instruction), the CFA offset for rbp is probably 16. So we
813 // want to say that the value is stored at the CFA address - 96.
814 regloc.SetAtCFAPlusOffset (-(stack_offset + row->GetCFAValue().GetOffset()));
816 row->SetRegisterInfo (lldb_regno, regloc);
821 else if (sub_rsp_pattern_p (stack_offset))
823 current_sp_bytes_offset_from_cfa += stack_offset;
824 if (row->GetCFAValue().GetRegisterNumber() == m_lldb_sp_regnum)
826 row->GetCFAValue().SetOffset (current_sp_bytes_offset_from_cfa);
831 else if (add_rsp_pattern_p (stack_offset))
833 current_sp_bytes_offset_from_cfa -= stack_offset;
834 if (row->GetCFAValue().GetRegisterNumber() == m_lldb_sp_regnum)
836 row->GetCFAValue().SetOffset (current_sp_bytes_offset_from_cfa);
842 else if (lea_rsp_pattern_p (stack_offset))
844 current_sp_bytes_offset_from_cfa -= stack_offset;
845 if (row->GetCFAValue().GetRegisterNumber() == m_lldb_sp_regnum)
847 row->GetCFAValue().SetOffset (current_sp_bytes_offset_from_cfa);
850 if (stack_offset > 0)
854 else if (ret_pattern_p () && prologue_completed_row.get())
856 // Reinstate the saved prologue setup for any instructions
857 // that come after the ret instruction
859 UnwindPlan::Row *newrow = new UnwindPlan::Row;
860 *newrow = *prologue_completed_row.get();
862 current_sp_bytes_offset_from_cfa = prologue_completed_sp_bytes_offset_from_cfa;
864 saved_registers.clear();
865 saved_registers.resize(prologue_completed_saved_registers.size(), false);
866 for (size_t i = 0; i < prologue_completed_saved_registers.size(); ++i)
868 saved_registers[i] = prologue_completed_saved_registers[i];
875 // call next instruction
878 // This is used in i386 programs to get the PIC base address for finding global data
879 else if (call_next_insn_pattern_p ())
881 current_sp_bytes_offset_from_cfa += m_wordsize;
882 if (row->GetCFAValue().GetRegisterNumber() == m_lldb_sp_regnum)
884 row->GetCFAValue().SetOffset (current_sp_bytes_offset_from_cfa);
891 if (current_func_text_offset + insn_len < m_func_bounds.GetByteSize())
893 row->SetOffset (current_func_text_offset + insn_len);
894 unwind_plan.AppendRow (row);
895 // Allocate a new Row, populate it with the existing Row contents.
896 newrow = new UnwindPlan::Row;
897 *newrow = *row.get();
902 if (in_epilogue == false && row_updated)
904 // If we're not in an epilogue sequence, save the updated Row
905 UnwindPlan::Row *newrow = new UnwindPlan::Row;
906 *newrow = *row.get();
907 prologue_completed_row.reset (newrow);
909 prologue_completed_saved_registers.clear();
910 prologue_completed_saved_registers.resize(saved_registers.size(), false);
911 for (size_t i = 0; i < saved_registers.size(); ++i)
913 prologue_completed_saved_registers[i] = saved_registers[i];
917 // We may change the sp value without adding a new Row necessarily -- keep
918 // track of it either way.
919 if (in_epilogue == false)
921 prologue_completed_sp_bytes_offset_from_cfa = current_sp_bytes_offset_from_cfa;
924 m_cur_insn.SetOffset (m_cur_insn.GetOffset() + insn_len);
925 current_func_text_offset += insn_len;
928 unwind_plan.SetSourceName ("assembly insn profiling");
929 unwind_plan.SetSourcedFromCompiler (eLazyBoolNo);
930 unwind_plan.SetUnwindPlanValidAtAllInstructions (eLazyBoolYes);
936 AssemblyParse_x86::augment_unwind_plan_from_call_site (AddressRange& func, UnwindPlan &unwind_plan)
938 // Is func address valid?
939 Address addr_start = func.GetBaseAddress();
940 if (!addr_start.IsValid())
943 // Is original unwind_plan valid?
944 // unwind_plan should have at least one row which is ABI-default (CFA register is sp),
945 // and another row in mid-function.
946 if (unwind_plan.GetRowCount() < 2)
948 UnwindPlan::RowSP first_row = unwind_plan.GetRowAtIndex (0);
949 if (first_row->GetOffset() != 0)
951 uint32_t cfa_reg = m_exe_ctx.GetThreadPtr()->GetRegisterContext()
952 ->ConvertRegisterKindToRegisterNumber (unwind_plan.GetRegisterKind(),
953 first_row->GetCFAValue().GetRegisterNumber());
954 if (cfa_reg != m_lldb_sp_regnum || first_row->GetCFAValue().GetOffset() != m_wordsize)
957 UnwindPlan::RowSP original_last_row = unwind_plan.GetRowForFunctionOffset (-1);
959 Target *target = m_exe_ctx.GetTargetPtr();
960 m_cur_insn = func.GetBaseAddress();
963 bool unwind_plan_updated = false;
964 UnwindPlan::RowSP row(new UnwindPlan::Row(*first_row));
966 // After a mid-function epilogue we will need to re-insert the original unwind rules
967 // so unwinds work for the remainder of the function. These aren't common with clang/gcc
968 // on x86 but it is possible.
969 bool reinstate_unwind_state = false;
971 while (func.ContainsFileAddress (m_cur_insn))
974 if (!instruction_length (m_cur_insn, insn_len)
975 || insn_len == 0 || insn_len > kMaxInstructionByteSize)
977 // An unrecognized/junk instruction.
980 const bool prefer_file_cache = true;
982 if (target->ReadMemory (m_cur_insn, prefer_file_cache, m_cur_insn_bytes,
983 insn_len, error) == static_cast<size_t>(-1))
985 // Error reading the instruction out of the file, stop scanning.
991 m_cur_insn.SetOffset(m_cur_insn.GetOffset() + insn_len);
993 if (reinstate_unwind_state)
995 // that was the last instruction of this function
996 if (func.ContainsFileAddress (m_cur_insn) == false)
999 UnwindPlan::RowSP new_row(new UnwindPlan::Row());
1000 *new_row = *original_last_row;
1001 new_row->SetOffset (offset);
1002 unwind_plan.AppendRow (new_row);
1003 row.reset (new UnwindPlan::Row());
1005 reinstate_unwind_state = false;
1006 unwind_plan_updated = true;
1010 // If we already have one row for this instruction, we can continue.
1011 while (row_id < unwind_plan.GetRowCount()
1012 && unwind_plan.GetRowAtIndex (row_id)->GetOffset() <= offset)
1016 UnwindPlan::RowSP original_row = unwind_plan.GetRowAtIndex (row_id - 1);
1017 if (original_row->GetOffset() == offset)
1019 *row = *original_row;
1025 // If we are here, compiler didn't generate CFI for prologue.
1026 // This won't happen to GCC or clang.
1027 // In this case, bail out directly.
1031 // Inspect the instruction to check if we need a new row for it.
1032 cfa_reg = m_exe_ctx.GetThreadPtr()->GetRegisterContext()
1033 ->ConvertRegisterKindToRegisterNumber (unwind_plan.GetRegisterKind(),
1034 row->GetCFAValue().GetRegisterNumber());
1035 if (cfa_reg == m_lldb_sp_regnum)
1037 // CFA register is sp.
1039 // call next instruction
1042 if (call_next_insn_pattern_p ())
1044 row->SetOffset (offset);
1045 row->GetCFAValue().IncOffset (m_wordsize);
1047 UnwindPlan::RowSP new_row(new UnwindPlan::Row(*row));
1048 unwind_plan.InsertRow (new_row);
1049 unwind_plan_updated = true;
1053 // push/pop register
1055 if (push_reg_p (regno))
1057 row->SetOffset (offset);
1058 row->GetCFAValue().IncOffset (m_wordsize);
1060 UnwindPlan::RowSP new_row(new UnwindPlan::Row(*row));
1061 unwind_plan.InsertRow (new_row);
1062 unwind_plan_updated = true;
1065 if (pop_reg_p (regno))
1067 // Technically, this might be a nonvolatile register recover in epilogue.
1068 // We should reset RegisterInfo for the register.
1069 // But in practice, previous rule for the register is still valid...
1070 // So we ignore this case.
1072 row->SetOffset (offset);
1073 row->GetCFAValue().IncOffset (-m_wordsize);
1075 UnwindPlan::RowSP new_row(new UnwindPlan::Row(*row));
1076 unwind_plan.InsertRow (new_row);
1077 unwind_plan_updated = true;
1082 if (push_imm_pattern_p ())
1084 row->SetOffset (offset);
1085 row->GetCFAValue().IncOffset (m_wordsize);
1086 UnwindPlan::RowSP new_row(new UnwindPlan::Row(*row));
1087 unwind_plan.InsertRow (new_row);
1088 unwind_plan_updated = true;
1092 // add/sub %rsp/%esp
1094 if (add_rsp_pattern_p (amount))
1096 row->SetOffset (offset);
1097 row->GetCFAValue().IncOffset (-amount);
1099 UnwindPlan::RowSP new_row(new UnwindPlan::Row(*row));
1100 unwind_plan.InsertRow (new_row);
1101 unwind_plan_updated = true;
1104 if (sub_rsp_pattern_p (amount))
1106 row->SetOffset (offset);
1107 row->GetCFAValue().IncOffset (amount);
1109 UnwindPlan::RowSP new_row(new UnwindPlan::Row(*row));
1110 unwind_plan.InsertRow (new_row);
1111 unwind_plan_updated = true;
1115 // lea %rsp, [%rsp + $offset]
1116 if (lea_rsp_pattern_p (amount))
1118 row->SetOffset (offset);
1119 row->GetCFAValue().IncOffset (-amount);
1121 UnwindPlan::RowSP new_row(new UnwindPlan::Row(*row));
1122 unwind_plan.InsertRow (new_row);
1123 unwind_plan_updated = true;
1127 if (ret_pattern_p ())
1129 reinstate_unwind_state = true;
1133 else if (cfa_reg == m_lldb_fp_regnum)
1135 // CFA register is fp.
1137 // The only case we care about is epilogue:
1138 // [0x5d] pop %rbp/%ebp
1140 if (pop_rbp_pattern_p ())
1142 if (target->ReadMemory (m_cur_insn, prefer_file_cache, m_cur_insn_bytes,
1143 1, error) != static_cast<size_t>(-1)
1144 && ret_pattern_p ())
1146 row->SetOffset (offset);
1147 row->GetCFAValue().SetIsRegisterPlusOffset (
1148 first_row->GetCFAValue().GetRegisterNumber(), m_wordsize);
1150 UnwindPlan::RowSP new_row(new UnwindPlan::Row(*row));
1151 unwind_plan.InsertRow (new_row);
1152 unwind_plan_updated = true;
1153 reinstate_unwind_state = true;
1160 // CFA register is not sp or fp.
1162 // This must be hand-written assembly.
1163 // Just trust eh_frame and assume we have finished.
1168 unwind_plan.SetPlanValidAddressRange (func);
1169 if (unwind_plan_updated)
1171 std::string unwind_plan_source (unwind_plan.GetSourceName().AsCString());
1172 unwind_plan_source += " plus augmentation from assembly parsing";
1173 unwind_plan.SetSourceName (unwind_plan_source.c_str());
1174 unwind_plan.SetSourcedFromCompiler (eLazyBoolNo);
1175 unwind_plan.SetUnwindPlanValidAtAllInstructions (eLazyBoolYes);
1180 /* The "fast unwind plan" is valid for functions that follow the usual convention of
1181 using the frame pointer register (ebp, rbp), i.e. the function prologue looks like
1183 mov %rsp,%rbp [0x48 0x89 0xe5] (this is a 2-byte insn seq on i386)
1187 AssemblyParse_x86::get_fast_unwind_plan (AddressRange& func, UnwindPlan &unwind_plan)
1189 UnwindPlan::RowSP row(new UnwindPlan::Row);
1190 UnwindPlan::Row::RegisterLocation pc_reginfo;
1191 UnwindPlan::Row::RegisterLocation sp_reginfo;
1192 UnwindPlan::Row::RegisterLocation fp_reginfo;
1193 unwind_plan.SetRegisterKind (eRegisterKindLLDB);
1195 if (!func.GetBaseAddress().IsValid())
1198 Target *target = m_exe_ctx.GetTargetPtr();
1202 const bool prefer_file_cache = true;
1203 if (target->ReadMemory (func.GetBaseAddress(), prefer_file_cache, bytebuf,
1204 sizeof (bytebuf), error) == static_cast<size_t>(-1))
1207 uint8_t i386_prologue[] = {0x55, 0x89, 0xe5};
1208 uint8_t x86_64_prologue[] = {0x55, 0x48, 0x89, 0xe5};
1211 if (memcmp (bytebuf, i386_prologue, sizeof (i386_prologue)) == 0)
1213 prologue_size = sizeof (i386_prologue);
1215 else if (memcmp (bytebuf, x86_64_prologue, sizeof (x86_64_prologue)) == 0)
1217 prologue_size = sizeof (x86_64_prologue);
1224 pc_reginfo.SetAtCFAPlusOffset (-m_wordsize);
1225 row->SetRegisterInfo (m_lldb_ip_regnum, pc_reginfo);
1227 sp_reginfo.SetIsCFAPlusOffset (0);
1228 row->SetRegisterInfo (m_lldb_sp_regnum, sp_reginfo);
1230 // Zero instructions into the function
1231 row->GetCFAValue().SetIsRegisterPlusOffset (m_lldb_sp_regnum, m_wordsize);
1233 unwind_plan.AppendRow (row);
1234 UnwindPlan::Row *newrow = new UnwindPlan::Row;
1235 *newrow = *row.get();
1238 // push %rbp has executed - stack moved, rbp now saved
1239 row->GetCFAValue().IncOffset (m_wordsize);
1240 fp_reginfo.SetAtCFAPlusOffset (2 * -m_wordsize);
1241 row->SetRegisterInfo (m_lldb_fp_regnum, fp_reginfo);
1243 unwind_plan.AppendRow (row);
1245 newrow = new UnwindPlan::Row;
1246 *newrow = *row.get();
1249 // mov %rsp, %rbp has executed
1250 row->GetCFAValue().SetIsRegisterPlusOffset (m_lldb_fp_regnum, 2 * m_wordsize);
1251 row->SetOffset (prologue_size); /// 3 or 4 bytes depending on arch
1252 unwind_plan.AppendRow (row);
1254 newrow = new UnwindPlan::Row;
1255 *newrow = *row.get();
1258 unwind_plan.SetPlanValidAddressRange (func);
1259 unwind_plan.SetSourceName ("fast unwind assembly profiling");
1260 unwind_plan.SetSourcedFromCompiler (eLazyBoolNo);
1261 unwind_plan.SetUnwindPlanValidAtAllInstructions (eLazyBoolNo);
1266 AssemblyParse_x86::find_first_non_prologue_insn (Address &address)
1268 m_cur_insn = m_func_bounds.GetBaseAddress ();
1269 if (!m_cur_insn.IsValid())
1274 const bool prefer_file_cache = true;
1275 Target *target = m_exe_ctx.GetTargetPtr();
1276 while (m_func_bounds.ContainsFileAddress (m_cur_insn))
1279 int insn_len, offset, regno;
1280 if (!instruction_length (m_cur_insn, insn_len) || insn_len > kMaxInstructionByteSize || insn_len == 0)
1282 // An error parsing the instruction, i.e. probably data/garbage - stop scanning
1285 if (target->ReadMemory (m_cur_insn, prefer_file_cache, m_cur_insn_bytes,
1286 insn_len, error) == static_cast<size_t>(-1))
1288 // Error reading the instruction out of the file, stop scanning
1292 if (push_rbp_pattern_p () || mov_rsp_rbp_pattern_p () || sub_rsp_pattern_p (offset)
1293 || push_reg_p (regno) || mov_reg_to_local_stack_frame_p (regno, offset)
1294 || (lea_rsp_pattern_p (offset) && offset < 0))
1296 m_cur_insn.SetOffset (m_cur_insn.GetOffset() + insn_len);
1300 // Unknown non-prologue instruction - stop scanning
1304 address = m_cur_insn;
1313 //-----------------------------------------------------------------------------------------------
1314 // UnwindAssemblyParser_x86 method definitions
1315 //-----------------------------------------------------------------------------------------------
1317 UnwindAssembly_x86::UnwindAssembly_x86 (const ArchSpec &arch, int cpu) :
1318 lldb_private::UnwindAssembly(arch),
1325 UnwindAssembly_x86::~UnwindAssembly_x86 ()
1330 UnwindAssembly_x86::GetNonCallSiteUnwindPlanFromAssembly (AddressRange& func, Thread& thread, UnwindPlan& unwind_plan)
1332 ExecutionContext exe_ctx (thread.shared_from_this());
1333 AssemblyParse_x86 asm_parse(exe_ctx, m_cpu, m_arch, func);
1334 return asm_parse.get_non_call_site_unwind_plan (unwind_plan);
1338 UnwindAssembly_x86::AugmentUnwindPlanFromCallSite (AddressRange& func, Thread& thread, UnwindPlan& unwind_plan)
1340 bool do_augment_unwindplan = true;
1342 UnwindPlan::RowSP first_row = unwind_plan.GetRowForFunctionOffset (0);
1343 UnwindPlan::RowSP last_row = unwind_plan.GetRowForFunctionOffset (-1);
1346 ProcessSP process_sp (thread.GetProcess());
1349 wordsize = process_sp->GetTarget().GetArchitecture().GetAddressByteSize();
1352 RegisterNumber sp_regnum (thread, eRegisterKindGeneric, LLDB_REGNUM_GENERIC_SP);
1353 RegisterNumber pc_regnum (thread, eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
1355 // Does this UnwindPlan describe the prologue? I want to see that the CFA is set
1356 // in terms of the stack pointer plus an offset, and I want to see that rip is
1357 // retrieved at the CFA-wordsize.
1358 // If there is no description of the prologue, don't try to augment this eh_frame
1359 // unwinder code, fall back to assembly parsing instead.
1361 if (first_row->GetCFAValue().GetValueType() != UnwindPlan::Row::CFAValue::isRegisterPlusOffset
1362 || RegisterNumber (thread, unwind_plan.GetRegisterKind(),
1363 first_row->GetCFAValue().GetRegisterNumber()) != sp_regnum
1364 || first_row->GetCFAValue().GetOffset() != wordsize)
1368 UnwindPlan::Row::RegisterLocation first_row_pc_loc;
1369 if (first_row->GetRegisterInfo (pc_regnum.GetAsKind (unwind_plan.GetRegisterKind()), first_row_pc_loc) == false
1370 || first_row_pc_loc.IsAtCFAPlusOffset() == false
1371 || first_row_pc_loc.GetOffset() != -wordsize)
1377 // It looks like the prologue is described.
1378 // Is the epilogue described? If it is, no need to do any augmentation.
1380 if (first_row != last_row && first_row->GetOffset() != last_row->GetOffset())
1382 // The first & last row have the same CFA register
1383 // and the same CFA offset value
1384 // and the CFA register is esp/rsp (the stack pointer).
1386 // We're checking that both of them have an unwind rule like "CFA=esp+4" or CFA+rsp+8".
1388 if (first_row->GetCFAValue().GetValueType() == last_row->GetCFAValue().GetValueType()
1389 && first_row->GetCFAValue().GetRegisterNumber() == last_row->GetCFAValue().GetRegisterNumber()
1390 && first_row->GetCFAValue().GetOffset() == last_row->GetCFAValue().GetOffset())
1392 // Get the register locations for eip/rip from the first & last rows.
1393 // Are they both CFA plus an offset? Is it the same offset?
1395 UnwindPlan::Row::RegisterLocation last_row_pc_loc;
1396 if (last_row->GetRegisterInfo (pc_regnum.GetAsKind (unwind_plan.GetRegisterKind()), last_row_pc_loc))
1398 if (last_row_pc_loc.IsAtCFAPlusOffset()
1399 && first_row_pc_loc.GetOffset() == last_row_pc_loc.GetOffset())
1402 // One last sanity check: Is the unwind rule for getting the caller pc value
1403 // "deref the CFA-4" or "deref the CFA-8"?
1405 // If so, we have an UnwindPlan that already describes the epilogue and we don't need
1406 // to modify it at all.
1408 if (first_row_pc_loc.GetOffset() == -wordsize)
1410 do_augment_unwindplan = false;
1417 if (do_augment_unwindplan)
1419 ExecutionContext exe_ctx (thread.shared_from_this());
1420 AssemblyParse_x86 asm_parse(exe_ctx, m_cpu, m_arch, func);
1421 return asm_parse.augment_unwind_plan_from_call_site (func, unwind_plan);
1428 UnwindAssembly_x86::GetFastUnwindPlan (AddressRange& func, Thread& thread, UnwindPlan &unwind_plan)
1432 // 89 e5 movl %esp, %ebp
1435 // 48 89 e5 movq %rsp, %rbp
1437 // We should pull in the ABI architecture default unwind plan and return that
1439 llvm::SmallVector <uint8_t, 4> opcode_data;
1441 ProcessSP process_sp = thread.GetProcess();
1444 Target &target (process_sp->GetTarget());
1445 const bool prefer_file_cache = true;
1447 if (target.ReadMemory (func.GetBaseAddress (), prefer_file_cache, opcode_data.data(),
1450 uint8_t i386_push_mov[] = {0x55, 0x89, 0xe5};
1451 uint8_t x86_64_push_mov[] = {0x55, 0x48, 0x89, 0xe5};
1453 if (memcmp (opcode_data.data(), i386_push_mov, sizeof (i386_push_mov)) == 0
1454 || memcmp (opcode_data.data(), x86_64_push_mov, sizeof (x86_64_push_mov)) == 0)
1456 ABISP abi_sp = process_sp->GetABI();
1459 return abi_sp->CreateDefaultUnwindPlan (unwind_plan);
1468 UnwindAssembly_x86::FirstNonPrologueInsn (AddressRange& func, const ExecutionContext &exe_ctx, Address& first_non_prologue_insn)
1470 AssemblyParse_x86 asm_parse(exe_ctx, m_cpu, m_arch, func);
1471 return asm_parse.find_first_non_prologue_insn (first_non_prologue_insn);
1475 UnwindAssembly_x86::CreateInstance (const ArchSpec &arch)
1477 const llvm::Triple::ArchType cpu = arch.GetMachine ();
1478 if (cpu == llvm::Triple::x86)
1479 return new UnwindAssembly_x86 (arch, k_i386);
1480 else if (cpu == llvm::Triple::x86_64)
1481 return new UnwindAssembly_x86 (arch, k_x86_64);
1486 //------------------------------------------------------------------
1487 // PluginInterface protocol in UnwindAssemblyParser_x86
1488 //------------------------------------------------------------------
1491 UnwindAssembly_x86::GetPluginName()
1493 return GetPluginNameStatic();
1498 UnwindAssembly_x86::GetPluginVersion()
1504 UnwindAssembly_x86::Initialize()
1506 PluginManager::RegisterPlugin (GetPluginNameStatic(),
1507 GetPluginDescriptionStatic(),
1512 UnwindAssembly_x86::Terminate()
1514 PluginManager::UnregisterPlugin (CreateInstance);
1518 lldb_private::ConstString
1519 UnwindAssembly_x86::GetPluginNameStatic()
1521 static ConstString g_name("x86");
1526 UnwindAssembly_x86::GetPluginDescriptionStatic()
1528 return "i386 and x86_64 assembly language profiler plugin.";