1 //===-- x86AssemblyInspectionEngine.cpp -------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "x86AssemblyInspectionEngine.h"
11 
12 #include "llvm-c/Disassembler.h"
13 
14 #include "lldb/Core/Address.h"
15 #include "lldb/Symbol/UnwindPlan.h"
16 #include "lldb/Target/RegisterContext.h"
17 #include "lldb/Target/UnwindAssembly.h"
18 
19 using namespace lldb_private;
20 using namespace lldb;
21 
22 x86AssemblyInspectionEngine::x86AssemblyInspectionEngine(const ArchSpec &arch)
23     : m_cur_insn(nullptr), m_machine_ip_regnum(LLDB_INVALID_REGNUM),
24       m_machine_sp_regnum(LLDB_INVALID_REGNUM),
25       m_machine_fp_regnum(LLDB_INVALID_REGNUM),
26       m_lldb_ip_regnum(LLDB_INVALID_REGNUM),
27       m_lldb_sp_regnum(LLDB_INVALID_REGNUM),
28       m_lldb_fp_regnum(LLDB_INVALID_REGNUM),
29 
30       m_reg_map(), m_arch(arch), m_cpu(k_cpu_unspecified), m_wordsize(-1),
31       m_register_map_initialized(false), m_disasm_context() {
32   m_disasm_context =
33       ::LLVMCreateDisasm(arch.GetTriple().getTriple().c_str(), nullptr,
34                          /*TagType=*/1, nullptr, nullptr);
35 }
36 
37 x86AssemblyInspectionEngine::~x86AssemblyInspectionEngine() {
38   ::LLVMDisasmDispose(m_disasm_context);
39 }
40 
41 void x86AssemblyInspectionEngine::Initialize(RegisterContextSP &reg_ctx) {
42   m_cpu = k_cpu_unspecified;
43   m_wordsize = -1;
44   m_register_map_initialized = false;
45 
46   const llvm::Triple::ArchType cpu = m_arch.GetMachine();
47   if (cpu == llvm::Triple::x86)
48     m_cpu = k_i386;
49   else if (cpu == llvm::Triple::x86_64)
50     m_cpu = k_x86_64;
51 
52   if (m_cpu == k_cpu_unspecified)
53     return;
54 
55   if (reg_ctx.get() == nullptr)
56     return;
57 
58   if (m_cpu == k_i386) {
59     m_machine_ip_regnum = k_machine_eip;
60     m_machine_sp_regnum = k_machine_esp;
61     m_machine_fp_regnum = k_machine_ebp;
62     m_wordsize = 4;
63 
64     struct lldb_reg_info reginfo;
65     reginfo.name = "eax";
66     m_reg_map[k_machine_eax] = reginfo;
67     reginfo.name = "edx";
68     m_reg_map[k_machine_edx] = reginfo;
69     reginfo.name = "esp";
70     m_reg_map[k_machine_esp] = reginfo;
71     reginfo.name = "esi";
72     m_reg_map[k_machine_esi] = reginfo;
73     reginfo.name = "eip";
74     m_reg_map[k_machine_eip] = reginfo;
75     reginfo.name = "ecx";
76     m_reg_map[k_machine_ecx] = reginfo;
77     reginfo.name = "ebx";
78     m_reg_map[k_machine_ebx] = reginfo;
79     reginfo.name = "ebp";
80     m_reg_map[k_machine_ebp] = reginfo;
81     reginfo.name = "edi";
82     m_reg_map[k_machine_edi] = reginfo;
83   } else {
84     m_machine_ip_regnum = k_machine_rip;
85     m_machine_sp_regnum = k_machine_rsp;
86     m_machine_fp_regnum = k_machine_rbp;
87     m_wordsize = 8;
88 
89     struct lldb_reg_info reginfo;
90     reginfo.name = "rax";
91     m_reg_map[k_machine_rax] = reginfo;
92     reginfo.name = "rdx";
93     m_reg_map[k_machine_rdx] = reginfo;
94     reginfo.name = "rsp";
95     m_reg_map[k_machine_rsp] = reginfo;
96     reginfo.name = "rsi";
97     m_reg_map[k_machine_rsi] = reginfo;
98     reginfo.name = "r8";
99     m_reg_map[k_machine_r8] = reginfo;
100     reginfo.name = "r10";
101     m_reg_map[k_machine_r10] = reginfo;
102     reginfo.name = "r12";
103     m_reg_map[k_machine_r12] = reginfo;
104     reginfo.name = "r14";
105     m_reg_map[k_machine_r14] = reginfo;
106     reginfo.name = "rip";
107     m_reg_map[k_machine_rip] = reginfo;
108     reginfo.name = "rcx";
109     m_reg_map[k_machine_rcx] = reginfo;
110     reginfo.name = "rbx";
111     m_reg_map[k_machine_rbx] = reginfo;
112     reginfo.name = "rbp";
113     m_reg_map[k_machine_rbp] = reginfo;
114     reginfo.name = "rdi";
115     m_reg_map[k_machine_rdi] = reginfo;
116     reginfo.name = "r9";
117     m_reg_map[k_machine_r9] = reginfo;
118     reginfo.name = "r11";
119     m_reg_map[k_machine_r11] = reginfo;
120     reginfo.name = "r13";
121     m_reg_map[k_machine_r13] = reginfo;
122     reginfo.name = "r15";
123     m_reg_map[k_machine_r15] = reginfo;
124   }
125 
126   for (MachineRegnumToNameAndLLDBRegnum::iterator it = m_reg_map.begin();
127        it != m_reg_map.end(); ++it) {
128     const RegisterInfo *ri = reg_ctx->GetRegisterInfoByName(it->second.name);
129     if (ri)
130       it->second.lldb_regnum = ri->kinds[eRegisterKindLLDB];
131   }
132 
133   uint32_t lldb_regno;
134   if (machine_regno_to_lldb_regno(m_machine_sp_regnum, lldb_regno))
135     m_lldb_sp_regnum = lldb_regno;
136   if (machine_regno_to_lldb_regno(m_machine_fp_regnum, lldb_regno))
137     m_lldb_fp_regnum = lldb_regno;
138   if (machine_regno_to_lldb_regno(m_machine_ip_regnum, lldb_regno))
139     m_lldb_ip_regnum = lldb_regno;
140 
141   m_register_map_initialized = true;
142 }
143 
144 void x86AssemblyInspectionEngine::Initialize(
145     std::vector<lldb_reg_info> &reg_info) {
146   m_cpu = k_cpu_unspecified;
147   m_wordsize = -1;
148   m_register_map_initialized = false;
149 
150   const llvm::Triple::ArchType cpu = m_arch.GetMachine();
151   if (cpu == llvm::Triple::x86)
152     m_cpu = k_i386;
153   else if (cpu == llvm::Triple::x86_64)
154     m_cpu = k_x86_64;
155 
156   if (m_cpu == k_cpu_unspecified)
157     return;
158 
159   if (m_cpu == k_i386) {
160     m_machine_ip_regnum = k_machine_eip;
161     m_machine_sp_regnum = k_machine_esp;
162     m_machine_fp_regnum = k_machine_ebp;
163     m_wordsize = 4;
164 
165     struct lldb_reg_info reginfo;
166     reginfo.name = "eax";
167     m_reg_map[k_machine_eax] = reginfo;
168     reginfo.name = "edx";
169     m_reg_map[k_machine_edx] = reginfo;
170     reginfo.name = "esp";
171     m_reg_map[k_machine_esp] = reginfo;
172     reginfo.name = "esi";
173     m_reg_map[k_machine_esi] = reginfo;
174     reginfo.name = "eip";
175     m_reg_map[k_machine_eip] = reginfo;
176     reginfo.name = "ecx";
177     m_reg_map[k_machine_ecx] = reginfo;
178     reginfo.name = "ebx";
179     m_reg_map[k_machine_ebx] = reginfo;
180     reginfo.name = "ebp";
181     m_reg_map[k_machine_ebp] = reginfo;
182     reginfo.name = "edi";
183     m_reg_map[k_machine_edi] = reginfo;
184   } else {
185     m_machine_ip_regnum = k_machine_rip;
186     m_machine_sp_regnum = k_machine_rsp;
187     m_machine_fp_regnum = k_machine_rbp;
188     m_wordsize = 8;
189 
190     struct lldb_reg_info reginfo;
191     reginfo.name = "rax";
192     m_reg_map[k_machine_rax] = reginfo;
193     reginfo.name = "rdx";
194     m_reg_map[k_machine_rdx] = reginfo;
195     reginfo.name = "rsp";
196     m_reg_map[k_machine_rsp] = reginfo;
197     reginfo.name = "rsi";
198     m_reg_map[k_machine_rsi] = reginfo;
199     reginfo.name = "r8";
200     m_reg_map[k_machine_r8] = reginfo;
201     reginfo.name = "r10";
202     m_reg_map[k_machine_r10] = reginfo;
203     reginfo.name = "r12";
204     m_reg_map[k_machine_r12] = reginfo;
205     reginfo.name = "r14";
206     m_reg_map[k_machine_r14] = reginfo;
207     reginfo.name = "rip";
208     m_reg_map[k_machine_rip] = reginfo;
209     reginfo.name = "rcx";
210     m_reg_map[k_machine_rcx] = reginfo;
211     reginfo.name = "rbx";
212     m_reg_map[k_machine_rbx] = reginfo;
213     reginfo.name = "rbp";
214     m_reg_map[k_machine_rbp] = reginfo;
215     reginfo.name = "rdi";
216     m_reg_map[k_machine_rdi] = reginfo;
217     reginfo.name = "r9";
218     m_reg_map[k_machine_r9] = reginfo;
219     reginfo.name = "r11";
220     m_reg_map[k_machine_r11] = reginfo;
221     reginfo.name = "r13";
222     m_reg_map[k_machine_r13] = reginfo;
223     reginfo.name = "r15";
224     m_reg_map[k_machine_r15] = reginfo;
225   }
226 
227   for (MachineRegnumToNameAndLLDBRegnum::iterator it = m_reg_map.begin();
228        it != m_reg_map.end(); ++it) {
229     for (size_t i = 0; i < reg_info.size(); ++i) {
230       if (::strcmp(reg_info[i].name, it->second.name) == 0) {
231         it->second.lldb_regnum = reg_info[i].lldb_regnum;
232         break;
233       }
234     }
235   }
236 
237   uint32_t lldb_regno;
238   if (machine_regno_to_lldb_regno(m_machine_sp_regnum, lldb_regno))
239     m_lldb_sp_regnum = lldb_regno;
240   if (machine_regno_to_lldb_regno(m_machine_fp_regnum, lldb_regno))
241     m_lldb_fp_regnum = lldb_regno;
242   if (machine_regno_to_lldb_regno(m_machine_ip_regnum, lldb_regno))
243     m_lldb_ip_regnum = lldb_regno;
244 
245   m_register_map_initialized = true;
246 }
247 
248 // This function expects an x86 native register number (i.e. the bits stripped
249 // out of the
250 // actual instruction), not an lldb register number.
251 //
252 // FIXME: This is ABI dependent, it shouldn't be hardcoded here.
253 
254 bool x86AssemblyInspectionEngine::nonvolatile_reg_p(int machine_regno) {
255   if (m_cpu == k_i386) {
256     switch (machine_regno) {
257     case k_machine_ebx:
258     case k_machine_ebp: // not actually a nonvolatile but often treated as such
259                         // by convention
260     case k_machine_esi:
261     case k_machine_edi:
262     case k_machine_esp:
263       return true;
264     default:
265       return false;
266     }
267   }
268   if (m_cpu == k_x86_64) {
269     switch (machine_regno) {
270     case k_machine_rbx:
271     case k_machine_rsp:
272     case k_machine_rbp: // not actually a nonvolatile but often treated as such
273                         // by convention
274     case k_machine_r12:
275     case k_machine_r13:
276     case k_machine_r14:
277     case k_machine_r15:
278       return true;
279     default:
280       return false;
281     }
282   }
283   return false;
284 }
285 
286 // Macro to detect if this is a REX mode prefix byte.
287 #define REX_W_PREFIX_P(opcode) (((opcode) & (~0x5)) == 0x48)
288 
289 // The high bit which should be added to the source register number (the "R"
290 // bit)
291 #define REX_W_SRCREG(opcode) (((opcode)&0x4) >> 2)
292 
293 // The high bit which should be added to the destination register number (the
294 // "B" bit)
295 #define REX_W_DSTREG(opcode) ((opcode)&0x1)
296 
297 // pushq %rbp [0x55]
298 bool x86AssemblyInspectionEngine::push_rbp_pattern_p() {
299   uint8_t *p = m_cur_insn;
300   if (*p == 0x55)
301     return true;
302   return false;
303 }
304 
305 // pushq $0 ; the first instruction in start() [0x6a 0x00]
306 bool x86AssemblyInspectionEngine::push_0_pattern_p() {
307   uint8_t *p = m_cur_insn;
308   if (*p == 0x6a && *(p + 1) == 0x0)
309     return true;
310   return false;
311 }
312 
313 // pushq $0
314 // pushl $0
315 bool x86AssemblyInspectionEngine::push_imm_pattern_p() {
316   uint8_t *p = m_cur_insn;
317   if (*p == 0x68 || *p == 0x6a)
318     return true;
319   return false;
320 }
321 
322 // pushl imm8(%esp)
323 //
324 // e.g. 0xff 0x74 0x24 0x20 - 'pushl 0x20(%esp)'
325 // (same byte pattern for 'pushq 0x20(%rsp)' in an x86_64 program)
326 //
327 // 0xff (with opcode bits '6' in next byte, PUSH r/m32)
328 // 0x74 (ModR/M byte with three bits used to specify the opcode)
329 //      mod == b01, opcode == b110, R/M == b100
330 //      "+disp8"
331 // 0x24 (SIB byte - scaled index = 0, r32 == esp)
332 // 0x20 imm8 value
333 
334 bool x86AssemblyInspectionEngine::push_extended_pattern_p() {
335   if (*m_cur_insn == 0xff) {
336     // Get the 3 opcode bits from the ModR/M byte
337     uint8_t opcode = (*(m_cur_insn + 1) >> 3) & 7;
338     if (opcode == 6) {
339       // I'm only looking for 0xff /6 here - I
340       // don't really care what value is being pushed,
341       // just that we're pushing a 32/64 bit value on
342       // to the stack is enough.
343       return true;
344     }
345   }
346   return false;
347 }
348 
349 // pushq %rbx
350 // pushl %ebx
351 bool x86AssemblyInspectionEngine::push_reg_p(int &regno) {
352   uint8_t *p = m_cur_insn;
353   int regno_prefix_bit = 0;
354   // If we have a rex prefix byte, check to see if a B bit is set
355   if (m_wordsize == 8 && *p == 0x41) {
356     regno_prefix_bit = 1 << 3;
357     p++;
358   }
359   if (*p >= 0x50 && *p <= 0x57) {
360     regno = (*p - 0x50) | regno_prefix_bit;
361     return true;
362   }
363   return false;
364 }
365 
366 // movq %rsp, %rbp [0x48 0x8b 0xec] or [0x48 0x89 0xe5]
367 // movl %esp, %ebp [0x8b 0xec] or [0x89 0xe5]
368 bool x86AssemblyInspectionEngine::mov_rsp_rbp_pattern_p() {
369   uint8_t *p = m_cur_insn;
370   if (m_wordsize == 8 && *p == 0x48)
371     p++;
372   if (*(p) == 0x8b && *(p + 1) == 0xec)
373     return true;
374   if (*(p) == 0x89 && *(p + 1) == 0xe5)
375     return true;
376   return false;
377 }
378 
379 // subq $0x20, %rsp
380 bool x86AssemblyInspectionEngine::sub_rsp_pattern_p(int &amount) {
381   uint8_t *p = m_cur_insn;
382   if (m_wordsize == 8 && *p == 0x48)
383     p++;
384   // 8-bit immediate operand
385   if (*p == 0x83 && *(p + 1) == 0xec) {
386     amount = (int8_t) * (p + 2);
387     return true;
388   }
389   // 32-bit immediate operand
390   if (*p == 0x81 && *(p + 1) == 0xec) {
391     amount = (int32_t)extract_4(p + 2);
392     return true;
393   }
394   return false;
395 }
396 
397 // addq $0x20, %rsp
398 bool x86AssemblyInspectionEngine::add_rsp_pattern_p(int &amount) {
399   uint8_t *p = m_cur_insn;
400   if (m_wordsize == 8 && *p == 0x48)
401     p++;
402   // 8-bit immediate operand
403   if (*p == 0x83 && *(p + 1) == 0xc4) {
404     amount = (int8_t) * (p + 2);
405     return true;
406   }
407   // 32-bit immediate operand
408   if (*p == 0x81 && *(p + 1) == 0xc4) {
409     amount = (int32_t)extract_4(p + 2);
410     return true;
411   }
412   return false;
413 }
414 
415 // lea esp, [esp - 0x28]
416 // lea esp, [esp + 0x28]
417 bool x86AssemblyInspectionEngine::lea_rsp_pattern_p(int &amount) {
418   uint8_t *p = m_cur_insn;
419   if (m_wordsize == 8 && *p == 0x48)
420     p++;
421 
422   // Check opcode
423   if (*p != 0x8d)
424     return false;
425 
426   // 8 bit displacement
427   if (*(p + 1) == 0x64 && (*(p + 2) & 0x3f) == 0x24) {
428     amount = (int8_t) * (p + 3);
429     return true;
430   }
431 
432   // 32 bit displacement
433   if (*(p + 1) == 0xa4 && (*(p + 2) & 0x3f) == 0x24) {
434     amount = (int32_t)extract_4(p + 3);
435     return true;
436   }
437 
438   return false;
439 }
440 
441 // popq %rbx
442 // popl %ebx
443 bool x86AssemblyInspectionEngine::pop_reg_p(int &regno) {
444   uint8_t *p = m_cur_insn;
445   int regno_prefix_bit = 0;
446   // If we have a rex prefix byte, check to see if a B bit is set
447   if (m_wordsize == 8 && *p == 0x41) {
448     regno_prefix_bit = 1 << 3;
449     p++;
450   }
451   if (*p >= 0x58 && *p <= 0x5f) {
452     regno = (*p - 0x58) | regno_prefix_bit;
453     return true;
454   }
455   return false;
456 }
457 
458 // popq %rbp [0x5d]
459 // popl %ebp [0x5d]
460 bool x86AssemblyInspectionEngine::pop_rbp_pattern_p() {
461   uint8_t *p = m_cur_insn;
462   return (*p == 0x5d);
463 }
464 
465 // leave [0xc9]
466 bool x86AssemblyInspectionEngine::leave_pattern_p() {
467   uint8_t *p = m_cur_insn;
468   return (*p == 0xc9);
469 }
470 
471 // call $0 [0xe8 0x0 0x0 0x0 0x0]
472 bool x86AssemblyInspectionEngine::call_next_insn_pattern_p() {
473   uint8_t *p = m_cur_insn;
474   return (*p == 0xe8) && (*(p + 1) == 0x0) && (*(p + 2) == 0x0) &&
475          (*(p + 3) == 0x0) && (*(p + 4) == 0x0);
476 }
477 
478 // Look for an instruction sequence storing a nonvolatile register
479 // on to the stack frame.
480 
481 //  movq %rax, -0x10(%rbp) [0x48 0x89 0x45 0xf0]
482 //  movl %eax, -0xc(%ebp)  [0x89 0x45 0xf4]
483 
484 // The offset value returned in rbp_offset will be positive --
485 // but it must be subtraced from the frame base register to get
486 // the actual location.  The positive value returned for the offset
487 // is a convention used elsewhere for CFA offsets et al.
488 
489 bool x86AssemblyInspectionEngine::mov_reg_to_local_stack_frame_p(
490     int &regno, int &rbp_offset) {
491   uint8_t *p = m_cur_insn;
492   int src_reg_prefix_bit = 0;
493   int target_reg_prefix_bit = 0;
494 
495   if (m_wordsize == 8 && REX_W_PREFIX_P(*p)) {
496     src_reg_prefix_bit = REX_W_SRCREG(*p) << 3;
497     target_reg_prefix_bit = REX_W_DSTREG(*p) << 3;
498     if (target_reg_prefix_bit == 1) {
499       // rbp/ebp don't need a prefix bit - we know this isn't the
500       // reg we care about.
501       return false;
502     }
503     p++;
504   }
505 
506   if (*p == 0x89) {
507     /* Mask off the 3-5 bits which indicate the destination register
508        if this is a ModR/M byte.  */
509     int opcode_destreg_masked_out = *(p + 1) & (~0x38);
510 
511     /* Is this a ModR/M byte with Mod bits 01 and R/M bits 101
512        and three bits between them, e.g. 01nnn101
513        We're looking for a destination of ebp-disp8 or ebp-disp32.   */
514     int immsize;
515     if (opcode_destreg_masked_out == 0x45)
516       immsize = 2;
517     else if (opcode_destreg_masked_out == 0x85)
518       immsize = 4;
519     else
520       return false;
521 
522     int offset = 0;
523     if (immsize == 2)
524       offset = (int8_t) * (p + 2);
525     if (immsize == 4)
526       offset = (uint32_t)extract_4(p + 2);
527     if (offset > 0)
528       return false;
529 
530     regno = ((*(p + 1) >> 3) & 0x7) | src_reg_prefix_bit;
531     rbp_offset = offset > 0 ? offset : -offset;
532     return true;
533   }
534   return false;
535 }
536 
537 // ret [0xc9] or [0xc2 imm8] or [0xca imm8]
538 bool x86AssemblyInspectionEngine::ret_pattern_p() {
539   uint8_t *p = m_cur_insn;
540   if (*p == 0xc9 || *p == 0xc2 || *p == 0xca || *p == 0xc3)
541     return true;
542   return false;
543 }
544 
545 uint32_t x86AssemblyInspectionEngine::extract_4(uint8_t *b) {
546   uint32_t v = 0;
547   for (int i = 3; i >= 0; i--)
548     v = (v << 8) | b[i];
549   return v;
550 }
551 
552 bool x86AssemblyInspectionEngine::instruction_length(uint8_t *insn_p,
553                                                      int &length) {
554 
555   const uint32_t max_op_byte_size = m_arch.GetMaximumOpcodeByteSize();
556   llvm::SmallVector<uint8_t, 32> opcode_data;
557   opcode_data.resize(max_op_byte_size);
558 
559   char out_string[512];
560   const size_t inst_size =
561       ::LLVMDisasmInstruction(m_disasm_context, insn_p, max_op_byte_size, 0,
562                               out_string, sizeof(out_string));
563 
564   length = inst_size;
565   return true;
566 }
567 
568 bool x86AssemblyInspectionEngine::machine_regno_to_lldb_regno(
569     int machine_regno, uint32_t &lldb_regno) {
570   MachineRegnumToNameAndLLDBRegnum::iterator it = m_reg_map.find(machine_regno);
571   if (it != m_reg_map.end()) {
572     lldb_regno = it->second.lldb_regnum;
573     return true;
574   }
575   return false;
576   return false;
577 }
578 
579 bool x86AssemblyInspectionEngine::GetNonCallSiteUnwindPlanFromAssembly(
580     uint8_t *data, size_t size, AddressRange &func_range,
581     UnwindPlan &unwind_plan) {
582   unwind_plan.Clear();
583 
584   if (data == nullptr || size == 0)
585     return false;
586 
587   if (m_register_map_initialized == false)
588     return false;
589 
590   addr_t current_func_text_offset = 0;
591   int current_sp_bytes_offset_from_cfa = 0;
592   UnwindPlan::Row::RegisterLocation initial_regloc;
593   UnwindPlan::RowSP row(new UnwindPlan::Row);
594 
595   unwind_plan.SetPlanValidAddressRange(func_range);
596   unwind_plan.SetRegisterKind(eRegisterKindLLDB);
597 
598   // At the start of the function, find the CFA by adding wordsize to the SP
599   // register
600   row->SetOffset(current_func_text_offset);
601   row->GetCFAValue().SetIsRegisterPlusOffset(m_lldb_sp_regnum, m_wordsize);
602 
603   // caller's stack pointer value before the call insn is the CFA address
604   initial_regloc.SetIsCFAPlusOffset(0);
605   row->SetRegisterInfo(m_lldb_sp_regnum, initial_regloc);
606 
607   // saved instruction pointer can be found at CFA - wordsize.
608   current_sp_bytes_offset_from_cfa = m_wordsize;
609   initial_regloc.SetAtCFAPlusOffset(-current_sp_bytes_offset_from_cfa);
610   row->SetRegisterInfo(m_lldb_ip_regnum, initial_regloc);
611 
612   unwind_plan.AppendRow(row);
613 
614   // Allocate a new Row, populate it with the existing Row contents.
615   UnwindPlan::Row *newrow = new UnwindPlan::Row;
616   *newrow = *row.get();
617   row.reset(newrow);
618 
619   // Track which registers have been saved so far in the prologue.
620   // If we see another push of that register, it's not part of the prologue.
621   // The register numbers used here are the machine register #'s
622   // (i386_register_numbers, x86_64_register_numbers).
623   std::vector<bool> saved_registers(32, false);
624 
625   // Once the prologue has completed we'll save a copy of the unwind
626   // instructions
627   // If there is an epilogue in the middle of the function, after that epilogue
628   // we'll reinstate
629   // the unwind setup -- we assume that some code path jumps over the
630   // mid-function epilogue
631 
632   UnwindPlan::RowSP prologue_completed_row; // copy of prologue row of CFI
633   int prologue_completed_sp_bytes_offset_from_cfa; // The sp value before the
634                                                    // epilogue started executed
635   std::vector<bool> prologue_completed_saved_registers;
636 
637   while (current_func_text_offset < size) {
638     int stack_offset, insn_len;
639     int machine_regno;   // register numbers masked directly out of instructions
640     uint32_t lldb_regno; // register numbers in lldb's eRegisterKindLLDB
641                          // numbering scheme
642 
643     bool in_epilogue = false; // we're in the middle of an epilogue sequence
644     bool row_updated = false; // The UnwindPlan::Row 'row' has been updated
645 
646     m_cur_insn = data + current_func_text_offset;
647     if (!instruction_length(m_cur_insn, insn_len) || insn_len == 0 ||
648         insn_len > kMaxInstructionByteSize) {
649       // An unrecognized/junk instruction
650       break;
651     }
652 
653     if (push_rbp_pattern_p()) {
654       current_sp_bytes_offset_from_cfa += m_wordsize;
655       row->GetCFAValue().SetOffset(current_sp_bytes_offset_from_cfa);
656       UnwindPlan::Row::RegisterLocation regloc;
657       regloc.SetAtCFAPlusOffset(-row->GetCFAValue().GetOffset());
658       row->SetRegisterInfo(m_lldb_fp_regnum, regloc);
659       saved_registers[m_machine_fp_regnum] = true;
660       row_updated = true;
661     }
662 
663     else if (mov_rsp_rbp_pattern_p()) {
664       row->GetCFAValue().SetIsRegisterPlusOffset(
665           m_lldb_fp_regnum, row->GetCFAValue().GetOffset());
666       row_updated = true;
667     }
668 
669     // This is the start() function (or a pthread equivalent), it starts with a
670     // pushl $0x0 which puts the
671     // saved pc value of 0 on the stack.  In this case we want to pretend we
672     // didn't see a stack movement at all --
673     // normally the saved pc value is already on the stack by the time the
674     // function starts executing.
675     else if (push_0_pattern_p()) {
676     }
677 
678     else if (push_reg_p(machine_regno)) {
679       current_sp_bytes_offset_from_cfa += m_wordsize;
680       // the PUSH instruction has moved the stack pointer - if the CFA is set in
681       // terms of the stack pointer,
682       // we need to add a new row of instructions.
683       if (row->GetCFAValue().GetRegisterNumber() == m_lldb_sp_regnum) {
684         row->GetCFAValue().SetOffset(current_sp_bytes_offset_from_cfa);
685         row_updated = true;
686       }
687       // record where non-volatile (callee-saved, spilled) registers are saved
688       // on the stack
689       if (nonvolatile_reg_p(machine_regno) &&
690           machine_regno_to_lldb_regno(machine_regno, lldb_regno) &&
691           saved_registers[machine_regno] == false) {
692         UnwindPlan::Row::RegisterLocation regloc;
693         regloc.SetAtCFAPlusOffset(-current_sp_bytes_offset_from_cfa);
694         row->SetRegisterInfo(lldb_regno, regloc);
695         saved_registers[machine_regno] = true;
696         row_updated = true;
697       }
698     }
699 
700     else if (pop_reg_p(machine_regno)) {
701       current_sp_bytes_offset_from_cfa -= m_wordsize;
702 
703       if (nonvolatile_reg_p(machine_regno) &&
704           machine_regno_to_lldb_regno(machine_regno, lldb_regno) &&
705           saved_registers[machine_regno] == true) {
706         saved_registers[machine_regno] = false;
707         row->RemoveRegisterInfo(lldb_regno);
708 
709         if (machine_regno == (int)m_machine_fp_regnum) {
710           row->GetCFAValue().SetIsRegisterPlusOffset(
711               m_lldb_sp_regnum, row->GetCFAValue().GetOffset());
712         }
713 
714         in_epilogue = true;
715         row_updated = true;
716       }
717 
718       // the POP instruction has moved the stack pointer - if the CFA is set in
719       // terms of the stack pointer,
720       // we need to add a new row of instructions.
721       if (row->GetCFAValue().GetRegisterNumber() == m_lldb_sp_regnum) {
722         row->GetCFAValue().SetIsRegisterPlusOffset(
723             m_lldb_sp_regnum, current_sp_bytes_offset_from_cfa);
724         row_updated = true;
725       }
726     }
727 
728     // The LEAVE instruction moves the value from rbp into rsp and pops
729     // a value off the stack into rbp (restoring the caller's rbp value).
730     // It is the opposite of ENTER, or 'push rbp, mov rsp rbp'.
731     else if (leave_pattern_p()) {
732       // We're going to copy the value in rbp into rsp, so re-set the sp offset
733       // based on the CFAValue.  Also, adjust it to recognize that we're popping
734       // the saved rbp value off the stack.
735       current_sp_bytes_offset_from_cfa = row->GetCFAValue().GetOffset();
736       current_sp_bytes_offset_from_cfa -= m_wordsize;
737       row->GetCFAValue().SetOffset(current_sp_bytes_offset_from_cfa);
738 
739       // rbp is restored to the caller's value
740       saved_registers[m_machine_fp_regnum] = false;
741       row->RemoveRegisterInfo(m_lldb_fp_regnum);
742 
743       // cfa is now in terms of rsp again.
744       row->GetCFAValue().SetIsRegisterPlusOffset(
745           m_lldb_sp_regnum, row->GetCFAValue().GetOffset());
746       row->GetCFAValue().SetOffset(current_sp_bytes_offset_from_cfa);
747 
748       in_epilogue = true;
749       row_updated = true;
750     }
751 
752     else if (mov_reg_to_local_stack_frame_p(machine_regno, stack_offset) &&
753              nonvolatile_reg_p(machine_regno) &&
754              machine_regno_to_lldb_regno(machine_regno, lldb_regno) &&
755              saved_registers[machine_regno] == false) {
756       saved_registers[machine_regno] = true;
757 
758       UnwindPlan::Row::RegisterLocation regloc;
759 
760       // stack_offset for 'movq %r15, -80(%rbp)' will be 80.
761       // In the Row, we want to express this as the offset from the CFA.  If the
762       // frame base
763       // is rbp (like the above instruction), the CFA offset for rbp is probably
764       // 16.  So we
765       // want to say that the value is stored at the CFA address - 96.
766       regloc.SetAtCFAPlusOffset(
767           -(stack_offset + row->GetCFAValue().GetOffset()));
768 
769       row->SetRegisterInfo(lldb_regno, regloc);
770 
771       row_updated = true;
772     }
773 
774     else if (sub_rsp_pattern_p(stack_offset)) {
775       current_sp_bytes_offset_from_cfa += stack_offset;
776       if (row->GetCFAValue().GetRegisterNumber() == m_lldb_sp_regnum) {
777         row->GetCFAValue().SetOffset(current_sp_bytes_offset_from_cfa);
778         row_updated = true;
779       }
780     }
781 
782     else if (add_rsp_pattern_p(stack_offset)) {
783       current_sp_bytes_offset_from_cfa -= stack_offset;
784       if (row->GetCFAValue().GetRegisterNumber() == m_lldb_sp_regnum) {
785         row->GetCFAValue().SetOffset(current_sp_bytes_offset_from_cfa);
786         row_updated = true;
787       }
788       in_epilogue = true;
789     }
790 
791     else if (push_extended_pattern_p() || push_imm_pattern_p()) {
792       current_sp_bytes_offset_from_cfa += m_wordsize;
793       if (row->GetCFAValue().GetRegisterNumber() == m_lldb_sp_regnum) {
794         row->GetCFAValue().SetOffset(current_sp_bytes_offset_from_cfa);
795         row_updated = true;
796       }
797     }
798 
799     else if (lea_rsp_pattern_p(stack_offset)) {
800       current_sp_bytes_offset_from_cfa -= stack_offset;
801       if (row->GetCFAValue().GetRegisterNumber() == m_lldb_sp_regnum) {
802         row->GetCFAValue().SetOffset(current_sp_bytes_offset_from_cfa);
803         row_updated = true;
804       }
805       if (stack_offset > 0)
806         in_epilogue = true;
807     }
808 
809     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
812 
813       UnwindPlan::Row *newrow = new UnwindPlan::Row;
814       *newrow = *prologue_completed_row.get();
815       row.reset(newrow);
816       current_sp_bytes_offset_from_cfa =
817           prologue_completed_sp_bytes_offset_from_cfa;
818 
819       saved_registers.clear();
820       saved_registers.resize(prologue_completed_saved_registers.size(), false);
821       for (size_t i = 0; i < prologue_completed_saved_registers.size(); ++i) {
822         saved_registers[i] = prologue_completed_saved_registers[i];
823       }
824 
825       in_epilogue = true;
826       row_updated = true;
827     }
828 
829     // call next instruction
830     //     call 0
831     //  => pop  %ebx
832     // This is used in i386 programs to get the PIC base address for finding
833     // global data
834     else if (call_next_insn_pattern_p()) {
835       current_sp_bytes_offset_from_cfa += m_wordsize;
836       if (row->GetCFAValue().GetRegisterNumber() == m_lldb_sp_regnum) {
837         row->GetCFAValue().SetOffset(current_sp_bytes_offset_from_cfa);
838         row_updated = true;
839       }
840     }
841 
842     if (row_updated) {
843       if (current_func_text_offset + insn_len < size) {
844         row->SetOffset(current_func_text_offset + insn_len);
845         unwind_plan.AppendRow(row);
846         // Allocate a new Row, populate it with the existing Row contents.
847         newrow = new UnwindPlan::Row;
848         *newrow = *row.get();
849         row.reset(newrow);
850       }
851     }
852 
853     if (in_epilogue == false && row_updated) {
854       // If we're not in an epilogue sequence, save the updated Row
855       UnwindPlan::Row *newrow = new UnwindPlan::Row;
856       *newrow = *row.get();
857       prologue_completed_row.reset(newrow);
858 
859       prologue_completed_saved_registers.clear();
860       prologue_completed_saved_registers.resize(saved_registers.size(), false);
861       for (size_t i = 0; i < saved_registers.size(); ++i) {
862         prologue_completed_saved_registers[i] = saved_registers[i];
863       }
864     }
865 
866     // We may change the sp value without adding a new Row necessarily -- keep
867     // track of it either way.
868     if (in_epilogue == false) {
869       prologue_completed_sp_bytes_offset_from_cfa =
870           current_sp_bytes_offset_from_cfa;
871     }
872 
873     m_cur_insn = m_cur_insn + insn_len;
874     current_func_text_offset += insn_len;
875   }
876 
877   unwind_plan.SetSourceName("assembly insn profiling");
878   unwind_plan.SetSourcedFromCompiler(eLazyBoolNo);
879   unwind_plan.SetUnwindPlanValidAtAllInstructions(eLazyBoolYes);
880 
881   return true;
882 }
883 
884 bool x86AssemblyInspectionEngine::AugmentUnwindPlanFromCallSite(
885     uint8_t *data, size_t size, AddressRange &func_range,
886     UnwindPlan &unwind_plan, RegisterContextSP &reg_ctx) {
887   Address addr_start = func_range.GetBaseAddress();
888   if (!addr_start.IsValid())
889     return false;
890 
891   // We either need a live RegisterContext, or we need the UnwindPlan to already
892   // be in the lldb register numbering scheme.
893   if (reg_ctx.get() == nullptr &&
894       unwind_plan.GetRegisterKind() != eRegisterKindLLDB)
895     return false;
896 
897   // Is original unwind_plan valid?
898   // unwind_plan should have at least one row which is ABI-default (CFA register
899   // is sp),
900   // and another row in mid-function.
901   if (unwind_plan.GetRowCount() < 2)
902     return false;
903 
904   UnwindPlan::RowSP first_row = unwind_plan.GetRowAtIndex(0);
905   if (first_row->GetOffset() != 0)
906     return false;
907   uint32_t cfa_reg = first_row->GetCFAValue().GetRegisterNumber();
908   if (unwind_plan.GetRegisterKind() != eRegisterKindLLDB) {
909     cfa_reg = reg_ctx->ConvertRegisterKindToRegisterNumber(
910         unwind_plan.GetRegisterKind(),
911         first_row->GetCFAValue().GetRegisterNumber());
912   }
913   if (cfa_reg != m_lldb_sp_regnum ||
914       first_row->GetCFAValue().GetOffset() != m_wordsize)
915     return false;
916 
917   UnwindPlan::RowSP original_last_row = unwind_plan.GetRowForFunctionOffset(-1);
918 
919   size_t offset = 0;
920   int row_id = 1;
921   bool unwind_plan_updated = false;
922   UnwindPlan::RowSP row(new UnwindPlan::Row(*first_row));
923   m_cur_insn = data + offset;
924 
925   // After a mid-function epilogue we will need to re-insert the original unwind
926   // rules
927   // so unwinds work for the remainder of the function.  These aren't common
928   // with clang/gcc
929   // on x86 but it is possible.
930   bool reinstate_unwind_state = false;
931 
932   while (offset < size) {
933     m_cur_insn = data + offset;
934     int insn_len;
935     if (!instruction_length(m_cur_insn, insn_len) || insn_len == 0 ||
936         insn_len > kMaxInstructionByteSize) {
937       // An unrecognized/junk instruction.
938       break;
939     }
940 
941     // Advance offsets.
942     offset += insn_len;
943     m_cur_insn = data + offset;
944 
945     if (reinstate_unwind_state) {
946       // that was the last instruction of this function
947       if (offset >= size)
948         continue;
949 
950       UnwindPlan::RowSP new_row(new UnwindPlan::Row());
951       *new_row = *original_last_row;
952       new_row->SetOffset(offset);
953       unwind_plan.AppendRow(new_row);
954       row.reset(new UnwindPlan::Row());
955       *row = *new_row;
956       reinstate_unwind_state = false;
957       unwind_plan_updated = true;
958       continue;
959     }
960 
961     // If we already have one row for this instruction, we can continue.
962     while (row_id < unwind_plan.GetRowCount() &&
963            unwind_plan.GetRowAtIndex(row_id)->GetOffset() <= offset) {
964       row_id++;
965     }
966     UnwindPlan::RowSP original_row = unwind_plan.GetRowAtIndex(row_id - 1);
967     if (original_row->GetOffset() == offset) {
968       *row = *original_row;
969       continue;
970     }
971 
972     if (row_id == 0) {
973       // If we are here, compiler didn't generate CFI for prologue.
974       // This won't happen to GCC or clang.
975       // In this case, bail out directly.
976       return false;
977     }
978 
979     // Inspect the instruction to check if we need a new row for it.
980     cfa_reg = row->GetCFAValue().GetRegisterNumber();
981     if (unwind_plan.GetRegisterKind() != eRegisterKindLLDB) {
982       cfa_reg = reg_ctx->ConvertRegisterKindToRegisterNumber(
983           unwind_plan.GetRegisterKind(),
984           row->GetCFAValue().GetRegisterNumber());
985     }
986     if (cfa_reg == m_lldb_sp_regnum) {
987       // CFA register is sp.
988 
989       // call next instruction
990       //     call 0
991       //  => pop  %ebx
992       if (call_next_insn_pattern_p()) {
993         row->SetOffset(offset);
994         row->GetCFAValue().IncOffset(m_wordsize);
995 
996         UnwindPlan::RowSP new_row(new UnwindPlan::Row(*row));
997         unwind_plan.InsertRow(new_row);
998         unwind_plan_updated = true;
999         continue;
1000       }
1001 
1002       // push/pop register
1003       int regno;
1004       if (push_reg_p(regno)) {
1005         row->SetOffset(offset);
1006         row->GetCFAValue().IncOffset(m_wordsize);
1007 
1008         UnwindPlan::RowSP new_row(new UnwindPlan::Row(*row));
1009         unwind_plan.InsertRow(new_row);
1010         unwind_plan_updated = true;
1011         continue;
1012       }
1013       if (pop_reg_p(regno)) {
1014         // Technically, this might be a nonvolatile register recover in
1015         // epilogue.
1016         // We should reset RegisterInfo for the register.
1017         // But in practice, previous rule for the register is still valid...
1018         // So we ignore this case.
1019 
1020         row->SetOffset(offset);
1021         row->GetCFAValue().IncOffset(-m_wordsize);
1022 
1023         UnwindPlan::RowSP new_row(new UnwindPlan::Row(*row));
1024         unwind_plan.InsertRow(new_row);
1025         unwind_plan_updated = true;
1026         continue;
1027       }
1028 
1029       // push imm
1030       if (push_imm_pattern_p()) {
1031         row->SetOffset(offset);
1032         row->GetCFAValue().IncOffset(m_wordsize);
1033         UnwindPlan::RowSP new_row(new UnwindPlan::Row(*row));
1034         unwind_plan.InsertRow(new_row);
1035         unwind_plan_updated = true;
1036         continue;
1037       }
1038 
1039       // push extended
1040       if (push_extended_pattern_p()) {
1041         row->SetOffset(offset);
1042         row->GetCFAValue().IncOffset(m_wordsize);
1043         UnwindPlan::RowSP new_row(new UnwindPlan::Row(*row));
1044         unwind_plan.InsertRow(new_row);
1045         unwind_plan_updated = true;
1046         continue;
1047       }
1048 
1049       // add/sub %rsp/%esp
1050       int amount;
1051       if (add_rsp_pattern_p(amount)) {
1052         row->SetOffset(offset);
1053         row->GetCFAValue().IncOffset(-amount);
1054 
1055         UnwindPlan::RowSP new_row(new UnwindPlan::Row(*row));
1056         unwind_plan.InsertRow(new_row);
1057         unwind_plan_updated = true;
1058         continue;
1059       }
1060       if (sub_rsp_pattern_p(amount)) {
1061         row->SetOffset(offset);
1062         row->GetCFAValue().IncOffset(amount);
1063 
1064         UnwindPlan::RowSP new_row(new UnwindPlan::Row(*row));
1065         unwind_plan.InsertRow(new_row);
1066         unwind_plan_updated = true;
1067         continue;
1068       }
1069 
1070       // lea %rsp, [%rsp + $offset]
1071       if (lea_rsp_pattern_p(amount)) {
1072         row->SetOffset(offset);
1073         row->GetCFAValue().IncOffset(-amount);
1074 
1075         UnwindPlan::RowSP new_row(new UnwindPlan::Row(*row));
1076         unwind_plan.InsertRow(new_row);
1077         unwind_plan_updated = true;
1078         continue;
1079       }
1080 
1081       if (ret_pattern_p()) {
1082         reinstate_unwind_state = true;
1083         continue;
1084       }
1085     } else if (cfa_reg == m_lldb_fp_regnum) {
1086       // CFA register is fp.
1087 
1088       // The only case we care about is epilogue:
1089       //     [0x5d] pop %rbp/%ebp
1090       //  => [0xc3] ret
1091       if (pop_rbp_pattern_p() || leave_pattern_p()) {
1092         offset += 1;
1093         row->SetOffset(offset);
1094         row->GetCFAValue().SetIsRegisterPlusOffset(
1095             first_row->GetCFAValue().GetRegisterNumber(), m_wordsize);
1096 
1097         UnwindPlan::RowSP new_row(new UnwindPlan::Row(*row));
1098         unwind_plan.InsertRow(new_row);
1099         unwind_plan_updated = true;
1100         reinstate_unwind_state = true;
1101         continue;
1102       }
1103     } else {
1104       // CFA register is not sp or fp.
1105 
1106       // This must be hand-written assembly.
1107       // Just trust eh_frame and assume we have finished.
1108       break;
1109     }
1110   }
1111 
1112   unwind_plan.SetPlanValidAddressRange(func_range);
1113   if (unwind_plan_updated) {
1114     std::string unwind_plan_source(unwind_plan.GetSourceName().AsCString());
1115     unwind_plan_source += " plus augmentation from assembly parsing";
1116     unwind_plan.SetSourceName(unwind_plan_source.c_str());
1117     unwind_plan.SetSourcedFromCompiler(eLazyBoolNo);
1118     unwind_plan.SetUnwindPlanValidAtAllInstructions(eLazyBoolYes);
1119   }
1120   return true;
1121 }
1122 
1123 bool x86AssemblyInspectionEngine::FindFirstNonPrologueInstruction(
1124     uint8_t *data, size_t size, size_t &offset) {
1125   offset = 0;
1126 
1127   if (m_register_map_initialized == false)
1128     return false;
1129 
1130   while (offset < size) {
1131     int regno;
1132     int insn_len;
1133     int scratch;
1134 
1135     m_cur_insn = data + offset;
1136     if (!instruction_length(m_cur_insn, insn_len) ||
1137         insn_len > kMaxInstructionByteSize || insn_len == 0) {
1138       // An error parsing the instruction, i.e. probably data/garbage - stop
1139       // scanning
1140       break;
1141     }
1142 
1143     if (push_rbp_pattern_p() || mov_rsp_rbp_pattern_p() ||
1144         sub_rsp_pattern_p(scratch) || push_reg_p(regno) ||
1145         mov_reg_to_local_stack_frame_p(regno, scratch) ||
1146         (lea_rsp_pattern_p(scratch) && offset == 0)) {
1147       offset += insn_len;
1148       continue;
1149     }
1150     //
1151     // Unknown non-prologue instruction - stop scanning
1152     break;
1153   }
1154 
1155   return true;
1156 }
1157