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/Support/TargetSelect.h"
15 #include "lldb/Core/Address.h"
16 #include "lldb/Core/Error.h"
17 #include "lldb/Core/ArchSpec.h"
18 #include "lldb/Core/PluginManager.h"
19 #include "lldb/Symbol/UnwindPlan.h"
20 #include "lldb/Target/ExecutionContext.h"
21 #include "lldb/Target/Process.h"
22 #include "lldb/Target/RegisterContext.h"
23 #include "lldb/Target/Thread.h"
24 #include "lldb/Target/Target.h"
25 #include "lldb/Target/UnwindAssembly.h"
26 #include "lldb/Utility/RegisterNumber.h"
29 using namespace lldb_private;
37 enum i386_register_numbers
50 enum x86_64_register_numbers
78 static struct regmap_ent i386_register_map[] =
80 {"eax", k_machine_eax, -1},
81 {"ecx", k_machine_ecx, -1},
82 {"edx", k_machine_edx, -1},
83 {"ebx", k_machine_ebx, -1},
84 {"esp", k_machine_esp, -1},
85 {"ebp", k_machine_ebp, -1},
86 {"esi", k_machine_esi, -1},
87 {"edi", k_machine_edi, -1},
88 {"eip", k_machine_eip, -1}
91 const int size_of_i386_register_map = llvm::array_lengthof (i386_register_map);
93 static int i386_register_map_initialized = 0;
95 static struct regmap_ent x86_64_register_map[] =
97 {"rax", k_machine_rax, -1},
98 {"rcx", k_machine_rcx, -1},
99 {"rdx", k_machine_rdx, -1},
100 {"rbx", k_machine_rbx, -1},
101 {"rsp", k_machine_rsp, -1},
102 {"rbp", k_machine_rbp, -1},
103 {"rsi", k_machine_rsi, -1},
104 {"rdi", k_machine_rdi, -1},
105 {"r8", k_machine_r8, -1},
106 {"r9", k_machine_r9, -1},
107 {"r10", k_machine_r10, -1},
108 {"r11", k_machine_r11, -1},
109 {"r12", k_machine_r12, -1},
110 {"r13", k_machine_r13, -1},
111 {"r14", k_machine_r14, -1},
112 {"r15", k_machine_r15, -1},
113 {"rip", k_machine_rip, -1}
116 const int size_of_x86_64_register_map = llvm::array_lengthof (x86_64_register_map);
118 static int x86_64_register_map_initialized = 0;
120 //-----------------------------------------------------------------------------------------------
121 // AssemblyParse_x86 local-file class definition & implementation functions
122 //-----------------------------------------------------------------------------------------------
124 class AssemblyParse_x86
128 AssemblyParse_x86 (const ExecutionContext &exe_ctx, int cpu, ArchSpec &arch, AddressRange func);
130 ~AssemblyParse_x86 ();
132 bool get_non_call_site_unwind_plan (UnwindPlan &unwind_plan);
134 bool augment_unwind_plan_from_call_site (AddressRange& func, UnwindPlan &unwind_plan);
136 bool get_fast_unwind_plan (AddressRange& func, UnwindPlan &unwind_plan);
138 bool find_first_non_prologue_insn (Address &address);
141 enum { kMaxInstructionByteSize = 32 };
143 bool nonvolatile_reg_p (int machine_regno);
144 bool push_rbp_pattern_p ();
145 bool push_0_pattern_p ();
146 bool mov_rsp_rbp_pattern_p ();
147 bool sub_rsp_pattern_p (int& amount);
148 bool add_rsp_pattern_p (int& amount);
149 bool push_reg_p (int& regno);
150 bool pop_reg_p (int& regno);
151 bool push_imm_pattern_p ();
152 bool mov_reg_to_local_stack_frame_p (int& regno, int& fp_offset);
153 bool ret_pattern_p ();
154 bool pop_rbp_pattern_p ();
155 bool call_next_insn_pattern_p();
156 uint32_t extract_4 (uint8_t *b);
157 bool machine_regno_to_lldb_regno (int machine_regno, uint32_t& lldb_regno);
158 bool instruction_length (Address addr, int &length);
160 const ExecutionContext m_exe_ctx;
162 AddressRange m_func_bounds;
165 uint8_t m_cur_insn_bytes[kMaxInstructionByteSize];
167 uint32_t m_machine_ip_regnum;
168 uint32_t m_machine_sp_regnum;
169 uint32_t m_machine_fp_regnum;
171 uint32_t m_lldb_ip_regnum;
172 uint32_t m_lldb_sp_regnum;
173 uint32_t m_lldb_fp_regnum;
178 ::LLVMDisasmContextRef m_disasm_context;
180 DISALLOW_COPY_AND_ASSIGN (AssemblyParse_x86);
183 AssemblyParse_x86::AssemblyParse_x86 (const ExecutionContext &exe_ctx, int cpu, ArchSpec &arch, AddressRange func) :
187 m_machine_ip_regnum (LLDB_INVALID_REGNUM),
188 m_machine_sp_regnum (LLDB_INVALID_REGNUM),
189 m_machine_fp_regnum (LLDB_INVALID_REGNUM),
190 m_lldb_ip_regnum (LLDB_INVALID_REGNUM),
191 m_lldb_sp_regnum (LLDB_INVALID_REGNUM),
192 m_lldb_fp_regnum (LLDB_INVALID_REGNUM),
197 int *initialized_flag = NULL;
200 m_machine_ip_regnum = k_machine_eip;
201 m_machine_sp_regnum = k_machine_esp;
202 m_machine_fp_regnum = k_machine_ebp;
204 initialized_flag = &i386_register_map_initialized;
208 m_machine_ip_regnum = k_machine_rip;
209 m_machine_sp_regnum = k_machine_rsp;
210 m_machine_fp_regnum = k_machine_rbp;
212 initialized_flag = &x86_64_register_map_initialized;
215 // we only look at prologue - it will be complete earlier than 512 bytes into func
216 if (m_func_bounds.GetByteSize() == 0)
217 m_func_bounds.SetByteSize(512);
219 Thread *thread = m_exe_ctx.GetThreadPtr();
220 if (thread && *initialized_flag == 0)
222 RegisterContext *reg_ctx = thread->GetRegisterContext().get();
225 struct regmap_ent *ent;
229 ent = i386_register_map;
230 count = size_of_i386_register_map;
234 ent = x86_64_register_map;
235 count = size_of_x86_64_register_map;
237 for (i = 0; i < count; i++, ent++)
239 const RegisterInfo *ri = reg_ctx->GetRegisterInfoByName (ent->name);
241 ent->lldb_regno = ri->kinds[eRegisterKindLLDB];
243 *initialized_flag = 1;
247 // on initial construction we may not have a Thread so these have to remain
248 // uninitialized until we can get a RegisterContext to set up the register map table
249 if (*initialized_flag == 1)
252 if (machine_regno_to_lldb_regno (m_machine_sp_regnum, lldb_regno))
253 m_lldb_sp_regnum = lldb_regno;
254 if (machine_regno_to_lldb_regno (m_machine_fp_regnum, lldb_regno))
255 m_lldb_fp_regnum = lldb_regno;
256 if (machine_regno_to_lldb_regno (m_machine_ip_regnum, lldb_regno))
257 m_lldb_ip_regnum = lldb_regno;
260 m_disasm_context = ::LLVMCreateDisasm(m_arch.GetTriple().getTriple().c_str(),
267 AssemblyParse_x86::~AssemblyParse_x86 ()
269 ::LLVMDisasmDispose(m_disasm_context);
272 // This function expects an x86 native register number (i.e. the bits stripped out of the
273 // actual instruction), not an lldb register number.
276 AssemblyParse_x86::nonvolatile_reg_p (int machine_regno)
280 switch (machine_regno)
283 case k_machine_ebp: // not actually a nonvolatile but often treated as such by convention
292 if (m_cpu == k_x86_64)
294 switch (machine_regno)
298 case k_machine_rbp: // not actually a nonvolatile but often treated as such by convention
312 // Macro to detect if this is a REX mode prefix byte.
313 #define REX_W_PREFIX_P(opcode) (((opcode) & (~0x5)) == 0x48)
315 // The high bit which should be added to the source register number (the "R" bit)
316 #define REX_W_SRCREG(opcode) (((opcode) & 0x4) >> 2)
318 // The high bit which should be added to the destination register number (the "B" bit)
319 #define REX_W_DSTREG(opcode) ((opcode) & 0x1)
323 AssemblyParse_x86::push_rbp_pattern_p ()
325 uint8_t *p = m_cur_insn_bytes;
331 // pushq $0 ; the first instruction in start() [0x6a 0x00]
333 AssemblyParse_x86::push_0_pattern_p ()
335 uint8_t *p = m_cur_insn_bytes;
336 if (*p == 0x6a && *(p + 1) == 0x0)
344 AssemblyParse_x86::push_imm_pattern_p ()
346 uint8_t *p = m_cur_insn_bytes;
347 if (*p == 0x68 || *p == 0x6a)
352 // movq %rsp, %rbp [0x48 0x8b 0xec] or [0x48 0x89 0xe5]
353 // movl %esp, %ebp [0x8b 0xec] or [0x89 0xe5]
355 AssemblyParse_x86::mov_rsp_rbp_pattern_p ()
357 uint8_t *p = m_cur_insn_bytes;
358 if (m_wordsize == 8 && *p == 0x48)
360 if (*(p) == 0x8b && *(p + 1) == 0xec)
362 if (*(p) == 0x89 && *(p + 1) == 0xe5)
369 AssemblyParse_x86::sub_rsp_pattern_p (int& amount)
371 uint8_t *p = m_cur_insn_bytes;
372 if (m_wordsize == 8 && *p == 0x48)
374 // 8-bit immediate operand
375 if (*p == 0x83 && *(p + 1) == 0xec)
377 amount = (int8_t) *(p + 2);
380 // 32-bit immediate operand
381 if (*p == 0x81 && *(p + 1) == 0xec)
383 amount = (int32_t) extract_4 (p + 2);
391 AssemblyParse_x86::add_rsp_pattern_p (int& amount)
393 uint8_t *p = m_cur_insn_bytes;
394 if (m_wordsize == 8 && *p == 0x48)
396 // 8-bit immediate operand
397 if (*p == 0x83 && *(p + 1) == 0xc4)
399 amount = (int8_t) *(p + 2);
402 // 32-bit immediate operand
403 if (*p == 0x81 && *(p + 1) == 0xc4)
405 amount = (int32_t) extract_4 (p + 2);
414 AssemblyParse_x86::push_reg_p (int& regno)
416 uint8_t *p = m_cur_insn_bytes;
417 int regno_prefix_bit = 0;
418 // If we have a rex prefix byte, check to see if a B bit is set
419 if (m_wordsize == 8 && *p == 0x41)
421 regno_prefix_bit = 1 << 3;
424 if (*p >= 0x50 && *p <= 0x57)
426 regno = (*p - 0x50) | regno_prefix_bit;
435 AssemblyParse_x86::pop_reg_p (int& regno)
437 uint8_t *p = m_cur_insn_bytes;
438 int regno_prefix_bit = 0;
439 // If we have a rex prefix byte, check to see if a B bit is set
440 if (m_wordsize == 8 && *p == 0x41)
442 regno_prefix_bit = 1 << 3;
445 if (*p >= 0x58 && *p <= 0x5f)
447 regno = (*p - 0x58) | regno_prefix_bit;
456 AssemblyParse_x86::pop_rbp_pattern_p ()
458 uint8_t *p = m_cur_insn_bytes;
462 // call $0 [0xe8 0x0 0x0 0x0 0x0]
464 AssemblyParse_x86::call_next_insn_pattern_p ()
466 uint8_t *p = m_cur_insn_bytes;
467 return (*p == 0xe8) && (*(p+1) == 0x0) && (*(p+2) == 0x0)
468 && (*(p+3) == 0x0) && (*(p+4) == 0x0);
471 // Look for an instruction sequence storing a nonvolatile register
472 // on to the stack frame.
474 // movq %rax, -0x10(%rbp) [0x48 0x89 0x45 0xf0]
475 // movl %eax, -0xc(%ebp) [0x89 0x45 0xf4]
477 // The offset value returned in rbp_offset will be positive --
478 // but it must be subtraced from the frame base register to get
479 // the actual location. The positive value returned for the offset
480 // is a convention used elsewhere for CFA offsets et al.
483 AssemblyParse_x86::mov_reg_to_local_stack_frame_p (int& regno, int& rbp_offset)
485 uint8_t *p = m_cur_insn_bytes;
486 int src_reg_prefix_bit = 0;
487 int target_reg_prefix_bit = 0;
489 if (m_wordsize == 8 && REX_W_PREFIX_P (*p))
491 src_reg_prefix_bit = REX_W_SRCREG (*p) << 3;
492 target_reg_prefix_bit = REX_W_DSTREG (*p) << 3;
493 if (target_reg_prefix_bit == 1)
495 // rbp/ebp don't need a prefix bit - we know this isn't the
496 // reg we care about.
504 /* Mask off the 3-5 bits which indicate the destination register
505 if this is a ModR/M byte. */
506 int opcode_destreg_masked_out = *(p + 1) & (~0x38);
508 /* Is this a ModR/M byte with Mod bits 01 and R/M bits 101
509 and three bits between them, e.g. 01nnn101
510 We're looking for a destination of ebp-disp8 or ebp-disp32. */
512 if (opcode_destreg_masked_out == 0x45)
514 else if (opcode_destreg_masked_out == 0x85)
521 offset = (int8_t) *(p + 2);
523 offset = (uint32_t) extract_4 (p + 2);
527 regno = ((*(p + 1) >> 3) & 0x7) | src_reg_prefix_bit;
528 rbp_offset = offset > 0 ? offset : -offset;
534 // ret [0xc9] or [0xc2 imm8] or [0xca imm8]
536 AssemblyParse_x86::ret_pattern_p ()
538 uint8_t *p = m_cur_insn_bytes;
539 if (*p == 0xc9 || *p == 0xc2 || *p == 0xca || *p == 0xc3)
545 AssemblyParse_x86::extract_4 (uint8_t *b)
548 for (int i = 3; i >= 0; i--)
554 AssemblyParse_x86::machine_regno_to_lldb_regno (int machine_regno, uint32_t &lldb_regno)
556 struct regmap_ent *ent;
560 ent = i386_register_map;
561 count = size_of_i386_register_map;
565 ent = x86_64_register_map;
566 count = size_of_x86_64_register_map;
568 for (i = 0; i < count; i++, ent++)
570 if (ent->machine_regno == machine_regno)
571 if (ent->lldb_regno != -1)
573 lldb_regno = ent->lldb_regno;
581 AssemblyParse_x86::instruction_length (Address addr, int &length)
583 const uint32_t max_op_byte_size = m_arch.GetMaximumOpcodeByteSize();
584 llvm::SmallVector <uint8_t, 32> opcode_data;
585 opcode_data.resize (max_op_byte_size);
590 const bool prefer_file_cache = true;
592 Target *target = m_exe_ctx.GetTargetPtr();
593 if (target->ReadMemory (addr, prefer_file_cache, opcode_data.data(),
594 max_op_byte_size, error) == static_cast<size_t>(-1))
599 char out_string[512];
600 const addr_t pc = addr.GetFileAddress();
601 const size_t inst_size = ::LLVMDisasmInstruction (m_disasm_context,
614 AssemblyParse_x86::get_non_call_site_unwind_plan (UnwindPlan &unwind_plan)
616 UnwindPlan::RowSP row(new UnwindPlan::Row);
617 m_cur_insn = m_func_bounds.GetBaseAddress ();
618 int current_func_text_offset = 0;
619 int current_sp_bytes_offset_from_cfa = 0;
620 UnwindPlan::Row::RegisterLocation initial_regloc;
623 if (!m_cur_insn.IsValid())
628 unwind_plan.SetPlanValidAddressRange (m_func_bounds);
629 unwind_plan.SetRegisterKind (eRegisterKindLLDB);
631 // At the start of the function, find the CFA by adding wordsize to the SP register
632 row->SetOffset (current_func_text_offset);
633 row->SetCFARegister (m_lldb_sp_regnum);
634 row->SetCFAOffset (m_wordsize);
636 // caller's stack pointer value before the call insn is the CFA address
637 initial_regloc.SetIsCFAPlusOffset (0);
638 row->SetRegisterInfo (m_lldb_sp_regnum, initial_regloc);
640 // saved instruction pointer can be found at CFA - wordsize.
641 current_sp_bytes_offset_from_cfa = m_wordsize;
642 initial_regloc.SetAtCFAPlusOffset (-current_sp_bytes_offset_from_cfa);
643 row->SetRegisterInfo (m_lldb_ip_regnum, initial_regloc);
645 unwind_plan.AppendRow (row);
647 // Allocate a new Row, populate it with the existing Row contents.
648 UnwindPlan::Row *newrow = new UnwindPlan::Row;
649 *newrow = *row.get();
652 // Track which registers have been saved so far in the prologue.
653 // If we see another push of that register, it's not part of the prologue.
654 // The register numbers used here are the machine register #'s
655 // (i386_register_numbers, x86_64_register_numbers).
656 std::vector<bool> saved_registers(32, false);
658 const bool prefer_file_cache = true;
660 // Once the prologue has completed we'll save a copy of the unwind instructions
661 // If there is an epilogue in the middle of the function, after that epilogue we'll reinstate
662 // the unwind setup -- we assume that some code path jumps over the mid-function epilogue
664 UnwindPlan::RowSP prologue_completed_row; // copy of prologue row of CFI
665 int prologue_completed_sp_bytes_offset_from_cfa; // The sp value before the epilogue started executed
666 std::vector<bool> prologue_completed_saved_registers;
668 Target *target = m_exe_ctx.GetTargetPtr();
669 while (m_func_bounds.ContainsFileAddress (m_cur_insn))
671 int stack_offset, insn_len;
672 int machine_regno; // register numbers masked directly out of instructions
673 uint32_t lldb_regno; // register numbers in lldb's eRegisterKindLLDB numbering scheme
675 bool in_epilogue = false; // we're in the middle of an epilogue sequence
676 bool row_updated = false; // The UnwindPlan::Row 'row' has been updated
678 if (!instruction_length (m_cur_insn, insn_len) || insn_len == 0 || insn_len > kMaxInstructionByteSize)
680 // An unrecognized/junk instruction
684 if (target->ReadMemory (m_cur_insn, prefer_file_cache, m_cur_insn_bytes,
685 insn_len, error) == static_cast<size_t>(-1))
687 // Error reading the instruction out of the file, stop scanning
691 if (push_rbp_pattern_p ())
693 current_sp_bytes_offset_from_cfa += m_wordsize;
694 row->SetCFAOffset (current_sp_bytes_offset_from_cfa);
695 UnwindPlan::Row::RegisterLocation regloc;
696 regloc.SetAtCFAPlusOffset (-row->GetCFAOffset());
697 row->SetRegisterInfo (m_lldb_fp_regnum, regloc);
698 saved_registers[m_machine_fp_regnum] = true;
702 else if (mov_rsp_rbp_pattern_p ())
704 row->SetCFARegister (m_lldb_fp_regnum);
708 // This is the start() function (or a pthread equivalent), it starts with a pushl $0x0 which puts the
709 // saved pc value of 0 on the stack. In this case we want to pretend we didn't see a stack movement at all --
710 // normally the saved pc value is already on the stack by the time the function starts executing.
711 else if (push_0_pattern_p ())
715 else if (push_reg_p (machine_regno))
717 current_sp_bytes_offset_from_cfa += m_wordsize;
718 // the PUSH instruction has moved the stack pointer - if the CFA is set in terms of the stack pointer,
719 // we need to add a new row of instructions.
720 if (row->GetCFARegister() == m_lldb_sp_regnum)
722 row->SetCFAOffset (current_sp_bytes_offset_from_cfa);
725 // record where non-volatile (callee-saved, spilled) registers are saved on the stack
726 if (nonvolatile_reg_p (machine_regno)
727 && machine_regno_to_lldb_regno (machine_regno, lldb_regno)
728 && saved_registers[machine_regno] == false)
730 UnwindPlan::Row::RegisterLocation regloc;
731 regloc.SetAtCFAPlusOffset (-current_sp_bytes_offset_from_cfa);
732 row->SetRegisterInfo (lldb_regno, regloc);
733 saved_registers[machine_regno] = true;
738 else if (pop_reg_p (machine_regno))
740 current_sp_bytes_offset_from_cfa -= m_wordsize;
742 if (nonvolatile_reg_p (machine_regno)
743 && machine_regno_to_lldb_regno (machine_regno, lldb_regno)
744 && saved_registers[machine_regno] == true)
746 saved_registers[machine_regno] = false;
747 row->RemoveRegisterInfo (lldb_regno);
749 if (machine_regno == m_machine_fp_regnum)
751 row->SetCFARegister (m_lldb_sp_regnum);
758 // the POP instruction has moved the stack pointer - if the CFA is set in terms of the stack pointer,
759 // we need to add a new row of instructions.
760 if (row->GetCFARegister() == m_lldb_sp_regnum)
762 row->SetCFAOffset (current_sp_bytes_offset_from_cfa);
767 else if (mov_reg_to_local_stack_frame_p (machine_regno, stack_offset)
768 && nonvolatile_reg_p (machine_regno)
769 && machine_regno_to_lldb_regno (machine_regno, lldb_regno)
770 && saved_registers[machine_regno] == false)
772 saved_registers[machine_regno] = true;
774 UnwindPlan::Row::RegisterLocation regloc;
776 // stack_offset for 'movq %r15, -80(%rbp)' will be 80.
777 // In the Row, we want to express this as the offset from the CFA. If the frame base
778 // is rbp (like the above instruction), the CFA offset for rbp is probably 16. So we
779 // want to say that the value is stored at the CFA address - 96.
780 regloc.SetAtCFAPlusOffset (-(stack_offset + row->GetCFAOffset()));
782 row->SetRegisterInfo (lldb_regno, regloc);
787 else if (sub_rsp_pattern_p (stack_offset))
789 current_sp_bytes_offset_from_cfa += stack_offset;
790 if (row->GetCFARegister() == m_lldb_sp_regnum)
792 row->SetCFAOffset (current_sp_bytes_offset_from_cfa);
797 else if (add_rsp_pattern_p (stack_offset))
799 current_sp_bytes_offset_from_cfa -= stack_offset;
800 if (row->GetCFARegister() == m_lldb_sp_regnum)
802 row->SetCFAOffset (current_sp_bytes_offset_from_cfa);
808 else if (ret_pattern_p () && prologue_completed_row.get())
810 // Reinstate the saved prologue setup for any instructions
811 // that come after the ret instruction
813 UnwindPlan::Row *newrow = new UnwindPlan::Row;
814 *newrow = *prologue_completed_row.get();
816 current_sp_bytes_offset_from_cfa = prologue_completed_sp_bytes_offset_from_cfa;
818 saved_registers.clear();
819 saved_registers.resize(prologue_completed_saved_registers.size(), false);
820 for (size_t i = 0; i < prologue_completed_saved_registers.size(); ++i)
822 saved_registers[i] = prologue_completed_saved_registers[i];
829 // call next instruction
832 // This is used in i386 programs to get the PIC base address for finding global data
833 else if (call_next_insn_pattern_p ())
835 current_sp_bytes_offset_from_cfa += m_wordsize;
836 if (row->GetCFARegister() == m_lldb_sp_regnum)
838 row->SetCFAOffset (current_sp_bytes_offset_from_cfa);
845 if (current_func_text_offset + insn_len < m_func_bounds.GetByteSize())
847 row->SetOffset (current_func_text_offset + insn_len);
848 unwind_plan.AppendRow (row);
849 // Allocate a new Row, populate it with the existing Row contents.
850 newrow = new UnwindPlan::Row;
851 *newrow = *row.get();
856 if (in_epilogue == false && row_updated)
858 // If we're not in an epilogue sequence, save the updated Row
859 UnwindPlan::Row *newrow = new UnwindPlan::Row;
860 *newrow = *row.get();
861 prologue_completed_row.reset (newrow);
863 prologue_completed_saved_registers.clear();
864 prologue_completed_saved_registers.resize(saved_registers.size(), false);
865 for (size_t i = 0; i < saved_registers.size(); ++i)
867 prologue_completed_saved_registers[i] = saved_registers[i];
871 // We may change the sp value without adding a new Row necessarily -- keep
872 // track of it either way.
873 if (in_epilogue == false)
875 prologue_completed_sp_bytes_offset_from_cfa = current_sp_bytes_offset_from_cfa;
878 m_cur_insn.SetOffset (m_cur_insn.GetOffset() + insn_len);
879 current_func_text_offset += insn_len;
882 unwind_plan.SetSourceName ("assembly insn profiling");
883 unwind_plan.SetSourcedFromCompiler (eLazyBoolNo);
884 unwind_plan.SetUnwindPlanValidAtAllInstructions (eLazyBoolYes);
890 AssemblyParse_x86::augment_unwind_plan_from_call_site (AddressRange& func, UnwindPlan &unwind_plan)
892 // Is func address valid?
893 Address addr_start = func.GetBaseAddress();
894 if (!addr_start.IsValid())
897 // Is original unwind_plan valid?
898 // unwind_plan should have at least one row which is ABI-default (CFA register is sp),
899 // and another row in mid-function.
900 if (unwind_plan.GetRowCount() < 2)
902 UnwindPlan::RowSP first_row = unwind_plan.GetRowAtIndex (0);
903 if (first_row->GetOffset() != 0)
905 uint32_t cfa_reg = m_exe_ctx.GetThreadPtr()->GetRegisterContext()
906 ->ConvertRegisterKindToRegisterNumber (unwind_plan.GetRegisterKind(),
907 first_row->GetCFARegister());
908 if (cfa_reg != m_lldb_sp_regnum || first_row->GetCFAOffset() != m_wordsize)
911 UnwindPlan::RowSP original_last_row = unwind_plan.GetRowForFunctionOffset (-1);
913 Target *target = m_exe_ctx.GetTargetPtr();
914 m_cur_insn = func.GetBaseAddress();
917 bool unwind_plan_updated = false;
918 UnwindPlan::RowSP row(new UnwindPlan::Row(*first_row));
920 // After a mid-function epilogue we will need to re-insert the original unwind rules
921 // so unwinds work for the remainder of the function. These aren't common with clang/gcc
922 // on x86 but it is possible.
923 bool reinstate_unwind_state = false;
925 while (func.ContainsFileAddress (m_cur_insn))
928 if (!instruction_length (m_cur_insn, insn_len)
929 || insn_len == 0 || insn_len > kMaxInstructionByteSize)
931 // An unrecognized/junk instruction.
934 const bool prefer_file_cache = true;
936 if (target->ReadMemory (m_cur_insn, prefer_file_cache, m_cur_insn_bytes,
937 insn_len, error) == static_cast<size_t>(-1))
939 // Error reading the instruction out of the file, stop scanning.
945 m_cur_insn.SetOffset(m_cur_insn.GetOffset() + insn_len);
947 if (reinstate_unwind_state)
949 // that was the last instruction of this function
950 if (func.ContainsFileAddress (m_cur_insn) == false)
953 UnwindPlan::RowSP new_row(new UnwindPlan::Row());
954 *new_row = *original_last_row;
955 new_row->SetOffset (offset);
956 unwind_plan.AppendRow (new_row);
957 row.reset (new UnwindPlan::Row());
959 reinstate_unwind_state = false;
960 unwind_plan_updated = true;
964 // If we already have one row for this instruction, we can continue.
965 while (row_id < unwind_plan.GetRowCount()
966 && unwind_plan.GetRowAtIndex (row_id)->GetOffset() <= offset)
970 UnwindPlan::RowSP original_row = unwind_plan.GetRowAtIndex (row_id - 1);
971 if (original_row->GetOffset() == offset)
973 *row = *original_row;
979 // If we are here, compiler didn't generate CFI for prologue.
980 // This won't happen to GCC or clang.
981 // In this case, bail out directly.
985 // Inspect the instruction to check if we need a new row for it.
986 cfa_reg = m_exe_ctx.GetThreadPtr()->GetRegisterContext()
987 ->ConvertRegisterKindToRegisterNumber (unwind_plan.GetRegisterKind(),
988 row->GetCFARegister());
989 if (cfa_reg == m_lldb_sp_regnum)
991 // CFA register is sp.
993 // call next instruction
996 if (call_next_insn_pattern_p ())
998 row->SetOffset (offset);
999 row->SetCFAOffset (m_wordsize + row->GetCFAOffset());
1001 UnwindPlan::RowSP new_row(new UnwindPlan::Row(*row));
1002 unwind_plan.InsertRow (new_row);
1003 unwind_plan_updated = true;
1007 // push/pop register
1009 if (push_reg_p (regno))
1011 row->SetOffset (offset);
1012 row->SetCFAOffset (m_wordsize + row->GetCFAOffset());
1014 UnwindPlan::RowSP new_row(new UnwindPlan::Row(*row));
1015 unwind_plan.InsertRow (new_row);
1016 unwind_plan_updated = true;
1019 if (pop_reg_p (regno))
1021 // Technically, this might be a nonvolatile register recover in epilogue.
1022 // We should reset RegisterInfo for the register.
1023 // But in practice, previous rule for the register is still valid...
1024 // So we ignore this case.
1026 row->SetOffset (offset);
1027 row->SetCFAOffset (-m_wordsize + row->GetCFAOffset());
1029 UnwindPlan::RowSP new_row(new UnwindPlan::Row(*row));
1030 unwind_plan.InsertRow (new_row);
1031 unwind_plan_updated = true;
1036 if (push_imm_pattern_p ())
1038 row->SetOffset (offset);
1039 row->SetCFAOffset (m_wordsize + row->GetCFAOffset());
1040 UnwindPlan::RowSP new_row(new UnwindPlan::Row(*row));
1041 unwind_plan.InsertRow (new_row);
1042 unwind_plan_updated = true;
1046 // add/sub %rsp/%esp
1048 if (add_rsp_pattern_p (amount))
1050 row->SetOffset (offset);
1051 row->SetCFAOffset (-amount + row->GetCFAOffset());
1053 UnwindPlan::RowSP new_row(new UnwindPlan::Row(*row));
1054 unwind_plan.InsertRow (new_row);
1055 unwind_plan_updated = true;
1058 if (sub_rsp_pattern_p (amount))
1060 row->SetOffset (offset);
1061 row->SetCFAOffset (amount + row->GetCFAOffset());
1063 UnwindPlan::RowSP new_row(new UnwindPlan::Row(*row));
1064 unwind_plan.InsertRow (new_row);
1065 unwind_plan_updated = true;
1068 if (ret_pattern_p ())
1070 reinstate_unwind_state = true;
1074 else if (cfa_reg == m_lldb_fp_regnum)
1076 // CFA register is fp.
1078 // The only case we care about is epilogue:
1079 // [0x5d] pop %rbp/%ebp
1081 if (pop_rbp_pattern_p ())
1083 if (target->ReadMemory (m_cur_insn, prefer_file_cache, m_cur_insn_bytes,
1084 1, error) != static_cast<size_t>(-1)
1085 && ret_pattern_p ())
1087 row->SetOffset (offset);
1088 row->SetCFARegister (first_row->GetCFARegister());
1089 row->SetCFAOffset (m_wordsize);
1091 UnwindPlan::RowSP new_row(new UnwindPlan::Row(*row));
1092 unwind_plan.InsertRow (new_row);
1093 unwind_plan_updated = true;
1094 reinstate_unwind_state = true;
1101 // CFA register is not sp or fp.
1103 // This must be hand-written assembly.
1104 // Just trust eh_frame and assume we have finished.
1109 unwind_plan.SetPlanValidAddressRange (func);
1110 if (unwind_plan_updated)
1112 std::string unwind_plan_source (unwind_plan.GetSourceName().AsCString());
1113 unwind_plan_source += " plus augmentation from assembly parsing";
1114 unwind_plan.SetSourceName (unwind_plan_source.c_str());
1115 unwind_plan.SetSourcedFromCompiler (eLazyBoolNo);
1116 unwind_plan.SetUnwindPlanValidAtAllInstructions (eLazyBoolYes);
1121 /* The "fast unwind plan" is valid for functions that follow the usual convention of
1122 using the frame pointer register (ebp, rbp), i.e. the function prologue looks like
1124 mov %rsp,%rbp [0x48 0x89 0xe5] (this is a 2-byte insn seq on i386)
1128 AssemblyParse_x86::get_fast_unwind_plan (AddressRange& func, UnwindPlan &unwind_plan)
1130 UnwindPlan::RowSP row(new UnwindPlan::Row);
1131 UnwindPlan::Row::RegisterLocation pc_reginfo;
1132 UnwindPlan::Row::RegisterLocation sp_reginfo;
1133 UnwindPlan::Row::RegisterLocation fp_reginfo;
1134 unwind_plan.SetRegisterKind (eRegisterKindLLDB);
1136 if (!func.GetBaseAddress().IsValid())
1139 Target *target = m_exe_ctx.GetTargetPtr();
1143 const bool prefer_file_cache = true;
1144 if (target->ReadMemory (func.GetBaseAddress(), prefer_file_cache, bytebuf,
1145 sizeof (bytebuf), error) == static_cast<size_t>(-1))
1148 uint8_t i386_prologue[] = {0x55, 0x89, 0xe5};
1149 uint8_t x86_64_prologue[] = {0x55, 0x48, 0x89, 0xe5};
1152 if (memcmp (bytebuf, i386_prologue, sizeof (i386_prologue)) == 0)
1154 prologue_size = sizeof (i386_prologue);
1156 else if (memcmp (bytebuf, x86_64_prologue, sizeof (x86_64_prologue)) == 0)
1158 prologue_size = sizeof (x86_64_prologue);
1165 pc_reginfo.SetAtCFAPlusOffset (-m_wordsize);
1166 row->SetRegisterInfo (m_lldb_ip_regnum, pc_reginfo);
1168 sp_reginfo.SetIsCFAPlusOffset (0);
1169 row->SetRegisterInfo (m_lldb_sp_regnum, sp_reginfo);
1171 // Zero instructions into the function
1172 row->SetCFARegister (m_lldb_sp_regnum);
1173 row->SetCFAOffset (m_wordsize);
1175 unwind_plan.AppendRow (row);
1176 UnwindPlan::Row *newrow = new UnwindPlan::Row;
1177 *newrow = *row.get();
1180 // push %rbp has executed - stack moved, rbp now saved
1181 row->SetCFAOffset (2 * m_wordsize);
1182 fp_reginfo.SetAtCFAPlusOffset (2 * -m_wordsize);
1183 row->SetRegisterInfo (m_lldb_fp_regnum, fp_reginfo);
1185 unwind_plan.AppendRow (row);
1187 newrow = new UnwindPlan::Row;
1188 *newrow = *row.get();
1191 // mov %rsp, %rbp has executed
1192 row->SetCFARegister (m_lldb_fp_regnum);
1193 row->SetCFAOffset (2 * m_wordsize);
1194 row->SetOffset (prologue_size); /// 3 or 4 bytes depending on arch
1195 unwind_plan.AppendRow (row);
1197 newrow = new UnwindPlan::Row;
1198 *newrow = *row.get();
1201 unwind_plan.SetPlanValidAddressRange (func);
1202 unwind_plan.SetSourceName ("fast unwind assembly profiling");
1203 unwind_plan.SetSourcedFromCompiler (eLazyBoolNo);
1204 unwind_plan.SetUnwindPlanValidAtAllInstructions (eLazyBoolNo);
1209 AssemblyParse_x86::find_first_non_prologue_insn (Address &address)
1211 m_cur_insn = m_func_bounds.GetBaseAddress ();
1212 if (!m_cur_insn.IsValid())
1217 const bool prefer_file_cache = true;
1218 Target *target = m_exe_ctx.GetTargetPtr();
1219 while (m_func_bounds.ContainsFileAddress (m_cur_insn))
1222 int insn_len, offset, regno;
1223 if (!instruction_length (m_cur_insn, insn_len) || insn_len > kMaxInstructionByteSize || insn_len == 0)
1225 // An error parsing the instruction, i.e. probably data/garbage - stop scanning
1228 if (target->ReadMemory (m_cur_insn, prefer_file_cache, m_cur_insn_bytes,
1229 insn_len, error) == static_cast<size_t>(-1))
1231 // Error reading the instruction out of the file, stop scanning
1235 if (push_rbp_pattern_p () || mov_rsp_rbp_pattern_p () || sub_rsp_pattern_p (offset)
1236 || push_reg_p (regno) || mov_reg_to_local_stack_frame_p (regno, offset))
1238 m_cur_insn.SetOffset (m_cur_insn.GetOffset() + insn_len);
1242 // Unknown non-prologue instruction - stop scanning
1246 address = m_cur_insn;
1255 //-----------------------------------------------------------------------------------------------
1256 // UnwindAssemblyParser_x86 method definitions
1257 //-----------------------------------------------------------------------------------------------
1259 UnwindAssembly_x86::UnwindAssembly_x86 (const ArchSpec &arch, int cpu) :
1260 lldb_private::UnwindAssembly(arch),
1267 UnwindAssembly_x86::~UnwindAssembly_x86 ()
1272 UnwindAssembly_x86::GetNonCallSiteUnwindPlanFromAssembly (AddressRange& func, Thread& thread, UnwindPlan& unwind_plan)
1274 ExecutionContext exe_ctx (thread.shared_from_this());
1275 AssemblyParse_x86 asm_parse(exe_ctx, m_cpu, m_arch, func);
1276 return asm_parse.get_non_call_site_unwind_plan (unwind_plan);
1280 UnwindAssembly_x86::AugmentUnwindPlanFromCallSite (AddressRange& func, Thread& thread, UnwindPlan& unwind_plan)
1282 bool do_augment_unwindplan = true;
1284 UnwindPlan::RowSP first_row = unwind_plan.GetRowForFunctionOffset (0);
1285 UnwindPlan::RowSP last_row = unwind_plan.GetRowForFunctionOffset (-1);
1288 ProcessSP process_sp (thread.GetProcess());
1291 wordsize = process_sp->GetTarget().GetArchitecture().GetAddressByteSize();
1294 RegisterNumber sp_regnum (thread, eRegisterKindGeneric, LLDB_REGNUM_GENERIC_SP);
1295 RegisterNumber pc_regnum (thread, eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC);
1297 // Does this UnwindPlan describe the prologue? I want to see that the CFA is set
1298 // in terms of the stack pointer plus an offset, and I want to see that rip is
1299 // retrieved at the CFA-wordsize.
1300 // If there is no description of the prologue, don't try to augment this eh_frame
1301 // unwinder code, fall back to assembly parsing instead.
1303 if (first_row->GetCFAType() != UnwindPlan::Row::CFAType::CFAIsRegisterPlusOffset
1304 || RegisterNumber (thread, unwind_plan.GetRegisterKind(), first_row->GetCFARegister()) != sp_regnum
1305 || first_row->GetCFAOffset() != wordsize)
1309 UnwindPlan::Row::RegisterLocation first_row_pc_loc;
1310 if (first_row->GetRegisterInfo (pc_regnum.GetAsKind (unwind_plan.GetRegisterKind()), first_row_pc_loc) == false
1311 || first_row_pc_loc.IsAtCFAPlusOffset() == false
1312 || first_row_pc_loc.GetOffset() != -wordsize)
1318 // It looks like the prologue is described.
1319 // Is the epilogue described? If it is, no need to do any augmentation.
1321 if (first_row != last_row && first_row->GetOffset() != last_row->GetOffset())
1323 // The first & last row have the same CFA register
1324 // and the same CFA offset value
1325 // and the CFA register is esp/rsp (the stack pointer).
1327 // We're checking that both of them have an unwind rule like "CFA=esp+4" or CFA+rsp+8".
1329 if (first_row->GetCFAType() == last_row->GetCFAType()
1330 && first_row->GetCFARegister() == last_row->GetCFARegister()
1331 && first_row->GetCFAOffset() == last_row->GetCFAOffset())
1333 // Get the register locations for eip/rip from the first & last rows.
1334 // Are they both CFA plus an offset? Is it the same offset?
1336 UnwindPlan::Row::RegisterLocation last_row_pc_loc;
1337 if (last_row->GetRegisterInfo (pc_regnum.GetAsKind (unwind_plan.GetRegisterKind()), last_row_pc_loc))
1339 if (last_row_pc_loc.IsAtCFAPlusOffset()
1340 && first_row_pc_loc.GetOffset() == last_row_pc_loc.GetOffset())
1343 // One last sanity check: Is the unwind rule for getting the caller pc value
1344 // "deref the CFA-4" or "deref the CFA-8"?
1346 // If so, we have an UnwindPlan that already describes the epilogue and we don't need
1347 // to modify it at all.
1349 if (first_row_pc_loc.GetOffset() == -wordsize)
1351 do_augment_unwindplan = false;
1358 if (do_augment_unwindplan)
1360 ExecutionContext exe_ctx (thread.shared_from_this());
1361 AssemblyParse_x86 asm_parse(exe_ctx, m_cpu, m_arch, func);
1362 return asm_parse.augment_unwind_plan_from_call_site (func, unwind_plan);
1369 UnwindAssembly_x86::GetFastUnwindPlan (AddressRange& func, Thread& thread, UnwindPlan &unwind_plan)
1373 // 89 e5 movl %esp, %ebp
1376 // 48 89 e5 movq %rsp, %rbp
1378 // We should pull in the ABI architecture default unwind plan and return that
1380 llvm::SmallVector <uint8_t, 4> opcode_data;
1382 ProcessSP process_sp = thread.GetProcess();
1385 Target &target (process_sp->GetTarget());
1386 const bool prefer_file_cache = true;
1388 if (target.ReadMemory (func.GetBaseAddress (), prefer_file_cache, opcode_data.data(),
1391 uint8_t i386_push_mov[] = {0x55, 0x89, 0xe5};
1392 uint8_t x86_64_push_mov[] = {0x55, 0x48, 0x89, 0xe5};
1394 if (memcmp (opcode_data.data(), i386_push_mov, sizeof (i386_push_mov)) == 0
1395 || memcmp (opcode_data.data(), x86_64_push_mov, sizeof (x86_64_push_mov)) == 0)
1397 ABISP abi_sp = process_sp->GetABI();
1400 return abi_sp->CreateDefaultUnwindPlan (unwind_plan);
1409 UnwindAssembly_x86::FirstNonPrologueInsn (AddressRange& func, const ExecutionContext &exe_ctx, Address& first_non_prologue_insn)
1411 AssemblyParse_x86 asm_parse(exe_ctx, m_cpu, m_arch, func);
1412 return asm_parse.find_first_non_prologue_insn (first_non_prologue_insn);
1416 UnwindAssembly_x86::CreateInstance (const ArchSpec &arch)
1418 const llvm::Triple::ArchType cpu = arch.GetMachine ();
1419 if (cpu == llvm::Triple::x86)
1420 return new UnwindAssembly_x86 (arch, k_i386);
1421 else if (cpu == llvm::Triple::x86_64)
1422 return new UnwindAssembly_x86 (arch, k_x86_64);
1427 //------------------------------------------------------------------
1428 // PluginInterface protocol in UnwindAssemblyParser_x86
1429 //------------------------------------------------------------------
1432 UnwindAssembly_x86::GetPluginName()
1434 return GetPluginNameStatic();
1439 UnwindAssembly_x86::GetPluginVersion()
1445 UnwindAssembly_x86::Initialize()
1447 PluginManager::RegisterPlugin (GetPluginNameStatic(),
1448 GetPluginDescriptionStatic(),
1453 UnwindAssembly_x86::Terminate()
1455 PluginManager::UnregisterPlugin (CreateInstance);
1459 lldb_private::ConstString
1460 UnwindAssembly_x86::GetPluginNameStatic()
1462 static ConstString g_name("x86");
1467 UnwindAssembly_x86::GetPluginDescriptionStatic()
1469 return "i386 and x86_64 assembly language profiler plugin.";