1 //===-- x86AssemblyInspectionEngine.cpp -----------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "x86AssemblyInspectionEngine.h"
10 
11 #include <memory>
12 
13 #include "llvm-c/Disassembler.h"
14 
15 #include "lldb/Core/Address.h"
16 #include "lldb/Symbol/UnwindPlan.h"
17 #include "lldb/Target/RegisterContext.h"
18 #include "lldb/Target/UnwindAssembly.h"
19 
20 using namespace lldb_private;
21 using namespace lldb;
22 
23 x86AssemblyInspectionEngine::x86AssemblyInspectionEngine(const ArchSpec &arch)
24     : m_cur_insn(nullptr), m_machine_ip_regnum(LLDB_INVALID_REGNUM),
25       m_machine_sp_regnum(LLDB_INVALID_REGNUM),
26       m_machine_fp_regnum(LLDB_INVALID_REGNUM),
27       m_machine_alt_fp_regnum(LLDB_INVALID_REGNUM),
28       m_lldb_ip_regnum(LLDB_INVALID_REGNUM),
29       m_lldb_sp_regnum(LLDB_INVALID_REGNUM),
30       m_lldb_fp_regnum(LLDB_INVALID_REGNUM),
31       m_lldb_alt_fp_regnum(LLDB_INVALID_REGNUM), m_reg_map(), m_arch(arch),
32       m_cpu(k_cpu_unspecified), m_wordsize(-1),
33       m_register_map_initialized(false), m_disasm_context() {
34   m_disasm_context =
35       ::LLVMCreateDisasm(arch.GetTriple().getTriple().c_str(), nullptr,
36                          /*TagType=*/1, nullptr, nullptr);
37 }
38 
39 x86AssemblyInspectionEngine::~x86AssemblyInspectionEngine() {
40   ::LLVMDisasmDispose(m_disasm_context);
41 }
42 
43 void x86AssemblyInspectionEngine::Initialize(RegisterContextSP &reg_ctx) {
44   m_cpu = k_cpu_unspecified;
45   m_wordsize = -1;
46   m_register_map_initialized = false;
47 
48   const llvm::Triple::ArchType cpu = m_arch.GetMachine();
49   if (cpu == llvm::Triple::x86)
50     m_cpu = k_i386;
51   else if (cpu == llvm::Triple::x86_64)
52     m_cpu = k_x86_64;
53 
54   if (m_cpu == k_cpu_unspecified)
55     return;
56 
57   if (reg_ctx.get() == nullptr)
58     return;
59 
60   if (m_cpu == k_i386) {
61     m_machine_ip_regnum = k_machine_eip;
62     m_machine_sp_regnum = k_machine_esp;
63     m_machine_fp_regnum = k_machine_ebp;
64     m_machine_alt_fp_regnum = k_machine_ebx;
65     m_wordsize = 4;
66 
67     struct lldb_reg_info reginfo;
68     reginfo.name = "eax";
69     m_reg_map[k_machine_eax] = reginfo;
70     reginfo.name = "edx";
71     m_reg_map[k_machine_edx] = reginfo;
72     reginfo.name = "esp";
73     m_reg_map[k_machine_esp] = reginfo;
74     reginfo.name = "esi";
75     m_reg_map[k_machine_esi] = reginfo;
76     reginfo.name = "eip";
77     m_reg_map[k_machine_eip] = reginfo;
78     reginfo.name = "ecx";
79     m_reg_map[k_machine_ecx] = reginfo;
80     reginfo.name = "ebx";
81     m_reg_map[k_machine_ebx] = reginfo;
82     reginfo.name = "ebp";
83     m_reg_map[k_machine_ebp] = reginfo;
84     reginfo.name = "edi";
85     m_reg_map[k_machine_edi] = reginfo;
86   } else {
87     m_machine_ip_regnum = k_machine_rip;
88     m_machine_sp_regnum = k_machine_rsp;
89     m_machine_fp_regnum = k_machine_rbp;
90     m_machine_alt_fp_regnum = k_machine_rbx;
91     m_wordsize = 8;
92 
93     struct lldb_reg_info reginfo;
94     reginfo.name = "rax";
95     m_reg_map[k_machine_rax] = reginfo;
96     reginfo.name = "rdx";
97     m_reg_map[k_machine_rdx] = reginfo;
98     reginfo.name = "rsp";
99     m_reg_map[k_machine_rsp] = reginfo;
100     reginfo.name = "rsi";
101     m_reg_map[k_machine_rsi] = reginfo;
102     reginfo.name = "r8";
103     m_reg_map[k_machine_r8] = reginfo;
104     reginfo.name = "r10";
105     m_reg_map[k_machine_r10] = reginfo;
106     reginfo.name = "r12";
107     m_reg_map[k_machine_r12] = reginfo;
108     reginfo.name = "r14";
109     m_reg_map[k_machine_r14] = reginfo;
110     reginfo.name = "rip";
111     m_reg_map[k_machine_rip] = reginfo;
112     reginfo.name = "rcx";
113     m_reg_map[k_machine_rcx] = reginfo;
114     reginfo.name = "rbx";
115     m_reg_map[k_machine_rbx] = reginfo;
116     reginfo.name = "rbp";
117     m_reg_map[k_machine_rbp] = reginfo;
118     reginfo.name = "rdi";
119     m_reg_map[k_machine_rdi] = reginfo;
120     reginfo.name = "r9";
121     m_reg_map[k_machine_r9] = reginfo;
122     reginfo.name = "r11";
123     m_reg_map[k_machine_r11] = reginfo;
124     reginfo.name = "r13";
125     m_reg_map[k_machine_r13] = reginfo;
126     reginfo.name = "r15";
127     m_reg_map[k_machine_r15] = reginfo;
128   }
129 
130   for (MachineRegnumToNameAndLLDBRegnum::iterator it = m_reg_map.begin();
131        it != m_reg_map.end(); ++it) {
132     const RegisterInfo *ri = reg_ctx->GetRegisterInfoByName(it->second.name);
133     if (ri)
134       it->second.lldb_regnum = ri->kinds[eRegisterKindLLDB];
135   }
136 
137   uint32_t lldb_regno;
138   if (machine_regno_to_lldb_regno(m_machine_sp_regnum, lldb_regno))
139     m_lldb_sp_regnum = lldb_regno;
140   if (machine_regno_to_lldb_regno(m_machine_fp_regnum, lldb_regno))
141     m_lldb_fp_regnum = lldb_regno;
142   if (machine_regno_to_lldb_regno(m_machine_alt_fp_regnum, lldb_regno))
143     m_lldb_alt_fp_regnum = lldb_regno;
144   if (machine_regno_to_lldb_regno(m_machine_ip_regnum, lldb_regno))
145     m_lldb_ip_regnum = lldb_regno;
146 
147   m_register_map_initialized = true;
148 }
149 
150 void x86AssemblyInspectionEngine::Initialize(
151     std::vector<lldb_reg_info> &reg_info) {
152   m_cpu = k_cpu_unspecified;
153   m_wordsize = -1;
154   m_register_map_initialized = false;
155 
156   const llvm::Triple::ArchType cpu = m_arch.GetMachine();
157   if (cpu == llvm::Triple::x86)
158     m_cpu = k_i386;
159   else if (cpu == llvm::Triple::x86_64)
160     m_cpu = k_x86_64;
161 
162   if (m_cpu == k_cpu_unspecified)
163     return;
164 
165   if (m_cpu == k_i386) {
166     m_machine_ip_regnum = k_machine_eip;
167     m_machine_sp_regnum = k_machine_esp;
168     m_machine_fp_regnum = k_machine_ebp;
169     m_machine_alt_fp_regnum = k_machine_ebx;
170     m_wordsize = 4;
171 
172     struct lldb_reg_info reginfo;
173     reginfo.name = "eax";
174     m_reg_map[k_machine_eax] = reginfo;
175     reginfo.name = "edx";
176     m_reg_map[k_machine_edx] = reginfo;
177     reginfo.name = "esp";
178     m_reg_map[k_machine_esp] = reginfo;
179     reginfo.name = "esi";
180     m_reg_map[k_machine_esi] = reginfo;
181     reginfo.name = "eip";
182     m_reg_map[k_machine_eip] = reginfo;
183     reginfo.name = "ecx";
184     m_reg_map[k_machine_ecx] = reginfo;
185     reginfo.name = "ebx";
186     m_reg_map[k_machine_ebx] = reginfo;
187     reginfo.name = "ebp";
188     m_reg_map[k_machine_ebp] = reginfo;
189     reginfo.name = "edi";
190     m_reg_map[k_machine_edi] = reginfo;
191   } else {
192     m_machine_ip_regnum = k_machine_rip;
193     m_machine_sp_regnum = k_machine_rsp;
194     m_machine_fp_regnum = k_machine_rbp;
195     m_machine_alt_fp_regnum = k_machine_rbx;
196     m_wordsize = 8;
197 
198     struct lldb_reg_info reginfo;
199     reginfo.name = "rax";
200     m_reg_map[k_machine_rax] = reginfo;
201     reginfo.name = "rdx";
202     m_reg_map[k_machine_rdx] = reginfo;
203     reginfo.name = "rsp";
204     m_reg_map[k_machine_rsp] = reginfo;
205     reginfo.name = "rsi";
206     m_reg_map[k_machine_rsi] = reginfo;
207     reginfo.name = "r8";
208     m_reg_map[k_machine_r8] = reginfo;
209     reginfo.name = "r10";
210     m_reg_map[k_machine_r10] = reginfo;
211     reginfo.name = "r12";
212     m_reg_map[k_machine_r12] = reginfo;
213     reginfo.name = "r14";
214     m_reg_map[k_machine_r14] = reginfo;
215     reginfo.name = "rip";
216     m_reg_map[k_machine_rip] = reginfo;
217     reginfo.name = "rcx";
218     m_reg_map[k_machine_rcx] = reginfo;
219     reginfo.name = "rbx";
220     m_reg_map[k_machine_rbx] = reginfo;
221     reginfo.name = "rbp";
222     m_reg_map[k_machine_rbp] = reginfo;
223     reginfo.name = "rdi";
224     m_reg_map[k_machine_rdi] = reginfo;
225     reginfo.name = "r9";
226     m_reg_map[k_machine_r9] = reginfo;
227     reginfo.name = "r11";
228     m_reg_map[k_machine_r11] = reginfo;
229     reginfo.name = "r13";
230     m_reg_map[k_machine_r13] = reginfo;
231     reginfo.name = "r15";
232     m_reg_map[k_machine_r15] = reginfo;
233   }
234 
235   for (MachineRegnumToNameAndLLDBRegnum::iterator it = m_reg_map.begin();
236        it != m_reg_map.end(); ++it) {
237     for (size_t i = 0; i < reg_info.size(); ++i) {
238       if (::strcmp(reg_info[i].name, it->second.name) == 0) {
239         it->second.lldb_regnum = reg_info[i].lldb_regnum;
240         break;
241       }
242     }
243   }
244 
245   uint32_t lldb_regno;
246   if (machine_regno_to_lldb_regno(m_machine_sp_regnum, lldb_regno))
247     m_lldb_sp_regnum = lldb_regno;
248   if (machine_regno_to_lldb_regno(m_machine_fp_regnum, lldb_regno))
249     m_lldb_fp_regnum = lldb_regno;
250   if (machine_regno_to_lldb_regno(m_machine_alt_fp_regnum, lldb_regno))
251     m_lldb_alt_fp_regnum = lldb_regno;
252   if (machine_regno_to_lldb_regno(m_machine_ip_regnum, lldb_regno))
253     m_lldb_ip_regnum = lldb_regno;
254 
255   m_register_map_initialized = true;
256 }
257 
258 // This function expects an x86 native register number (i.e. the bits stripped
259 // out of the actual instruction), not an lldb register number.
260 //
261 // FIXME: This is ABI dependent, it shouldn't be hardcoded here.
262 
263 bool x86AssemblyInspectionEngine::nonvolatile_reg_p(int machine_regno) {
264   if (m_cpu == k_i386) {
265     switch (machine_regno) {
266     case k_machine_ebx:
267     case k_machine_ebp: // not actually a nonvolatile but often treated as such
268                         // by convention
269     case k_machine_esi:
270     case k_machine_edi:
271     case k_machine_esp:
272       return true;
273     default:
274       return false;
275     }
276   }
277   if (m_cpu == k_x86_64) {
278     switch (machine_regno) {
279     case k_machine_rbx:
280     case k_machine_rsp:
281     case k_machine_rbp: // not actually a nonvolatile but often treated as such
282                         // by convention
283     case k_machine_r12:
284     case k_machine_r13:
285     case k_machine_r14:
286     case k_machine_r15:
287       return true;
288     default:
289       return false;
290     }
291   }
292   return false;
293 }
294 
295 // Macro to detect if this is a REX mode prefix byte.
296 #define REX_W_PREFIX_P(opcode) (((opcode) & (~0x5)) == 0x48)
297 
298 // The high bit which should be added to the source register number (the "R"
299 // bit)
300 #define REX_W_SRCREG(opcode) (((opcode)&0x4) >> 2)
301 
302 // The high bit which should be added to the destination register number (the
303 // "B" bit)
304 #define REX_W_DSTREG(opcode) ((opcode)&0x1)
305 
306 // pushq %rbp [0x55]
307 bool x86AssemblyInspectionEngine::push_rbp_pattern_p() {
308   uint8_t *p = m_cur_insn;
309   return *p == 0x55;
310 }
311 
312 // pushq $0 ; the first instruction in start() [0x6a 0x00]
313 bool x86AssemblyInspectionEngine::push_0_pattern_p() {
314   uint8_t *p = m_cur_insn;
315   return *p == 0x6a && *(p + 1) == 0x0;
316 }
317 
318 // pushq $0
319 // pushl $0
320 bool x86AssemblyInspectionEngine::push_imm_pattern_p() {
321   uint8_t *p = m_cur_insn;
322   return *p == 0x68 || *p == 0x6a;
323 }
324 
325 // pushl imm8(%esp)
326 //
327 // e.g. 0xff 0x74 0x24 0x20 - 'pushl 0x20(%esp)' (same byte pattern for 'pushq
328 // 0x20(%rsp)' in an x86_64 program)
329 //
330 // 0xff (with opcode bits '6' in next byte, PUSH r/m32) 0x74 (ModR/M byte with
331 // three bits used to specify the opcode)
332 //      mod == b01, opcode == b110, R/M == b100
333 //      "+disp8"
334 // 0x24 (SIB byte - scaled index = 0, r32 == esp) 0x20 imm8 value
335 
336 bool x86AssemblyInspectionEngine::push_extended_pattern_p() {
337   if (*m_cur_insn == 0xff) {
338     // Get the 3 opcode bits from the ModR/M byte
339     uint8_t opcode = (*(m_cur_insn + 1) >> 3) & 7;
340     if (opcode == 6) {
341       // I'm only looking for 0xff /6 here - I
342       // don't really care what value is being pushed, just that we're pushing
343       // a 32/64 bit value on to the stack is enough.
344       return true;
345     }
346   }
347   return false;
348 }
349 
350 // instructions only valid in 32-bit mode:
351 // 0x0e - push cs
352 // 0x16 - push ss
353 // 0x1e - push ds
354 // 0x06 - push es
355 bool x86AssemblyInspectionEngine::push_misc_reg_p() {
356   uint8_t p = *m_cur_insn;
357   if (m_wordsize == 4) {
358     if (p == 0x0e || p == 0x16 || p == 0x1e || p == 0x06)
359       return true;
360   }
361   return false;
362 }
363 
364 // pushq %rbx
365 // pushl %ebx
366 bool x86AssemblyInspectionEngine::push_reg_p(int &regno) {
367   uint8_t *p = m_cur_insn;
368   int regno_prefix_bit = 0;
369   // If we have a rex prefix byte, check to see if a B bit is set
370   if (m_wordsize == 8 && (*p & 0xfe) == 0x40) {
371     regno_prefix_bit = (*p & 1) << 3;
372     p++;
373   }
374   if (*p >= 0x50 && *p <= 0x57) {
375     regno = (*p - 0x50) | regno_prefix_bit;
376     return true;
377   }
378   return false;
379 }
380 
381 // movq %rsp, %rbp [0x48 0x8b 0xec] or [0x48 0x89 0xe5] movl %esp, %ebp [0x8b
382 // 0xec] or [0x89 0xe5]
383 bool x86AssemblyInspectionEngine::mov_rsp_rbp_pattern_p() {
384   uint8_t *p = m_cur_insn;
385   if (m_wordsize == 8 && *p == 0x48)
386     p++;
387   if (*(p) == 0x8b && *(p + 1) == 0xec)
388     return true;
389   if (*(p) == 0x89 && *(p + 1) == 0xe5)
390     return true;
391   return false;
392 }
393 
394 // movq %rsp, %rbx [0x48 0x8b 0xdc] or [0x48 0x89 0xe3]
395 // movl %esp, %ebx [0x8b 0xdc] or [0x89 0xe3]
396 bool x86AssemblyInspectionEngine::mov_rsp_rbx_pattern_p() {
397   uint8_t *p = m_cur_insn;
398   if (m_wordsize == 8 && *p == 0x48)
399     p++;
400   if (*(p) == 0x8b && *(p + 1) == 0xdc)
401     return true;
402   if (*(p) == 0x89 && *(p + 1) == 0xe3)
403     return true;
404   return false;
405 }
406 
407 // movq %rbp, %rsp [0x48 0x8b 0xe5] or [0x48 0x89 0xec]
408 // movl %ebp, %esp [0x8b 0xe5] or [0x89 0xec]
409 bool x86AssemblyInspectionEngine::mov_rbp_rsp_pattern_p() {
410   uint8_t *p = m_cur_insn;
411   if (m_wordsize == 8 && *p == 0x48)
412     p++;
413   if (*(p) == 0x8b && *(p + 1) == 0xe5)
414     return true;
415   if (*(p) == 0x89 && *(p + 1) == 0xec)
416     return true;
417   return false;
418 }
419 
420 // movq %rbx, %rsp [0x48 0x8b 0xe3] or [0x48 0x89 0xdc]
421 // movl %ebx, %esp [0x8b 0xe3] or [0x89 0xdc]
422 bool x86AssemblyInspectionEngine::mov_rbx_rsp_pattern_p() {
423   uint8_t *p = m_cur_insn;
424   if (m_wordsize == 8 && *p == 0x48)
425     p++;
426   if (*(p) == 0x8b && *(p + 1) == 0xe3)
427     return true;
428   if (*(p) == 0x89 && *(p + 1) == 0xdc)
429     return true;
430   return false;
431 }
432 
433 // subq $0x20, %rsp
434 bool x86AssemblyInspectionEngine::sub_rsp_pattern_p(int &amount) {
435   uint8_t *p = m_cur_insn;
436   if (m_wordsize == 8 && *p == 0x48)
437     p++;
438   // 8-bit immediate operand
439   if (*p == 0x83 && *(p + 1) == 0xec) {
440     amount = (int8_t) * (p + 2);
441     return true;
442   }
443   // 32-bit immediate operand
444   if (*p == 0x81 && *(p + 1) == 0xec) {
445     amount = (int32_t)extract_4(p + 2);
446     return true;
447   }
448   return false;
449 }
450 
451 // addq $0x20, %rsp
452 bool x86AssemblyInspectionEngine::add_rsp_pattern_p(int &amount) {
453   uint8_t *p = m_cur_insn;
454   if (m_wordsize == 8 && *p == 0x48)
455     p++;
456   // 8-bit immediate operand
457   if (*p == 0x83 && *(p + 1) == 0xc4) {
458     amount = (int8_t) * (p + 2);
459     return true;
460   }
461   // 32-bit immediate operand
462   if (*p == 0x81 && *(p + 1) == 0xc4) {
463     amount = (int32_t)extract_4(p + 2);
464     return true;
465   }
466   return false;
467 }
468 
469 // lea esp, [esp - 0x28]
470 // lea esp, [esp + 0x28]
471 bool x86AssemblyInspectionEngine::lea_rsp_pattern_p(int &amount) {
472   uint8_t *p = m_cur_insn;
473   if (m_wordsize == 8 && *p == 0x48)
474     p++;
475 
476   // Check opcode
477   if (*p != 0x8d)
478     return false;
479 
480   // 8 bit displacement
481   if (*(p + 1) == 0x64 && (*(p + 2) & 0x3f) == 0x24) {
482     amount = (int8_t) * (p + 3);
483     return true;
484   }
485 
486   // 32 bit displacement
487   if (*(p + 1) == 0xa4 && (*(p + 2) & 0x3f) == 0x24) {
488     amount = (int32_t)extract_4(p + 3);
489     return true;
490   }
491 
492   return false;
493 }
494 
495 // lea -0x28(%ebp), %esp
496 // (32-bit and 64-bit variants, 8-bit and 32-bit displacement)
497 bool x86AssemblyInspectionEngine::lea_rbp_rsp_pattern_p(int &amount) {
498   uint8_t *p = m_cur_insn;
499   if (m_wordsize == 8 && *p == 0x48)
500     p++;
501 
502   // Check opcode
503   if (*p != 0x8d)
504     return false;
505   ++p;
506 
507   // 8 bit displacement
508   if (*p == 0x65) {
509     amount = (int8_t)p[1];
510     return true;
511   }
512 
513   // 32 bit displacement
514   if (*p == 0xa5) {
515     amount = (int32_t)extract_4(p + 1);
516     return true;
517   }
518 
519   return false;
520 }
521 
522 // lea -0x28(%ebx), %esp
523 // (32-bit and 64-bit variants, 8-bit and 32-bit displacement)
524 bool x86AssemblyInspectionEngine::lea_rbx_rsp_pattern_p(int &amount) {
525   uint8_t *p = m_cur_insn;
526   if (m_wordsize == 8 && *p == 0x48)
527     p++;
528 
529   // Check opcode
530   if (*p != 0x8d)
531     return false;
532   ++p;
533 
534   // 8 bit displacement
535   if (*p == 0x63) {
536     amount = (int8_t)p[1];
537     return true;
538   }
539 
540   // 32 bit displacement
541   if (*p == 0xa3) {
542     amount = (int32_t)extract_4(p + 1);
543     return true;
544   }
545 
546   return false;
547 }
548 
549 // and -0xfffffff0, %esp
550 // (32-bit and 64-bit variants, 8-bit and 32-bit displacement)
551 bool x86AssemblyInspectionEngine::and_rsp_pattern_p() {
552   uint8_t *p = m_cur_insn;
553   if (m_wordsize == 8 && *p == 0x48)
554     p++;
555 
556   if (*p != 0x81 && *p != 0x83)
557     return false;
558 
559   return *++p == 0xe4;
560 }
561 
562 // popq %rbx
563 // popl %ebx
564 bool x86AssemblyInspectionEngine::pop_reg_p(int &regno) {
565   uint8_t *p = m_cur_insn;
566   int regno_prefix_bit = 0;
567   // If we have a rex prefix byte, check to see if a B bit is set
568   if (m_wordsize == 8 && (*p & 0xfe) == 0x40) {
569     regno_prefix_bit = (*p & 1) << 3;
570     p++;
571   }
572   if (*p >= 0x58 && *p <= 0x5f) {
573     regno = (*p - 0x58) | regno_prefix_bit;
574     return true;
575   }
576   return false;
577 }
578 
579 // popq %rbp [0x5d]
580 // popl %ebp [0x5d]
581 bool x86AssemblyInspectionEngine::pop_rbp_pattern_p() {
582   uint8_t *p = m_cur_insn;
583   return (*p == 0x5d);
584 }
585 
586 // instructions valid only in 32-bit mode:
587 // 0x1f - pop ds
588 // 0x07 - pop es
589 // 0x17 - pop ss
590 bool x86AssemblyInspectionEngine::pop_misc_reg_p() {
591   uint8_t p = *m_cur_insn;
592   if (m_wordsize == 4) {
593     if (p == 0x1f || p == 0x07 || p == 0x17)
594       return true;
595   }
596   return false;
597 }
598 
599 // leave [0xc9]
600 bool x86AssemblyInspectionEngine::leave_pattern_p() {
601   uint8_t *p = m_cur_insn;
602   return (*p == 0xc9);
603 }
604 
605 // call $0 [0xe8 0x0 0x0 0x0 0x0]
606 bool x86AssemblyInspectionEngine::call_next_insn_pattern_p() {
607   uint8_t *p = m_cur_insn;
608   return (*p == 0xe8) && (*(p + 1) == 0x0) && (*(p + 2) == 0x0) &&
609          (*(p + 3) == 0x0) && (*(p + 4) == 0x0);
610 }
611 
612 // Look for an instruction sequence storing a nonvolatile register on to the
613 // stack frame.
614 
615 //  movq %rax, -0x10(%rbp) [0x48 0x89 0x45 0xf0]
616 //  movl %eax, -0xc(%ebp)  [0x89 0x45 0xf4]
617 
618 // The offset value returned in rbp_offset will be positive -- but it must be
619 // subtraced from the frame base register to get the actual location.  The
620 // positive value returned for the offset is a convention used elsewhere for
621 // CFA offsets et al.
622 
623 bool x86AssemblyInspectionEngine::mov_reg_to_local_stack_frame_p(
624     int &regno, int &rbp_offset) {
625   uint8_t *p = m_cur_insn;
626   int src_reg_prefix_bit = 0;
627   int target_reg_prefix_bit = 0;
628 
629   if (m_wordsize == 8 && REX_W_PREFIX_P(*p)) {
630     src_reg_prefix_bit = REX_W_SRCREG(*p) << 3;
631     target_reg_prefix_bit = REX_W_DSTREG(*p) << 3;
632     if (target_reg_prefix_bit == 1) {
633       // rbp/ebp don't need a prefix bit - we know this isn't the reg we care
634       // about.
635       return false;
636     }
637     p++;
638   }
639 
640   if (*p == 0x89) {
641     /* Mask off the 3-5 bits which indicate the destination register
642        if this is a ModR/M byte.  */
643     int opcode_destreg_masked_out = *(p + 1) & (~0x38);
644 
645     /* Is this a ModR/M byte with Mod bits 01 and R/M bits 101
646        and three bits between them, e.g. 01nnn101
647        We're looking for a destination of ebp-disp8 or ebp-disp32.   */
648     int immsize;
649     if (opcode_destreg_masked_out == 0x45)
650       immsize = 2;
651     else if (opcode_destreg_masked_out == 0x85)
652       immsize = 4;
653     else
654       return false;
655 
656     int offset = 0;
657     if (immsize == 2)
658       offset = (int8_t) * (p + 2);
659     if (immsize == 4)
660       offset = (uint32_t)extract_4(p + 2);
661     if (offset > 0)
662       return false;
663 
664     regno = ((*(p + 1) >> 3) & 0x7) | src_reg_prefix_bit;
665     rbp_offset = offset > 0 ? offset : -offset;
666     return true;
667   }
668   return false;
669 }
670 
671 // Returns true if this is a jmp instruction where we can't
672 // know the destination address statically.
673 //
674 // ff e0                                   jmpq   *%rax
675 // ff e1                                   jmpq   *%rcx
676 // ff 60 28                                jmpq   *0x28(%rax)
677 // ff 60 60                                jmpq   *0x60(%rax)
678 bool x86AssemblyInspectionEngine::jmp_to_reg_p() {
679   if (*m_cur_insn != 0xff)
680     return false;
681 
682   // The second byte is a ModR/M /4 byte, strip off the registers
683   uint8_t second_byte_sans_reg = *(m_cur_insn + 1) & ~7;
684 
685   // Don't handle 0x24 disp32, because the target address is
686   // knowable statically - pc_rel_branch_or_jump_p() will
687   // return the target address.
688 
689   // [reg]
690   if (second_byte_sans_reg == 0x20)
691     return true;
692 
693   // [reg]+disp8
694   if (second_byte_sans_reg == 0x60)
695     return true;
696 
697   // [reg]+disp32
698   if (second_byte_sans_reg == 0xa0)
699     return true;
700 
701   // reg
702   if (second_byte_sans_reg == 0xe0)
703     return true;
704 
705   // disp32
706   // jumps to an address stored in memory, the value can't be cached
707   // in an unwind plan.
708   if (second_byte_sans_reg == 0x24)
709     return true;
710 
711   // use SIB byte
712   // ff 24 fe  jmpq   *(%rsi,%rdi,8)
713   if (second_byte_sans_reg == 0x24)
714     return true;
715 
716   return false;
717 }
718 
719 // Detect branches to fixed pc-relative offsets.
720 // Returns the offset from the address of the next instruction
721 // that may be branch/jumped to.
722 //
723 // Cannot determine the offset of a JMP that jumps to the address in
724 // a register ("jmpq *%rax") or offset from a register value
725 // ("jmpq *0x28(%rax)"), this method will return false on those
726 // instructions.
727 //
728 // These instructions all end in either a relative 8/16/32 bit value
729 // depending on the instruction and the current execution mode of the
730 // inferior process.  Once we know the size of the opcode instruction,
731 // we can use the total instruction length to determine the size of
732 // the relative offset without having to compute it correctly.
733 
734 bool x86AssemblyInspectionEngine::pc_rel_branch_or_jump_p (
735     const int instruction_length, int &offset)
736 {
737   int opcode_size = 0;
738 
739   uint8_t b1 = m_cur_insn[0];
740 
741   switch (b1) {
742     case 0x77: // JA/JNBE rel8
743     case 0x73: // JAE/JNB/JNC rel8
744     case 0x72: // JB/JC/JNAE rel8
745     case 0x76: // JBE/JNA rel8
746     case 0xe3: // JCXZ/JECXZ/JRCXZ rel8
747     case 0x74: // JE/JZ rel8
748     case 0x7f: // JG/JNLE rel8
749     case 0x7d: // JGE/JNL rel8
750     case 0x7c: // JL/JNGE rel8
751     case 0x7e: // JNG/JLE rel8
752     case 0x71: // JNO rel8
753     case 0x7b: // JNP/JPO rel8
754     case 0x79: // JNS rel8
755     case 0x75: // JNE/JNZ rel8
756     case 0x70: // JO rel8
757     case 0x7a: // JP/JPE rel8
758     case 0x78: // JS rel8
759     case 0xeb: // JMP rel8
760     case 0xe9: // JMP rel16/rel32
761       opcode_size = 1;
762       break;
763     default:
764       break;
765   }
766   if (b1 == 0x0f && opcode_size == 0) {
767     uint8_t b2 = m_cur_insn[1];
768     switch (b2) {
769       case 0x87: // JA/JNBE rel16/rel32
770       case 0x86: // JBE/JNA rel16/rel32
771       case 0x84: // JE/JZ rel16/rel32
772       case 0x8f: // JG/JNLE rel16/rel32
773       case 0x8d: // JNL/JGE rel16/rel32
774       case 0x8e: // JLE rel16/rel32
775       case 0x82: // JB/JC/JNAE rel16/rel32
776       case 0x83: // JAE/JNB/JNC rel16/rel32
777       case 0x85: // JNE/JNZ rel16/rel32
778       case 0x8c: // JL/JNGE rel16/rel32
779       case 0x81: // JNO rel16/rel32
780       case 0x8b: // JNP/JPO rel16/rel32
781       case 0x89: // JNS rel16/rel32
782       case 0x80: // JO rel16/rel32
783       case 0x8a: // JP rel16/rel32
784       case 0x88: // JS rel16/rel32
785         opcode_size = 2;
786         break;
787       default:
788         break;
789     }
790   }
791 
792   if (opcode_size == 0)
793     return false;
794 
795   offset = 0;
796   if (instruction_length - opcode_size == 1) {
797     int8_t rel8 = (int8_t) *(m_cur_insn + opcode_size);
798     offset = rel8;
799   } else if (instruction_length - opcode_size == 2) {
800     int16_t rel16 = extract_2_signed (m_cur_insn + opcode_size);
801     offset = rel16;
802   } else if (instruction_length - opcode_size == 4) {
803     int32_t rel32 = extract_4_signed (m_cur_insn + opcode_size);
804     offset = rel32;
805   } else {
806     return false;
807   }
808   return true;
809 }
810 
811 // Returns true if this instruction is a intra-function branch or jump -
812 // a branch/jump within the bounds of this same function.
813 // Cannot predict where a jump through a register value ("jmpq *%rax")
814 // will go, so it will return false on that instruction.
815 bool x86AssemblyInspectionEngine::local_branch_p (
816     const addr_t current_func_text_offset,
817     const AddressRange &func_range,
818     const int instruction_length,
819     addr_t &target_insn_offset) {
820   int offset;
821   if (pc_rel_branch_or_jump_p (instruction_length, offset) && offset != 0) {
822     addr_t next_pc_value = current_func_text_offset + instruction_length;
823     if (offset < 0 && addr_t(-offset) > current_func_text_offset) {
824       // Branch target is before the start of this function
825       return false;
826     }
827     if (offset + next_pc_value > func_range.GetByteSize()) {
828       // Branch targets outside this function's bounds
829       return false;
830     }
831     // This instruction branches to target_insn_offset (byte offset into the function)
832     target_insn_offset = next_pc_value + offset;
833     return true;
834   }
835   return false;
836 }
837 
838 // Returns true if this instruction is a inter-function branch or jump - a
839 // branch/jump to another function.
840 // Cannot predict where a jump through a register value ("jmpq *%rax")
841 // will go, so it will return false on that instruction.
842 bool x86AssemblyInspectionEngine::non_local_branch_p (
843     const addr_t current_func_text_offset,
844     const AddressRange &func_range,
845     const int instruction_length) {
846   int offset;
847   addr_t target_insn_offset;
848   if (pc_rel_branch_or_jump_p (instruction_length, offset)) {
849     return !local_branch_p(current_func_text_offset,func_range,instruction_length,target_insn_offset);
850   }
851   return false;
852 }
853 
854 // ret [0xc3] or [0xcb] or [0xc2 imm16] or [0xca imm16]
855 bool x86AssemblyInspectionEngine::ret_pattern_p() {
856   uint8_t *p = m_cur_insn;
857   return *p == 0xc3 || *p == 0xc2 || *p == 0xca || *p == 0xcb;
858 }
859 
860 uint16_t x86AssemblyInspectionEngine::extract_2(uint8_t *b) {
861   uint16_t v = 0;
862   for (int i = 1; i >= 0; i--)
863     v = (v << 8) | b[i];
864   return v;
865 }
866 
867 int16_t x86AssemblyInspectionEngine::extract_2_signed(uint8_t *b) {
868   int16_t v = 0;
869   for (int i = 1; i >= 0; i--)
870     v = (v << 8) | b[i];
871   return v;
872 }
873 
874 uint32_t x86AssemblyInspectionEngine::extract_4(uint8_t *b) {
875   uint32_t v = 0;
876   for (int i = 3; i >= 0; i--)
877     v = (v << 8) | b[i];
878   return v;
879 }
880 
881 int32_t x86AssemblyInspectionEngine::extract_4_signed(uint8_t *b) {
882   int32_t v = 0;
883   for (int i = 3; i >= 0; i--)
884     v = (v << 8) | b[i];
885   return v;
886 }
887 
888 
889 bool x86AssemblyInspectionEngine::instruction_length(uint8_t *insn_p,
890                                                      int &length,
891                                                      uint32_t buffer_remaining_bytes) {
892 
893   uint32_t max_op_byte_size = std::min(buffer_remaining_bytes, m_arch.GetMaximumOpcodeByteSize());
894   llvm::SmallVector<uint8_t, 32> opcode_data;
895   opcode_data.resize(max_op_byte_size);
896 
897   char out_string[512];
898   const size_t inst_size =
899       ::LLVMDisasmInstruction(m_disasm_context, insn_p, max_op_byte_size, 0,
900                               out_string, sizeof(out_string));
901 
902   length = inst_size;
903   return true;
904 }
905 
906 bool x86AssemblyInspectionEngine::machine_regno_to_lldb_regno(
907     int machine_regno, uint32_t &lldb_regno) {
908   MachineRegnumToNameAndLLDBRegnum::iterator it = m_reg_map.find(machine_regno);
909   if (it != m_reg_map.end()) {
910     lldb_regno = it->second.lldb_regnum;
911     return true;
912   }
913   return false;
914 }
915 
916 bool x86AssemblyInspectionEngine::GetNonCallSiteUnwindPlanFromAssembly(
917     uint8_t *data, size_t size, AddressRange &func_range,
918     UnwindPlan &unwind_plan) {
919   unwind_plan.Clear();
920 
921   if (data == nullptr || size == 0)
922     return false;
923 
924   if (!m_register_map_initialized)
925     return false;
926 
927   addr_t current_func_text_offset = 0;
928   int current_sp_bytes_offset_from_fa = 0;
929   bool is_aligned = false;
930   UnwindPlan::Row::RegisterLocation initial_regloc;
931   UnwindPlan::RowSP row(new UnwindPlan::Row);
932 
933   unwind_plan.SetPlanValidAddressRange(func_range);
934   unwind_plan.SetRegisterKind(eRegisterKindLLDB);
935 
936   // At the start of the function, find the CFA by adding wordsize to the SP
937   // register
938   row->SetOffset(current_func_text_offset);
939   row->GetCFAValue().SetIsRegisterPlusOffset(m_lldb_sp_regnum, m_wordsize);
940 
941   // caller's stack pointer value before the call insn is the CFA address
942   initial_regloc.SetIsCFAPlusOffset(0);
943   row->SetRegisterInfo(m_lldb_sp_regnum, initial_regloc);
944 
945   // saved instruction pointer can be found at CFA - wordsize.
946   current_sp_bytes_offset_from_fa = m_wordsize;
947   initial_regloc.SetAtCFAPlusOffset(-current_sp_bytes_offset_from_fa);
948   row->SetRegisterInfo(m_lldb_ip_regnum, initial_regloc);
949 
950   unwind_plan.AppendRow(row);
951 
952   // Allocate a new Row, populate it with the existing Row contents.
953   UnwindPlan::Row *newrow = new UnwindPlan::Row;
954   *newrow = *row.get();
955   row.reset(newrow);
956 
957   // Track which registers have been saved so far in the prologue. If we see
958   // another push of that register, it's not part of the prologue. The register
959   // numbers used here are the machine register #'s (i386_register_numbers,
960   // x86_64_register_numbers).
961   std::vector<bool> saved_registers(32, false);
962 
963   // Once the prologue has completed we'll save a copy of the unwind
964   // instructions If there is an epilogue in the middle of the function, after
965   // that epilogue we'll reinstate the unwind setup -- we assume that some code
966   // path jumps over the mid-function epilogue
967 
968   UnwindPlan::RowSP prologue_completed_row; // copy of prologue row of CFI
969   int prologue_completed_sp_bytes_offset_from_cfa; // The sp value before the
970                                                    // epilogue started executed
971   bool prologue_completed_is_aligned = false;
972   std::vector<bool> prologue_completed_saved_registers;
973 
974   while (current_func_text_offset < size) {
975     int stack_offset, insn_len;
976     int machine_regno;   // register numbers masked directly out of instructions
977     uint32_t lldb_regno; // register numbers in lldb's eRegisterKindLLDB
978                          // numbering scheme
979 
980     bool in_epilogue = false; // we're in the middle of an epilogue sequence
981     bool row_updated = false; // The UnwindPlan::Row 'row' has been updated
982 
983     m_cur_insn = data + current_func_text_offset;
984     if (!instruction_length(m_cur_insn, insn_len, size - current_func_text_offset)
985         || insn_len == 0
986         || insn_len > kMaxInstructionByteSize) {
987       // An unrecognized/junk instruction
988       break;
989     }
990 
991     auto &cfa_value = row->GetCFAValue();
992     auto &afa_value = row->GetAFAValue();
993     auto fa_value_ptr = is_aligned ? &afa_value : &cfa_value;
994 
995     if (mov_rsp_rbp_pattern_p()) {
996       if (fa_value_ptr->GetRegisterNumber() == m_lldb_sp_regnum) {
997         fa_value_ptr->SetIsRegisterPlusOffset(
998             m_lldb_fp_regnum, fa_value_ptr->GetOffset());
999         row_updated = true;
1000       }
1001     }
1002 
1003     else if (mov_rsp_rbx_pattern_p()) {
1004       if (fa_value_ptr->GetRegisterNumber() == m_lldb_sp_regnum) {
1005         fa_value_ptr->SetIsRegisterPlusOffset(
1006             m_lldb_alt_fp_regnum, fa_value_ptr->GetOffset());
1007         row_updated = true;
1008       }
1009     }
1010 
1011     else if (and_rsp_pattern_p()) {
1012       current_sp_bytes_offset_from_fa = 0;
1013       afa_value.SetIsRegisterPlusOffset(
1014           m_lldb_sp_regnum, current_sp_bytes_offset_from_fa);
1015       fa_value_ptr = &afa_value;
1016       is_aligned = true;
1017       row_updated = true;
1018     }
1019 
1020     else if (mov_rbp_rsp_pattern_p()) {
1021       if (is_aligned && cfa_value.GetRegisterNumber() == m_lldb_fp_regnum)
1022       {
1023         is_aligned = false;
1024         fa_value_ptr = &cfa_value;
1025         afa_value.SetUnspecified();
1026         row_updated = true;
1027       }
1028       if (fa_value_ptr->GetRegisterNumber() == m_lldb_fp_regnum)
1029         current_sp_bytes_offset_from_fa = fa_value_ptr->GetOffset();
1030     }
1031 
1032     else if (mov_rbx_rsp_pattern_p()) {
1033       if (is_aligned && cfa_value.GetRegisterNumber() == m_lldb_alt_fp_regnum)
1034       {
1035         is_aligned = false;
1036         fa_value_ptr = &cfa_value;
1037         afa_value.SetUnspecified();
1038         row_updated = true;
1039       }
1040       if (fa_value_ptr->GetRegisterNumber() == m_lldb_alt_fp_regnum)
1041         current_sp_bytes_offset_from_fa = fa_value_ptr->GetOffset();
1042     }
1043 
1044     // This is the start() function (or a pthread equivalent), it starts with a
1045     // pushl $0x0 which puts the saved pc value of 0 on the stack.  In this
1046     // case we want to pretend we didn't see a stack movement at all --
1047     // normally the saved pc value is already on the stack by the time the
1048     // function starts executing.
1049     else if (push_0_pattern_p()) {
1050     }
1051 
1052     else if (push_reg_p(machine_regno)) {
1053       current_sp_bytes_offset_from_fa += m_wordsize;
1054       // the PUSH instruction has moved the stack pointer - if the FA is set
1055       // in terms of the stack pointer, we need to add a new row of
1056       // instructions.
1057       if (fa_value_ptr->GetRegisterNumber() == m_lldb_sp_regnum) {
1058         fa_value_ptr->SetOffset(current_sp_bytes_offset_from_fa);
1059         row_updated = true;
1060       }
1061       // record where non-volatile (callee-saved, spilled) registers are saved
1062       // on the stack
1063       if (nonvolatile_reg_p(machine_regno) &&
1064           machine_regno_to_lldb_regno(machine_regno, lldb_regno) &&
1065           !saved_registers[machine_regno]) {
1066         UnwindPlan::Row::RegisterLocation regloc;
1067         if (is_aligned)
1068             regloc.SetAtAFAPlusOffset(-current_sp_bytes_offset_from_fa);
1069         else
1070             regloc.SetAtCFAPlusOffset(-current_sp_bytes_offset_from_fa);
1071         row->SetRegisterInfo(lldb_regno, regloc);
1072         saved_registers[machine_regno] = true;
1073         row_updated = true;
1074       }
1075     }
1076 
1077     else if (pop_reg_p(machine_regno)) {
1078       current_sp_bytes_offset_from_fa -= m_wordsize;
1079 
1080       if (nonvolatile_reg_p(machine_regno) &&
1081           machine_regno_to_lldb_regno(machine_regno, lldb_regno) &&
1082           saved_registers[machine_regno]) {
1083         saved_registers[machine_regno] = false;
1084         row->RemoveRegisterInfo(lldb_regno);
1085 
1086         if (lldb_regno == fa_value_ptr->GetRegisterNumber()) {
1087           fa_value_ptr->SetIsRegisterPlusOffset(
1088               m_lldb_sp_regnum, fa_value_ptr->GetOffset());
1089         }
1090 
1091         in_epilogue = true;
1092         row_updated = true;
1093       }
1094 
1095       // the POP instruction has moved the stack pointer - if the FA is set in
1096       // terms of the stack pointer, we need to add a new row of instructions.
1097       if (fa_value_ptr->GetRegisterNumber() == m_lldb_sp_regnum) {
1098         fa_value_ptr->SetIsRegisterPlusOffset(
1099             m_lldb_sp_regnum, current_sp_bytes_offset_from_fa);
1100         row_updated = true;
1101       }
1102     }
1103 
1104     else if (pop_misc_reg_p()) {
1105       current_sp_bytes_offset_from_fa -= m_wordsize;
1106       if (fa_value_ptr->GetRegisterNumber() == m_lldb_sp_regnum) {
1107         fa_value_ptr->SetIsRegisterPlusOffset(
1108             m_lldb_sp_regnum, current_sp_bytes_offset_from_fa);
1109         row_updated = true;
1110       }
1111     }
1112 
1113     // The LEAVE instruction moves the value from rbp into rsp and pops a value
1114     // off the stack into rbp (restoring the caller's rbp value). It is the
1115     // opposite of ENTER, or 'push rbp, mov rsp rbp'.
1116     else if (leave_pattern_p()) {
1117       if (saved_registers[m_machine_fp_regnum]) {
1118         saved_registers[m_machine_fp_regnum] = false;
1119         row->RemoveRegisterInfo(m_lldb_fp_regnum);
1120 
1121         row_updated = true;
1122       }
1123 
1124       if (is_aligned && cfa_value.GetRegisterNumber() == m_lldb_fp_regnum)
1125       {
1126         is_aligned = false;
1127         fa_value_ptr = &cfa_value;
1128         afa_value.SetUnspecified();
1129         row_updated = true;
1130       }
1131 
1132       if (fa_value_ptr->GetRegisterNumber() == m_lldb_fp_regnum)
1133       {
1134         fa_value_ptr->SetIsRegisterPlusOffset(
1135             m_lldb_sp_regnum, fa_value_ptr->GetOffset());
1136 
1137         current_sp_bytes_offset_from_fa = fa_value_ptr->GetOffset();
1138       }
1139 
1140       current_sp_bytes_offset_from_fa -= m_wordsize;
1141 
1142       if (fa_value_ptr->GetRegisterNumber() == m_lldb_sp_regnum) {
1143         fa_value_ptr->SetIsRegisterPlusOffset(
1144             m_lldb_sp_regnum, current_sp_bytes_offset_from_fa);
1145         row_updated = true;
1146       }
1147 
1148       in_epilogue = true;
1149     }
1150 
1151     else if (mov_reg_to_local_stack_frame_p(machine_regno, stack_offset) &&
1152              nonvolatile_reg_p(machine_regno) &&
1153              machine_regno_to_lldb_regno(machine_regno, lldb_regno) &&
1154              !saved_registers[machine_regno]) {
1155       saved_registers[machine_regno] = true;
1156 
1157       UnwindPlan::Row::RegisterLocation regloc;
1158 
1159       // stack_offset for 'movq %r15, -80(%rbp)' will be 80. In the Row, we
1160       // want to express this as the offset from the FA.  If the frame base is
1161       // rbp (like the above instruction), the FA offset for rbp is probably
1162       // 16.  So we want to say that the value is stored at the FA address -
1163       // 96.
1164       if (is_aligned)
1165           regloc.SetAtAFAPlusOffset(-(stack_offset + fa_value_ptr->GetOffset()));
1166       else
1167           regloc.SetAtCFAPlusOffset(-(stack_offset + fa_value_ptr->GetOffset()));
1168 
1169       row->SetRegisterInfo(lldb_regno, regloc);
1170 
1171       row_updated = true;
1172     }
1173 
1174     else if (sub_rsp_pattern_p(stack_offset)) {
1175       current_sp_bytes_offset_from_fa += stack_offset;
1176       if (fa_value_ptr->GetRegisterNumber() == m_lldb_sp_regnum) {
1177         fa_value_ptr->SetOffset(current_sp_bytes_offset_from_fa);
1178         row_updated = true;
1179       }
1180     }
1181 
1182     else if (add_rsp_pattern_p(stack_offset)) {
1183       current_sp_bytes_offset_from_fa -= stack_offset;
1184       if (fa_value_ptr->GetRegisterNumber() == m_lldb_sp_regnum) {
1185         fa_value_ptr->SetOffset(current_sp_bytes_offset_from_fa);
1186         row_updated = true;
1187       }
1188       in_epilogue = true;
1189     }
1190 
1191     else if (push_extended_pattern_p() || push_imm_pattern_p() ||
1192              push_misc_reg_p()) {
1193       current_sp_bytes_offset_from_fa += m_wordsize;
1194       if (fa_value_ptr->GetRegisterNumber() == m_lldb_sp_regnum) {
1195         fa_value_ptr->SetOffset(current_sp_bytes_offset_from_fa);
1196         row_updated = true;
1197       }
1198     }
1199 
1200     else if (lea_rsp_pattern_p(stack_offset)) {
1201       current_sp_bytes_offset_from_fa -= stack_offset;
1202       if (fa_value_ptr->GetRegisterNumber() == m_lldb_sp_regnum) {
1203         fa_value_ptr->SetOffset(current_sp_bytes_offset_from_fa);
1204         row_updated = true;
1205       }
1206       if (stack_offset > 0)
1207         in_epilogue = true;
1208     }
1209 
1210     else if (lea_rbp_rsp_pattern_p(stack_offset)) {
1211       if (is_aligned &&
1212           cfa_value.GetRegisterNumber() == m_lldb_fp_regnum) {
1213         is_aligned = false;
1214         fa_value_ptr = &cfa_value;
1215         afa_value.SetUnspecified();
1216         row_updated = true;
1217       }
1218       if (fa_value_ptr->GetRegisterNumber() == m_lldb_fp_regnum) {
1219         current_sp_bytes_offset_from_fa =
1220           fa_value_ptr->GetOffset() - stack_offset;
1221       }
1222     }
1223 
1224     else if (lea_rbx_rsp_pattern_p(stack_offset)) {
1225       if (is_aligned &&
1226           cfa_value.GetRegisterNumber() == m_lldb_alt_fp_regnum) {
1227         is_aligned = false;
1228         fa_value_ptr = &cfa_value;
1229         afa_value.SetUnspecified();
1230         row_updated = true;
1231       }
1232       if (fa_value_ptr->GetRegisterNumber() == m_lldb_alt_fp_regnum) {
1233         current_sp_bytes_offset_from_fa = fa_value_ptr->GetOffset() - stack_offset;
1234       }
1235     }
1236 
1237     else if (prologue_completed_row.get() &&
1238              (ret_pattern_p() ||
1239               non_local_branch_p (current_func_text_offset, func_range, insn_len) ||
1240               jmp_to_reg_p())) {
1241       // Check if the current instruction is the end of an epilogue sequence,
1242       // and if so, re-instate the prologue-completed unwind state.
1243 
1244       // The current instruction is a branch/jump outside this function,
1245       // a ret, or a jump through a register value which we cannot
1246       // determine the effcts of.  Verify that the stack frame state
1247       // has been unwound to the same as it was at function entry to avoid
1248       // mis-identifying a JMP instruction as an epilogue.
1249       UnwindPlan::Row::RegisterLocation sp, pc;
1250       if (row->GetRegisterInfo(m_lldb_sp_regnum, sp) &&
1251           row->GetRegisterInfo(m_lldb_ip_regnum, pc)) {
1252         // Any ret instruction variant is definitely indicative of an
1253         // epilogue; for other insn patterns verify that we're back to
1254         // the original unwind state.
1255         if (ret_pattern_p() ||
1256             (sp.IsCFAPlusOffset() && sp.GetOffset() == 0 &&
1257             pc.IsAtCFAPlusOffset() && pc.GetOffset() == -m_wordsize)) {
1258           // Reinstate the saved prologue setup for any instructions that come
1259           // after the epilogue
1260 
1261           UnwindPlan::Row *newrow = new UnwindPlan::Row;
1262           *newrow = *prologue_completed_row.get();
1263           row.reset(newrow);
1264           current_sp_bytes_offset_from_fa =
1265               prologue_completed_sp_bytes_offset_from_cfa;
1266           is_aligned = prologue_completed_is_aligned;
1267 
1268           saved_registers.clear();
1269           saved_registers.resize(prologue_completed_saved_registers.size(), false);
1270           for (size_t i = 0; i < prologue_completed_saved_registers.size(); ++i) {
1271             saved_registers[i] = prologue_completed_saved_registers[i];
1272           }
1273 
1274           in_epilogue = true;
1275           row_updated = true;
1276         }
1277       }
1278     }
1279 
1280     // call next instruction
1281     //     call 0
1282     //  => pop  %ebx
1283     // This is used in i386 programs to get the PIC base address for finding
1284     // global data
1285     else if (call_next_insn_pattern_p()) {
1286       current_sp_bytes_offset_from_fa += m_wordsize;
1287       if (fa_value_ptr->GetRegisterNumber() == m_lldb_sp_regnum) {
1288         fa_value_ptr->SetOffset(current_sp_bytes_offset_from_fa);
1289         row_updated = true;
1290       }
1291     }
1292 
1293     if (row_updated) {
1294       if (current_func_text_offset + insn_len < size) {
1295         row->SetOffset(current_func_text_offset + insn_len);
1296         unwind_plan.AppendRow(row);
1297         // Allocate a new Row, populate it with the existing Row contents.
1298         newrow = new UnwindPlan::Row;
1299         *newrow = *row.get();
1300         row.reset(newrow);
1301       }
1302     }
1303 
1304     if (!in_epilogue && row_updated) {
1305       // If we're not in an epilogue sequence, save the updated Row
1306       UnwindPlan::Row *newrow = new UnwindPlan::Row;
1307       *newrow = *row.get();
1308       prologue_completed_row.reset(newrow);
1309 
1310       prologue_completed_saved_registers.clear();
1311       prologue_completed_saved_registers.resize(saved_registers.size(), false);
1312       for (size_t i = 0; i < saved_registers.size(); ++i) {
1313         prologue_completed_saved_registers[i] = saved_registers[i];
1314       }
1315     }
1316 
1317     // We may change the sp value without adding a new Row necessarily -- keep
1318     // track of it either way.
1319     if (!in_epilogue) {
1320       prologue_completed_sp_bytes_offset_from_cfa =
1321           current_sp_bytes_offset_from_fa;
1322       prologue_completed_is_aligned = is_aligned;
1323     }
1324 
1325     m_cur_insn = m_cur_insn + insn_len;
1326     current_func_text_offset += insn_len;
1327   }
1328 
1329   unwind_plan.SetSourceName("assembly insn profiling");
1330   unwind_plan.SetSourcedFromCompiler(eLazyBoolNo);
1331   unwind_plan.SetUnwindPlanValidAtAllInstructions(eLazyBoolYes);
1332   unwind_plan.SetUnwindPlanForSignalTrap(eLazyBoolNo);
1333 
1334   return true;
1335 }
1336 
1337 bool x86AssemblyInspectionEngine::AugmentUnwindPlanFromCallSite(
1338     uint8_t *data, size_t size, AddressRange &func_range,
1339     UnwindPlan &unwind_plan, RegisterContextSP &reg_ctx) {
1340   Address addr_start = func_range.GetBaseAddress();
1341   if (!addr_start.IsValid())
1342     return false;
1343 
1344   // We either need a live RegisterContext, or we need the UnwindPlan to
1345   // already be in the lldb register numbering scheme.
1346   if (reg_ctx.get() == nullptr &&
1347       unwind_plan.GetRegisterKind() != eRegisterKindLLDB)
1348     return false;
1349 
1350   // Is original unwind_plan valid?
1351   // unwind_plan should have at least one row which is ABI-default (CFA
1352   // register is sp), and another row in mid-function.
1353   if (unwind_plan.GetRowCount() < 2)
1354     return false;
1355 
1356   UnwindPlan::RowSP first_row = unwind_plan.GetRowAtIndex(0);
1357   if (first_row->GetOffset() != 0)
1358     return false;
1359   uint32_t cfa_reg = first_row->GetCFAValue().GetRegisterNumber();
1360   if (unwind_plan.GetRegisterKind() != eRegisterKindLLDB) {
1361     cfa_reg = reg_ctx->ConvertRegisterKindToRegisterNumber(
1362         unwind_plan.GetRegisterKind(),
1363         first_row->GetCFAValue().GetRegisterNumber());
1364   }
1365   if (cfa_reg != m_lldb_sp_regnum ||
1366       first_row->GetCFAValue().GetOffset() != m_wordsize)
1367     return false;
1368 
1369   UnwindPlan::RowSP original_last_row = unwind_plan.GetRowForFunctionOffset(-1);
1370 
1371   size_t offset = 0;
1372   int row_id = 1;
1373   bool unwind_plan_updated = false;
1374   UnwindPlan::RowSP row(new UnwindPlan::Row(*first_row));
1375 
1376   // After a mid-function epilogue we will need to re-insert the original
1377   // unwind rules so unwinds work for the remainder of the function.  These
1378   // aren't common with clang/gcc on x86 but it is possible.
1379   bool reinstate_unwind_state = false;
1380 
1381   while (offset < size) {
1382     m_cur_insn = data + offset;
1383     int insn_len;
1384     if (!instruction_length(m_cur_insn, insn_len, size - offset) ||
1385         insn_len == 0 || insn_len > kMaxInstructionByteSize) {
1386       // An unrecognized/junk instruction.
1387       break;
1388     }
1389 
1390     // Advance offsets.
1391     offset += insn_len;
1392 
1393     // offset is pointing beyond the bounds of the function; stop looping.
1394     if (offset >= size)
1395       continue;
1396 
1397     if (reinstate_unwind_state) {
1398       UnwindPlan::RowSP new_row(new UnwindPlan::Row());
1399       *new_row = *original_last_row;
1400       new_row->SetOffset(offset);
1401       unwind_plan.AppendRow(new_row);
1402       row = std::make_shared<UnwindPlan::Row>();
1403       *row = *new_row;
1404       reinstate_unwind_state = false;
1405       unwind_plan_updated = true;
1406       continue;
1407     }
1408 
1409     // If we already have one row for this instruction, we can continue.
1410     while (row_id < unwind_plan.GetRowCount() &&
1411            unwind_plan.GetRowAtIndex(row_id)->GetOffset() <= offset) {
1412       row_id++;
1413     }
1414     UnwindPlan::RowSP original_row = unwind_plan.GetRowAtIndex(row_id - 1);
1415     if (original_row->GetOffset() == offset) {
1416       *row = *original_row;
1417       continue;
1418     }
1419 
1420     if (row_id == 0) {
1421       // If we are here, compiler didn't generate CFI for prologue. This won't
1422       // happen to GCC or clang. In this case, bail out directly.
1423       return false;
1424     }
1425 
1426     // Inspect the instruction to check if we need a new row for it.
1427     cfa_reg = row->GetCFAValue().GetRegisterNumber();
1428     if (unwind_plan.GetRegisterKind() != eRegisterKindLLDB) {
1429       cfa_reg = reg_ctx->ConvertRegisterKindToRegisterNumber(
1430           unwind_plan.GetRegisterKind(),
1431           row->GetCFAValue().GetRegisterNumber());
1432     }
1433     if (cfa_reg == m_lldb_sp_regnum) {
1434       // CFA register is sp.
1435 
1436       // call next instruction
1437       //     call 0
1438       //  => pop  %ebx
1439       if (call_next_insn_pattern_p()) {
1440         row->SetOffset(offset);
1441         row->GetCFAValue().IncOffset(m_wordsize);
1442 
1443         UnwindPlan::RowSP new_row(new UnwindPlan::Row(*row));
1444         unwind_plan.InsertRow(new_row);
1445         unwind_plan_updated = true;
1446         continue;
1447       }
1448 
1449       // push/pop register
1450       int regno;
1451       if (push_reg_p(regno)) {
1452         row->SetOffset(offset);
1453         row->GetCFAValue().IncOffset(m_wordsize);
1454 
1455         UnwindPlan::RowSP new_row(new UnwindPlan::Row(*row));
1456         unwind_plan.InsertRow(new_row);
1457         unwind_plan_updated = true;
1458         continue;
1459       }
1460       if (pop_reg_p(regno)) {
1461         // Technically, this might be a nonvolatile register recover in
1462         // epilogue. We should reset RegisterInfo for the register. But in
1463         // practice, previous rule for the register is still valid... So we
1464         // ignore this case.
1465 
1466         row->SetOffset(offset);
1467         row->GetCFAValue().IncOffset(-m_wordsize);
1468 
1469         UnwindPlan::RowSP new_row(new UnwindPlan::Row(*row));
1470         unwind_plan.InsertRow(new_row);
1471         unwind_plan_updated = true;
1472         continue;
1473       }
1474 
1475       if (pop_misc_reg_p()) {
1476         row->SetOffset(offset);
1477         row->GetCFAValue().IncOffset(-m_wordsize);
1478 
1479         UnwindPlan::RowSP new_row(new UnwindPlan::Row(*row));
1480         unwind_plan.InsertRow(new_row);
1481         unwind_plan_updated = true;
1482         continue;
1483       }
1484 
1485       // push imm
1486       if (push_imm_pattern_p()) {
1487         row->SetOffset(offset);
1488         row->GetCFAValue().IncOffset(m_wordsize);
1489         UnwindPlan::RowSP new_row(new UnwindPlan::Row(*row));
1490         unwind_plan.InsertRow(new_row);
1491         unwind_plan_updated = true;
1492         continue;
1493       }
1494 
1495       // push extended
1496       if (push_extended_pattern_p() || push_misc_reg_p()) {
1497         row->SetOffset(offset);
1498         row->GetCFAValue().IncOffset(m_wordsize);
1499         UnwindPlan::RowSP new_row(new UnwindPlan::Row(*row));
1500         unwind_plan.InsertRow(new_row);
1501         unwind_plan_updated = true;
1502         continue;
1503       }
1504 
1505       // add/sub %rsp/%esp
1506       int amount;
1507       if (add_rsp_pattern_p(amount)) {
1508         row->SetOffset(offset);
1509         row->GetCFAValue().IncOffset(-amount);
1510 
1511         UnwindPlan::RowSP new_row(new UnwindPlan::Row(*row));
1512         unwind_plan.InsertRow(new_row);
1513         unwind_plan_updated = true;
1514         continue;
1515       }
1516       if (sub_rsp_pattern_p(amount)) {
1517         row->SetOffset(offset);
1518         row->GetCFAValue().IncOffset(amount);
1519 
1520         UnwindPlan::RowSP new_row(new UnwindPlan::Row(*row));
1521         unwind_plan.InsertRow(new_row);
1522         unwind_plan_updated = true;
1523         continue;
1524       }
1525 
1526       // lea %rsp, [%rsp + $offset]
1527       if (lea_rsp_pattern_p(amount)) {
1528         row->SetOffset(offset);
1529         row->GetCFAValue().IncOffset(-amount);
1530 
1531         UnwindPlan::RowSP new_row(new UnwindPlan::Row(*row));
1532         unwind_plan.InsertRow(new_row);
1533         unwind_plan_updated = true;
1534         continue;
1535       }
1536 
1537       if (ret_pattern_p()) {
1538         reinstate_unwind_state = true;
1539         continue;
1540       }
1541     } else if (cfa_reg == m_lldb_fp_regnum) {
1542       // CFA register is fp.
1543 
1544       // The only case we care about is epilogue:
1545       //     [0x5d] pop %rbp/%ebp
1546       //  => [0xc3] ret
1547       if (pop_rbp_pattern_p() || leave_pattern_p()) {
1548         m_cur_insn++;
1549         if (ret_pattern_p()) {
1550           row->SetOffset(offset);
1551           row->GetCFAValue().SetIsRegisterPlusOffset(
1552               first_row->GetCFAValue().GetRegisterNumber(), m_wordsize);
1553 
1554           UnwindPlan::RowSP new_row(new UnwindPlan::Row(*row));
1555           unwind_plan.InsertRow(new_row);
1556           unwind_plan_updated = true;
1557           reinstate_unwind_state = true;
1558           continue;
1559         }
1560       }
1561     } else {
1562       // CFA register is not sp or fp.
1563 
1564       // This must be hand-written assembly.
1565       // Just trust eh_frame and assume we have finished.
1566       break;
1567     }
1568   }
1569 
1570   unwind_plan.SetPlanValidAddressRange(func_range);
1571   if (unwind_plan_updated) {
1572     std::string unwind_plan_source(unwind_plan.GetSourceName().AsCString());
1573     unwind_plan_source += " plus augmentation from assembly parsing";
1574     unwind_plan.SetSourceName(unwind_plan_source.c_str());
1575     unwind_plan.SetSourcedFromCompiler(eLazyBoolNo);
1576     unwind_plan.SetUnwindPlanValidAtAllInstructions(eLazyBoolYes);
1577   }
1578   return true;
1579 }
1580 
1581 bool x86AssemblyInspectionEngine::FindFirstNonPrologueInstruction(
1582     uint8_t *data, size_t size, size_t &offset) {
1583   offset = 0;
1584 
1585   if (!m_register_map_initialized)
1586     return false;
1587 
1588   while (offset < size) {
1589     int regno;
1590     int insn_len;
1591     int scratch;
1592 
1593     m_cur_insn = data + offset;
1594     if (!instruction_length(m_cur_insn, insn_len, size - offset)
1595         || insn_len > kMaxInstructionByteSize
1596         || insn_len == 0) {
1597       // An error parsing the instruction, i.e. probably data/garbage - stop
1598       // scanning
1599       break;
1600     }
1601 
1602     if (push_rbp_pattern_p() || mov_rsp_rbp_pattern_p() ||
1603         sub_rsp_pattern_p(scratch) || push_reg_p(regno) ||
1604         mov_reg_to_local_stack_frame_p(regno, scratch) ||
1605         (lea_rsp_pattern_p(scratch) && offset == 0)) {
1606       offset += insn_len;
1607       continue;
1608     }
1609     //
1610     // Unknown non-prologue instruction - stop scanning
1611     break;
1612   }
1613 
1614   return true;
1615 }
1616