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