1 //===-- NativeRegisterContextLinux_x86_64.cpp ---------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #if defined(__i386__) || defined(__x86_64__)
11 
12 #include "NativeRegisterContextLinux_x86_64.h"
13 
14 #include "lldb/Core/DataBufferHeap.h"
15 #include "lldb/Core/Error.h"
16 #include "lldb/Core/Log.h"
17 #include "lldb/Core/RegisterValue.h"
18 #include "lldb/Host/HostInfo.h"
19 
20 #include "Plugins/Process/Utility/RegisterContextLinux_i386.h"
21 #include "Plugins/Process/Utility/RegisterContextLinux_x86_64.h"
22 
23 using namespace lldb_private;
24 using namespace lldb_private::process_linux;
25 
26 // ----------------------------------------------------------------------------
27 // Private namespace.
28 // ----------------------------------------------------------------------------
29 
30 namespace {
31 // x86 32-bit general purpose registers.
32 const uint32_t g_gpr_regnums_i386[] = {
33     lldb_eax_i386,      lldb_ebx_i386,    lldb_ecx_i386, lldb_edx_i386,
34     lldb_edi_i386,      lldb_esi_i386,    lldb_ebp_i386, lldb_esp_i386,
35     lldb_eip_i386,      lldb_eflags_i386, lldb_cs_i386,  lldb_fs_i386,
36     lldb_gs_i386,       lldb_ss_i386,     lldb_ds_i386,  lldb_es_i386,
37     lldb_ax_i386,       lldb_bx_i386,     lldb_cx_i386,  lldb_dx_i386,
38     lldb_di_i386,       lldb_si_i386,     lldb_bp_i386,  lldb_sp_i386,
39     lldb_ah_i386,       lldb_bh_i386,     lldb_ch_i386,  lldb_dh_i386,
40     lldb_al_i386,       lldb_bl_i386,     lldb_cl_i386,  lldb_dl_i386,
41     LLDB_INVALID_REGNUM // register sets need to end with this flag
42 };
43 static_assert((sizeof(g_gpr_regnums_i386) / sizeof(g_gpr_regnums_i386[0])) -
44                       1 ==
45                   k_num_gpr_registers_i386,
46               "g_gpr_regnums_i386 has wrong number of register infos");
47 
48 // x86 32-bit floating point registers.
49 const uint32_t g_fpu_regnums_i386[] = {
50     lldb_fctrl_i386,    lldb_fstat_i386,     lldb_ftag_i386,  lldb_fop_i386,
51     lldb_fiseg_i386,    lldb_fioff_i386,     lldb_foseg_i386, lldb_fooff_i386,
52     lldb_mxcsr_i386,    lldb_mxcsrmask_i386, lldb_st0_i386,   lldb_st1_i386,
53     lldb_st2_i386,      lldb_st3_i386,       lldb_st4_i386,   lldb_st5_i386,
54     lldb_st6_i386,      lldb_st7_i386,       lldb_mm0_i386,   lldb_mm1_i386,
55     lldb_mm2_i386,      lldb_mm3_i386,       lldb_mm4_i386,   lldb_mm5_i386,
56     lldb_mm6_i386,      lldb_mm7_i386,       lldb_xmm0_i386,  lldb_xmm1_i386,
57     lldb_xmm2_i386,     lldb_xmm3_i386,      lldb_xmm4_i386,  lldb_xmm5_i386,
58     lldb_xmm6_i386,     lldb_xmm7_i386,
59     LLDB_INVALID_REGNUM // register sets need to end with this flag
60 };
61 static_assert((sizeof(g_fpu_regnums_i386) / sizeof(g_fpu_regnums_i386[0])) -
62                       1 ==
63                   k_num_fpr_registers_i386,
64               "g_fpu_regnums_i386 has wrong number of register infos");
65 
66 // x86 32-bit AVX registers.
67 const uint32_t g_avx_regnums_i386[] = {
68     lldb_ymm0_i386,     lldb_ymm1_i386, lldb_ymm2_i386, lldb_ymm3_i386,
69     lldb_ymm4_i386,     lldb_ymm5_i386, lldb_ymm6_i386, lldb_ymm7_i386,
70     LLDB_INVALID_REGNUM // register sets need to end with this flag
71 };
72 static_assert((sizeof(g_avx_regnums_i386) / sizeof(g_avx_regnums_i386[0])) -
73                       1 ==
74                   k_num_avx_registers_i386,
75               " g_avx_regnums_i386 has wrong number of register infos");
76 
77 // x64 32-bit MPX registers.
78 static const uint32_t g_mpx_regnums_i386[] = {
79     lldb_bnd0_i386,     lldb_bnd1_i386, lldb_bnd2_i386, lldb_bnd3_i386,
80     lldb_bndcfgu_i386,  lldb_bndstatus_i386,
81     LLDB_INVALID_REGNUM // register sets need to end with this flag
82 };
83 static_assert((sizeof(g_mpx_regnums_i386) / sizeof(g_mpx_regnums_i386[0])) -
84                       1 ==
85                   k_num_mpx_registers_i386,
86               "g_mpx_regnums_x86_64 has wrong number of register infos");
87 
88 // x86 64-bit general purpose registers.
89 static const uint32_t g_gpr_regnums_x86_64[] = {
90     lldb_rax_x86_64,    lldb_rbx_x86_64,    lldb_rcx_x86_64, lldb_rdx_x86_64,
91     lldb_rdi_x86_64,    lldb_rsi_x86_64,    lldb_rbp_x86_64, lldb_rsp_x86_64,
92     lldb_r8_x86_64,     lldb_r9_x86_64,     lldb_r10_x86_64, lldb_r11_x86_64,
93     lldb_r12_x86_64,    lldb_r13_x86_64,    lldb_r14_x86_64, lldb_r15_x86_64,
94     lldb_rip_x86_64,    lldb_rflags_x86_64, lldb_cs_x86_64,  lldb_fs_x86_64,
95     lldb_gs_x86_64,     lldb_ss_x86_64,     lldb_ds_x86_64,  lldb_es_x86_64,
96     lldb_eax_x86_64,    lldb_ebx_x86_64,    lldb_ecx_x86_64, lldb_edx_x86_64,
97     lldb_edi_x86_64,    lldb_esi_x86_64,    lldb_ebp_x86_64, lldb_esp_x86_64,
98     lldb_r8d_x86_64,  // Low 32 bits or r8
99     lldb_r9d_x86_64,  // Low 32 bits or r9
100     lldb_r10d_x86_64, // Low 32 bits or r10
101     lldb_r11d_x86_64, // Low 32 bits or r11
102     lldb_r12d_x86_64, // Low 32 bits or r12
103     lldb_r13d_x86_64, // Low 32 bits or r13
104     lldb_r14d_x86_64, // Low 32 bits or r14
105     lldb_r15d_x86_64, // Low 32 bits or r15
106     lldb_ax_x86_64,     lldb_bx_x86_64,     lldb_cx_x86_64,  lldb_dx_x86_64,
107     lldb_di_x86_64,     lldb_si_x86_64,     lldb_bp_x86_64,  lldb_sp_x86_64,
108     lldb_r8w_x86_64,  // Low 16 bits or r8
109     lldb_r9w_x86_64,  // Low 16 bits or r9
110     lldb_r10w_x86_64, // Low 16 bits or r10
111     lldb_r11w_x86_64, // Low 16 bits or r11
112     lldb_r12w_x86_64, // Low 16 bits or r12
113     lldb_r13w_x86_64, // Low 16 bits or r13
114     lldb_r14w_x86_64, // Low 16 bits or r14
115     lldb_r15w_x86_64, // Low 16 bits or r15
116     lldb_ah_x86_64,     lldb_bh_x86_64,     lldb_ch_x86_64,  lldb_dh_x86_64,
117     lldb_al_x86_64,     lldb_bl_x86_64,     lldb_cl_x86_64,  lldb_dl_x86_64,
118     lldb_dil_x86_64,    lldb_sil_x86_64,    lldb_bpl_x86_64, lldb_spl_x86_64,
119     lldb_r8l_x86_64,    // Low 8 bits or r8
120     lldb_r9l_x86_64,    // Low 8 bits or r9
121     lldb_r10l_x86_64,   // Low 8 bits or r10
122     lldb_r11l_x86_64,   // Low 8 bits or r11
123     lldb_r12l_x86_64,   // Low 8 bits or r12
124     lldb_r13l_x86_64,   // Low 8 bits or r13
125     lldb_r14l_x86_64,   // Low 8 bits or r14
126     lldb_r15l_x86_64,   // Low 8 bits or r15
127     LLDB_INVALID_REGNUM // register sets need to end with this flag
128 };
129 static_assert((sizeof(g_gpr_regnums_x86_64) / sizeof(g_gpr_regnums_x86_64[0])) -
130                       1 ==
131                   k_num_gpr_registers_x86_64,
132               "g_gpr_regnums_x86_64 has wrong number of register infos");
133 
134 // x86 64-bit floating point registers.
135 static const uint32_t g_fpu_regnums_x86_64[] = {
136     lldb_fctrl_x86_64,     lldb_fstat_x86_64, lldb_ftag_x86_64,
137     lldb_fop_x86_64,       lldb_fiseg_x86_64, lldb_fioff_x86_64,
138     lldb_foseg_x86_64,     lldb_fooff_x86_64, lldb_mxcsr_x86_64,
139     lldb_mxcsrmask_x86_64, lldb_st0_x86_64,   lldb_st1_x86_64,
140     lldb_st2_x86_64,       lldb_st3_x86_64,   lldb_st4_x86_64,
141     lldb_st5_x86_64,       lldb_st6_x86_64,   lldb_st7_x86_64,
142     lldb_mm0_x86_64,       lldb_mm1_x86_64,   lldb_mm2_x86_64,
143     lldb_mm3_x86_64,       lldb_mm4_x86_64,   lldb_mm5_x86_64,
144     lldb_mm6_x86_64,       lldb_mm7_x86_64,   lldb_xmm0_x86_64,
145     lldb_xmm1_x86_64,      lldb_xmm2_x86_64,  lldb_xmm3_x86_64,
146     lldb_xmm4_x86_64,      lldb_xmm5_x86_64,  lldb_xmm6_x86_64,
147     lldb_xmm7_x86_64,      lldb_xmm8_x86_64,  lldb_xmm9_x86_64,
148     lldb_xmm10_x86_64,     lldb_xmm11_x86_64, lldb_xmm12_x86_64,
149     lldb_xmm13_x86_64,     lldb_xmm14_x86_64, lldb_xmm15_x86_64,
150     LLDB_INVALID_REGNUM // register sets need to end with this flag
151 };
152 static_assert((sizeof(g_fpu_regnums_x86_64) / sizeof(g_fpu_regnums_x86_64[0])) -
153                       1 ==
154                   k_num_fpr_registers_x86_64,
155               "g_fpu_regnums_x86_64 has wrong number of register infos");
156 
157 // x86 64-bit AVX registers.
158 static const uint32_t g_avx_regnums_x86_64[] = {
159     lldb_ymm0_x86_64,   lldb_ymm1_x86_64,  lldb_ymm2_x86_64,  lldb_ymm3_x86_64,
160     lldb_ymm4_x86_64,   lldb_ymm5_x86_64,  lldb_ymm6_x86_64,  lldb_ymm7_x86_64,
161     lldb_ymm8_x86_64,   lldb_ymm9_x86_64,  lldb_ymm10_x86_64, lldb_ymm11_x86_64,
162     lldb_ymm12_x86_64,  lldb_ymm13_x86_64, lldb_ymm14_x86_64, lldb_ymm15_x86_64,
163     LLDB_INVALID_REGNUM // register sets need to end with this flag
164 };
165 static_assert((sizeof(g_avx_regnums_x86_64) / sizeof(g_avx_regnums_x86_64[0])) -
166                       1 ==
167                   k_num_avx_registers_x86_64,
168               "g_avx_regnums_x86_64 has wrong number of register infos");
169 
170 // x86 64-bit MPX registers.
171 static const uint32_t g_mpx_regnums_x86_64[] = {
172     lldb_bnd0_x86_64,    lldb_bnd1_x86_64,    lldb_bnd2_x86_64,
173     lldb_bnd3_x86_64,    lldb_bndcfgu_x86_64, lldb_bndstatus_x86_64,
174     LLDB_INVALID_REGNUM // register sets need to end with this flag
175 };
176 static_assert((sizeof(g_mpx_regnums_x86_64) / sizeof(g_mpx_regnums_x86_64[0])) -
177                       1 ==
178                   k_num_mpx_registers_x86_64,
179               "g_mpx_regnums_x86_64 has wrong number of register infos");
180 
181 // Number of register sets provided by this context.
182 enum { k_num_extended_register_sets = 2, k_num_register_sets = 4 };
183 
184 // Register sets for x86 32-bit.
185 static const RegisterSet g_reg_sets_i386[k_num_register_sets] = {
186     {"General Purpose Registers", "gpr", k_num_gpr_registers_i386,
187      g_gpr_regnums_i386},
188     {"Floating Point Registers", "fpu", k_num_fpr_registers_i386,
189      g_fpu_regnums_i386},
190     {"Advanced Vector Extensions", "avx", k_num_avx_registers_i386,
191      g_avx_regnums_i386},
192     { "Memory Protection Extensions", "mpx", k_num_mpx_registers_i386,
193      g_mpx_regnums_i386}};
194 
195 // Register sets for x86 64-bit.
196 static const RegisterSet g_reg_sets_x86_64[k_num_register_sets] = {
197     {"General Purpose Registers", "gpr", k_num_gpr_registers_x86_64,
198      g_gpr_regnums_x86_64},
199     {"Floating Point Registers", "fpu", k_num_fpr_registers_x86_64,
200      g_fpu_regnums_x86_64},
201     {"Advanced Vector Extensions", "avx", k_num_avx_registers_x86_64,
202      g_avx_regnums_x86_64},
203     { "Memory Protection Extensions", "mpx", k_num_mpx_registers_x86_64,
204      g_mpx_regnums_x86_64}};
205 }
206 
207 #define REG_CONTEXT_SIZE (GetRegisterInfoInterface().GetGPRSize() + sizeof(FPR))
208 
209 // ----------------------------------------------------------------------------
210 // Required ptrace defines.
211 // ----------------------------------------------------------------------------
212 
213 // Support ptrace extensions even when compiled without required kernel support
214 #ifndef NT_X86_XSTATE
215 #define NT_X86_XSTATE 0x202
216 #endif
217 #ifndef NT_PRXFPREG
218 #define NT_PRXFPREG 0x46e62b7f
219 #endif
220 
221 NativeRegisterContextLinux *
222 NativeRegisterContextLinux::CreateHostNativeRegisterContextLinux(
223     const ArchSpec &target_arch, NativeThreadProtocol &native_thread,
224     uint32_t concrete_frame_idx) {
225   return new NativeRegisterContextLinux_x86_64(target_arch, native_thread,
226                                                concrete_frame_idx);
227 }
228 
229 // ----------------------------------------------------------------------------
230 // NativeRegisterContextLinux_x86_64 members.
231 // ----------------------------------------------------------------------------
232 
233 static RegisterInfoInterface *
234 CreateRegisterInfoInterface(const ArchSpec &target_arch) {
235   if (HostInfo::GetArchitecture().GetAddressByteSize() == 4) {
236     // 32-bit hosts run with a RegisterContextLinux_i386 context.
237     return new RegisterContextLinux_i386(target_arch);
238   } else {
239     assert((HostInfo::GetArchitecture().GetAddressByteSize() == 8) &&
240            "Register setting path assumes this is a 64-bit host");
241     // X86_64 hosts know how to work with 64-bit and 32-bit EXEs using the
242     // x86_64 register context.
243     return new RegisterContextLinux_x86_64(target_arch);
244   }
245 }
246 
247 NativeRegisterContextLinux_x86_64::NativeRegisterContextLinux_x86_64(
248     const ArchSpec &target_arch, NativeThreadProtocol &native_thread,
249     uint32_t concrete_frame_idx)
250     : NativeRegisterContextLinux(native_thread, concrete_frame_idx,
251                                  CreateRegisterInfoInterface(target_arch)),
252       m_fpr_type(eFPRTypeNotValid), m_fpr(), m_iovec(), m_ymm_set(),
253       m_mpx_set(), m_reg_info(), m_gpr_x86_64() {
254   // Set up data about ranges of valid registers.
255   switch (target_arch.GetMachine()) {
256   case llvm::Triple::x86:
257     m_reg_info.num_registers = k_num_registers_i386;
258     m_reg_info.num_gpr_registers = k_num_gpr_registers_i386;
259     m_reg_info.num_fpr_registers = k_num_fpr_registers_i386;
260     m_reg_info.num_avx_registers = k_num_avx_registers_i386;
261     m_reg_info.num_mpx_registers = k_num_mpx_registers_i386;
262     m_reg_info.last_gpr = k_last_gpr_i386;
263     m_reg_info.first_fpr = k_first_fpr_i386;
264     m_reg_info.last_fpr = k_last_fpr_i386;
265     m_reg_info.first_st = lldb_st0_i386;
266     m_reg_info.last_st = lldb_st7_i386;
267     m_reg_info.first_mm = lldb_mm0_i386;
268     m_reg_info.last_mm = lldb_mm7_i386;
269     m_reg_info.first_xmm = lldb_xmm0_i386;
270     m_reg_info.last_xmm = lldb_xmm7_i386;
271     m_reg_info.first_ymm = lldb_ymm0_i386;
272     m_reg_info.last_ymm = lldb_ymm7_i386;
273     m_reg_info.first_mpxr = lldb_bnd0_i386;
274     m_reg_info.last_mpxr = lldb_bnd3_i386;
275     m_reg_info.first_mpxc = lldb_bndcfgu_i386;
276     m_reg_info.last_mpxc = lldb_bndstatus_i386;
277     m_reg_info.first_dr = lldb_dr0_i386;
278     m_reg_info.gpr_flags = lldb_eflags_i386;
279     break;
280   case llvm::Triple::x86_64:
281     m_reg_info.num_registers = k_num_registers_x86_64;
282     m_reg_info.num_gpr_registers = k_num_gpr_registers_x86_64;
283     m_reg_info.num_fpr_registers = k_num_fpr_registers_x86_64;
284     m_reg_info.num_avx_registers = k_num_avx_registers_x86_64;
285     m_reg_info.num_mpx_registers = k_num_mpx_registers_x86_64;
286     m_reg_info.last_gpr = k_last_gpr_x86_64;
287     m_reg_info.first_fpr = k_first_fpr_x86_64;
288     m_reg_info.last_fpr = k_last_fpr_x86_64;
289     m_reg_info.first_st = lldb_st0_x86_64;
290     m_reg_info.last_st = lldb_st7_x86_64;
291     m_reg_info.first_mm = lldb_mm0_x86_64;
292     m_reg_info.last_mm = lldb_mm7_x86_64;
293     m_reg_info.first_xmm = lldb_xmm0_x86_64;
294     m_reg_info.last_xmm = lldb_xmm15_x86_64;
295     m_reg_info.first_ymm = lldb_ymm0_x86_64;
296     m_reg_info.last_ymm = lldb_ymm15_x86_64;
297     m_reg_info.first_mpxr = lldb_bnd0_x86_64;
298     m_reg_info.last_mpxr = lldb_bnd3_x86_64;
299     m_reg_info.first_mpxc = lldb_bndcfgu_x86_64;
300     m_reg_info.last_mpxc = lldb_bndstatus_x86_64;
301     m_reg_info.first_dr = lldb_dr0_x86_64;
302     m_reg_info.gpr_flags = lldb_rflags_x86_64;
303     break;
304   default:
305     assert(false && "Unhandled target architecture.");
306     break;
307   }
308 
309   // Initialize m_iovec to point to the buffer and buffer size
310   // using the conventions of Berkeley style UIO structures, as required
311   // by PTRACE extensions.
312   m_iovec.iov_base = &m_fpr.xstate.xsave;
313   m_iovec.iov_len = sizeof(m_fpr.xstate.xsave);
314 
315   // Clear out the FPR state.
316   ::memset(&m_fpr, 0, sizeof(FPR));
317 
318   // Store byte offset of fctrl (i.e. first register of FPR)
319   const RegisterInfo *reg_info_fctrl = GetRegisterInfoByName("fctrl");
320   m_fctrl_offset_in_userarea = reg_info_fctrl->byte_offset;
321 }
322 
323 // CONSIDER after local and llgs debugging are merged, register set support can
324 // be moved into a base x86-64 class with IsRegisterSetAvailable made virtual.
325 uint32_t NativeRegisterContextLinux_x86_64::GetRegisterSetCount() const {
326   uint32_t sets = 0;
327   for (uint32_t set_index = 0; set_index < k_num_register_sets; ++set_index) {
328     if (IsRegisterSetAvailable(set_index))
329       ++sets;
330   }
331 
332   return sets;
333 }
334 
335 uint32_t NativeRegisterContextLinux_x86_64::GetUserRegisterCount() const {
336   uint32_t count = 0;
337   for (uint32_t set_index = 0; set_index < k_num_register_sets; ++set_index) {
338     const RegisterSet *set = GetRegisterSet(set_index);
339     if (set)
340       count += set->num_registers;
341   }
342   return count;
343 }
344 
345 const RegisterSet *
346 NativeRegisterContextLinux_x86_64::GetRegisterSet(uint32_t set_index) const {
347   if (!IsRegisterSetAvailable(set_index))
348     return nullptr;
349 
350   switch (GetRegisterInfoInterface().GetTargetArchitecture().GetMachine()) {
351   case llvm::Triple::x86:
352     return &g_reg_sets_i386[set_index];
353   case llvm::Triple::x86_64:
354     return &g_reg_sets_x86_64[set_index];
355   default:
356     assert(false && "Unhandled target architecture.");
357     return nullptr;
358   }
359 
360   return nullptr;
361 }
362 
363 Error NativeRegisterContextLinux_x86_64::ReadRegister(
364     const RegisterInfo *reg_info, RegisterValue &reg_value) {
365   Error error;
366 
367   if (!reg_info) {
368     error.SetErrorString("reg_info NULL");
369     return error;
370   }
371 
372   const uint32_t reg = reg_info->kinds[lldb::eRegisterKindLLDB];
373   if (reg == LLDB_INVALID_REGNUM) {
374     // This is likely an internal register for lldb use only and should not be
375     // directly queried.
376     error.SetErrorStringWithFormat("register \"%s\" is an internal-only lldb "
377                                    "register, cannot read directly",
378                                    reg_info->name);
379     return error;
380   }
381 
382   if (IsFPR(reg, GetFPRType())) {
383     error = ReadFPR();
384     if (error.Fail())
385       return error;
386   } else {
387     uint32_t full_reg = reg;
388     bool is_subreg = reg_info->invalidate_regs &&
389                      (reg_info->invalidate_regs[0] != LLDB_INVALID_REGNUM);
390 
391     if (is_subreg) {
392       // Read the full aligned 64-bit register.
393       full_reg = reg_info->invalidate_regs[0];
394     }
395 
396     error = ReadRegisterRaw(full_reg, reg_value);
397 
398     if (error.Success()) {
399       // If our read was not aligned (for ah,bh,ch,dh), shift our returned value
400       // one byte to the right.
401       if (is_subreg && (reg_info->byte_offset & 0x1))
402         reg_value.SetUInt64(reg_value.GetAsUInt64() >> 8);
403 
404       // If our return byte size was greater than the return value reg size,
405       // then
406       // use the type specified by reg_info rather than the uint64_t default
407       if (reg_value.GetByteSize() > reg_info->byte_size)
408         reg_value.SetType(reg_info);
409     }
410     return error;
411   }
412 
413   if (reg_info->encoding == lldb::eEncodingVector) {
414     lldb::ByteOrder byte_order = GetByteOrder();
415 
416     if (byte_order != lldb::eByteOrderInvalid) {
417       if (reg >= m_reg_info.first_st && reg <= m_reg_info.last_st)
418         reg_value.SetBytes(
419             m_fpr.xstate.fxsave.stmm[reg - m_reg_info.first_st].bytes,
420             reg_info->byte_size, byte_order);
421       if (reg >= m_reg_info.first_mm && reg <= m_reg_info.last_mm)
422         reg_value.SetBytes(
423             m_fpr.xstate.fxsave.stmm[reg - m_reg_info.first_mm].bytes,
424             reg_info->byte_size, byte_order);
425       if (reg >= m_reg_info.first_xmm && reg <= m_reg_info.last_xmm)
426         reg_value.SetBytes(
427             m_fpr.xstate.fxsave.xmm[reg - m_reg_info.first_xmm].bytes,
428             reg_info->byte_size, byte_order);
429       if (reg >= m_reg_info.first_ymm && reg <= m_reg_info.last_ymm) {
430         // Concatenate ymm using the register halves in xmm.bytes and ymmh.bytes
431         if (GetFPRType() == eFPRTypeXSAVE && CopyXSTATEtoYMM(reg, byte_order))
432           reg_value.SetBytes(m_ymm_set.ymm[reg - m_reg_info.first_ymm].bytes,
433                              reg_info->byte_size, byte_order);
434         else {
435           error.SetErrorString("failed to copy ymm register value");
436           return error;
437         }
438       }
439       if (reg >= m_reg_info.first_mpxr && reg <= m_reg_info.last_mpxr) {
440         if (GetFPRType() == eFPRTypeXSAVE && CopyXSTATEtoMPX(reg))
441           reg_value.SetBytes(m_mpx_set.mpxr[reg - m_reg_info.first_mpxr].bytes,
442                              reg_info->byte_size, byte_order);
443         else {
444           error.SetErrorString("failed to copy mpx register value");
445           return error;
446         }
447       }
448       if (reg >= m_reg_info.first_mpxc && reg <= m_reg_info.last_mpxc) {
449         if (GetFPRType() == eFPRTypeXSAVE && CopyXSTATEtoMPX(reg))
450           reg_value.SetBytes(m_mpx_set.mpxc[reg - m_reg_info.first_mpxc].bytes,
451                              reg_info->byte_size, byte_order);
452         else {
453           error.SetErrorString("failed to copy mpx register value");
454           return error;
455         }
456       }
457 
458       if (reg_value.GetType() != RegisterValue::eTypeBytes)
459         error.SetErrorString(
460             "write failed - type was expected to be RegisterValue::eTypeBytes");
461 
462       return error;
463     }
464 
465     error.SetErrorString("byte order is invalid");
466     return error;
467   }
468 
469   // Get pointer to m_fpr.xstate.fxsave variable and set the data from it.
470 
471   // Byte offsets of all registers are calculated wrt 'UserArea' structure.
472   // However, ReadFPR() reads fpu registers {using ptrace(PTRACE_GETFPREGS,..)}
473   // and stores them in 'm_fpr' (of type FPR structure). To extract values of
474   // fpu
475   // registers, m_fpr should be read at byte offsets calculated wrt to FPR
476   // structure.
477 
478   // Since, FPR structure is also one of the member of UserArea structure.
479   // byte_offset(fpu wrt FPR) = byte_offset(fpu wrt UserArea) -
480   // byte_offset(fctrl wrt UserArea)
481   assert((reg_info->byte_offset - m_fctrl_offset_in_userarea) < sizeof(m_fpr));
482   uint8_t *src =
483       (uint8_t *)&m_fpr + reg_info->byte_offset - m_fctrl_offset_in_userarea;
484   switch (reg_info->byte_size) {
485   case 1:
486     reg_value.SetUInt8(*(uint8_t *)src);
487     break;
488   case 2:
489     reg_value.SetUInt16(*(uint16_t *)src);
490     break;
491   case 4:
492     reg_value.SetUInt32(*(uint32_t *)src);
493     break;
494   case 8:
495     reg_value.SetUInt64(*(uint64_t *)src);
496     break;
497   default:
498     assert(false && "Unhandled data size.");
499     error.SetErrorStringWithFormat("unhandled byte size: %" PRIu32,
500                                    reg_info->byte_size);
501     break;
502   }
503 
504   return error;
505 }
506 
507 Error NativeRegisterContextLinux_x86_64::WriteRegister(
508     const RegisterInfo *reg_info, const RegisterValue &reg_value) {
509   assert(reg_info && "reg_info is null");
510 
511   const uint32_t reg_index = reg_info->kinds[lldb::eRegisterKindLLDB];
512   if (reg_index == LLDB_INVALID_REGNUM)
513     return Error("no lldb regnum for %s", reg_info && reg_info->name
514                                               ? reg_info->name
515                                               : "<unknown register>");
516 
517   if (IsGPR(reg_index))
518     return WriteRegisterRaw(reg_index, reg_value);
519 
520   if (IsFPR(reg_index, GetFPRType())) {
521     if (reg_info->encoding == lldb::eEncodingVector) {
522       if (reg_index >= m_reg_info.first_st && reg_index <= m_reg_info.last_st)
523         ::memcpy(
524             m_fpr.xstate.fxsave.stmm[reg_index - m_reg_info.first_st].bytes,
525             reg_value.GetBytes(), reg_value.GetByteSize());
526 
527       if (reg_index >= m_reg_info.first_mm && reg_index <= m_reg_info.last_mm)
528         ::memcpy(
529             m_fpr.xstate.fxsave.stmm[reg_index - m_reg_info.first_mm].bytes,
530             reg_value.GetBytes(), reg_value.GetByteSize());
531 
532       if (reg_index >= m_reg_info.first_xmm && reg_index <= m_reg_info.last_xmm)
533         ::memcpy(
534             m_fpr.xstate.fxsave.xmm[reg_index - m_reg_info.first_xmm].bytes,
535             reg_value.GetBytes(), reg_value.GetByteSize());
536 
537       if (reg_index >= m_reg_info.first_ymm &&
538           reg_index <= m_reg_info.last_ymm) {
539         if (GetFPRType() != eFPRTypeXSAVE)
540           return Error("target processor does not support AVX");
541 
542         // Store ymm register content, and split into the register halves in
543         // xmm.bytes and ymmh.bytes
544         ::memcpy(m_ymm_set.ymm[reg_index - m_reg_info.first_ymm].bytes,
545                  reg_value.GetBytes(), reg_value.GetByteSize());
546         if (!CopyYMMtoXSTATE(reg_index, GetByteOrder()))
547           return Error("CopyYMMtoXSTATE() failed");
548       }
549 
550       if (reg_index >= m_reg_info.first_mpxr &&
551           reg_index <= m_reg_info.last_mpxr) {
552         if (GetFPRType() != eFPRTypeXSAVE)
553           return Error("target processor does not support MPX");
554 
555         ::memcpy(m_mpx_set.mpxr[reg_index - m_reg_info.first_mpxr].bytes,
556                  reg_value.GetBytes(), reg_value.GetByteSize());
557         if (!CopyMPXtoXSTATE(reg_index))
558           return Error("CopyMPXtoXSTATE() failed");
559       }
560 
561       if (reg_index >= m_reg_info.first_mpxc &&
562           reg_index <= m_reg_info.last_mpxc) {
563         if (GetFPRType() != eFPRTypeXSAVE)
564           return Error("target processor does not support MPX");
565 
566         ::memcpy(m_mpx_set.mpxc[reg_index - m_reg_info.first_mpxc].bytes,
567                  reg_value.GetBytes(), reg_value.GetByteSize());
568         if (!CopyMPXtoXSTATE(reg_index))
569           return Error("CopyMPXtoXSTATE() failed");
570       }
571     } else {
572       // Get pointer to m_fpr.xstate.fxsave variable and set the data to it.
573 
574       // Byte offsets of all registers are calculated wrt 'UserArea' structure.
575       // However, WriteFPR() takes m_fpr (of type FPR structure) and writes only
576       // fpu
577       // registers using ptrace(PTRACE_SETFPREGS,..) API. Hence fpu registers
578       // should
579       // be written in m_fpr at byte offsets calculated wrt FPR structure.
580 
581       // Since, FPR structure is also one of the member of UserArea structure.
582       // byte_offset(fpu wrt FPR) = byte_offset(fpu wrt UserArea) -
583       // byte_offset(fctrl wrt UserArea)
584       assert((reg_info->byte_offset - m_fctrl_offset_in_userarea) <
585              sizeof(m_fpr));
586       uint8_t *dst = (uint8_t *)&m_fpr + reg_info->byte_offset -
587                      m_fctrl_offset_in_userarea;
588       switch (reg_info->byte_size) {
589       case 1:
590         *(uint8_t *)dst = reg_value.GetAsUInt8();
591         break;
592       case 2:
593         *(uint16_t *)dst = reg_value.GetAsUInt16();
594         break;
595       case 4:
596         *(uint32_t *)dst = reg_value.GetAsUInt32();
597         break;
598       case 8:
599         *(uint64_t *)dst = reg_value.GetAsUInt64();
600         break;
601       default:
602         assert(false && "Unhandled data size.");
603         return Error("unhandled register data size %" PRIu32,
604                      reg_info->byte_size);
605       }
606     }
607 
608     Error error = WriteFPR();
609     if (error.Fail())
610       return error;
611 
612     if (IsAVX(reg_index)) {
613       if (!CopyYMMtoXSTATE(reg_index, GetByteOrder()))
614         return Error("CopyYMMtoXSTATE() failed");
615     }
616 
617     if (IsMPX(reg_index)) {
618       if (!CopyMPXtoXSTATE(reg_index))
619         return Error("CopyMPXtoXSTATE() failed");
620     }
621     return Error();
622   }
623   return Error("failed - register wasn't recognized to be a GPR or an FPR, "
624                "write strategy unknown");
625 }
626 
627 Error NativeRegisterContextLinux_x86_64::ReadAllRegisterValues(
628     lldb::DataBufferSP &data_sp) {
629   Error error;
630 
631   data_sp.reset(new DataBufferHeap(REG_CONTEXT_SIZE, 0));
632   if (!data_sp) {
633     error.SetErrorStringWithFormat(
634         "failed to allocate DataBufferHeap instance of size %" PRIu64,
635         REG_CONTEXT_SIZE);
636     return error;
637   }
638 
639   error = ReadGPR();
640   if (error.Fail())
641     return error;
642 
643   error = ReadFPR();
644   if (error.Fail())
645     return error;
646 
647   uint8_t *dst = data_sp->GetBytes();
648   if (dst == nullptr) {
649     error.SetErrorStringWithFormat("DataBufferHeap instance of size %" PRIu64
650                                    " returned a null pointer",
651                                    REG_CONTEXT_SIZE);
652     return error;
653   }
654 
655   ::memcpy(dst, &m_gpr_x86_64, GetRegisterInfoInterface().GetGPRSize());
656   dst += GetRegisterInfoInterface().GetGPRSize();
657   if (GetFPRType() == eFPRTypeFXSAVE)
658     ::memcpy(dst, &m_fpr.xstate.fxsave, sizeof(m_fpr.xstate.fxsave));
659   else if (GetFPRType() == eFPRTypeXSAVE) {
660     lldb::ByteOrder byte_order = GetByteOrder();
661 
662     // Assemble the YMM register content from the register halves.
663     for (uint32_t reg = m_reg_info.first_ymm; reg <= m_reg_info.last_ymm;
664          ++reg) {
665       if (!CopyXSTATEtoYMM(reg, byte_order)) {
666         error.SetErrorStringWithFormat("NativeRegisterContextLinux_x86_64::%s "
667                                        "CopyXSTATEtoYMM() failed for reg num "
668                                        "%" PRIu32,
669                                        __FUNCTION__, reg);
670         return error;
671       }
672     }
673 
674     for (uint32_t reg = m_reg_info.first_mpxr; reg <= m_reg_info.last_mpxc;
675          ++reg) {
676       if (!CopyXSTATEtoMPX(reg)) {
677         error.SetErrorStringWithFormat("NativeRegisterContextLinux_x86_64::%s "
678                                        "CopyXSTATEtoMPX() failed for reg num "
679                                        "%" PRIu32,
680                                        __FUNCTION__, reg);
681         return error;
682       }
683     }
684     // Copy the extended register state including the assembled ymm registers.
685     ::memcpy(dst, &m_fpr, sizeof(m_fpr));
686   } else {
687     assert(false && "how do we save the floating point registers?");
688     error.SetErrorString("unsure how to save the floating point registers");
689   }
690   /** The following code is specific to Linux x86 based architectures,
691    *  where the register orig_eax (32 bit)/orig_rax (64 bit) is set to
692    *  -1 to solve the bug 23659, such a setting prevents the automatic
693    *  decrement of the instruction pointer which was causing the SIGILL
694    *  exception.
695    * **/
696 
697   RegisterValue value((uint64_t)-1);
698   const RegisterInfo *reg_info =
699       GetRegisterInfoInterface().GetDynamicRegisterInfo("orig_eax");
700   if (reg_info == nullptr)
701     reg_info = GetRegisterInfoInterface().GetDynamicRegisterInfo("orig_rax");
702 
703   if (reg_info != nullptr)
704     return DoWriteRegisterValue(reg_info->byte_offset, reg_info->name, value);
705 
706   return error;
707 }
708 
709 Error NativeRegisterContextLinux_x86_64::WriteAllRegisterValues(
710     const lldb::DataBufferSP &data_sp) {
711   Error error;
712 
713   if (!data_sp) {
714     error.SetErrorStringWithFormat(
715         "NativeRegisterContextLinux_x86_64::%s invalid data_sp provided",
716         __FUNCTION__);
717     return error;
718   }
719 
720   if (data_sp->GetByteSize() != REG_CONTEXT_SIZE) {
721     error.SetErrorStringWithFormat(
722         "NativeRegisterContextLinux_x86_64::%s data_sp contained mismatched "
723         "data size, expected %" PRIu64 ", actual %" PRIu64,
724         __FUNCTION__, REG_CONTEXT_SIZE, data_sp->GetByteSize());
725     return error;
726   }
727 
728   uint8_t *src = data_sp->GetBytes();
729   if (src == nullptr) {
730     error.SetErrorStringWithFormat("NativeRegisterContextLinux_x86_64::%s "
731                                    "DataBuffer::GetBytes() returned a null "
732                                    "pointer",
733                                    __FUNCTION__);
734     return error;
735   }
736   ::memcpy(&m_gpr_x86_64, src, GetRegisterInfoInterface().GetGPRSize());
737 
738   error = WriteGPR();
739   if (error.Fail())
740     return error;
741 
742   src += GetRegisterInfoInterface().GetGPRSize();
743   if (GetFPRType() == eFPRTypeFXSAVE)
744     ::memcpy(&m_fpr.xstate.fxsave, src, sizeof(m_fpr.xstate.fxsave));
745   else if (GetFPRType() == eFPRTypeXSAVE)
746     ::memcpy(&m_fpr.xstate.xsave, src, sizeof(m_fpr.xstate.xsave));
747 
748   error = WriteFPR();
749   if (error.Fail())
750     return error;
751 
752   if (GetFPRType() == eFPRTypeXSAVE) {
753     lldb::ByteOrder byte_order = GetByteOrder();
754 
755     // Parse the YMM register content from the register halves.
756     for (uint32_t reg = m_reg_info.first_ymm; reg <= m_reg_info.last_ymm;
757          ++reg) {
758       if (!CopyYMMtoXSTATE(reg, byte_order)) {
759         error.SetErrorStringWithFormat("NativeRegisterContextLinux_x86_64::%s "
760                                        "CopyYMMtoXSTATE() failed for reg num "
761                                        "%" PRIu32,
762                                        __FUNCTION__, reg);
763         return error;
764       }
765     }
766 
767     for (uint32_t reg = m_reg_info.first_mpxr; reg <= m_reg_info.last_mpxc;
768          ++reg) {
769       if (!CopyMPXtoXSTATE(reg)) {
770         error.SetErrorStringWithFormat("NativeRegisterContextLinux_x86_64::%s "
771                                          "CopyMPXtoXSTATE() failed for reg num "
772                                          "%" PRIu32,
773                                          __FUNCTION__, reg);
774         return error;
775       }
776     }
777   }
778 
779   return error;
780 }
781 
782 bool NativeRegisterContextLinux_x86_64::IsRegisterSetAvailable(
783     uint32_t set_index) const {
784   // Note: Extended register sets are assumed to be at the end of g_reg_sets.
785   uint32_t num_sets = k_num_register_sets - k_num_extended_register_sets;
786 
787   if (GetFPRType() == eFPRTypeXSAVE) {
788     // AVX is the first extended register set.
789     num_sets += 2;
790   }
791   return (set_index < num_sets);
792 }
793 
794 bool NativeRegisterContextLinux_x86_64::IsGPR(uint32_t reg_index) const {
795   // GPRs come first.
796   return reg_index <= m_reg_info.last_gpr;
797 }
798 
799 NativeRegisterContextLinux_x86_64::FPRType
800 NativeRegisterContextLinux_x86_64::GetFPRType() const {
801   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
802   if (m_fpr_type == eFPRTypeNotValid) {
803     // TODO: Use assembly to call cpuid on the inferior and query ebx or ecx.
804 
805     // Try and see if AVX register retrieval works.
806     m_fpr_type = eFPRTypeXSAVE;
807     if (const_cast<NativeRegisterContextLinux_x86_64 *>(this)
808             ->ReadFPR()
809             .Fail()) {
810       // Fall back to general floating point with no AVX support.
811       m_fpr_type = eFPRTypeFXSAVE;
812 
813       // Check if FXSAVE area can be read.
814       if (const_cast<NativeRegisterContextLinux_x86_64 *>(this)
815               ->ReadFPR()
816               .Fail()) {
817         if (log)
818           log->Printf("NativeRegisterContextLinux_x86_64::%s ptrace APIs "
819                       "failed to read XSAVE/FXSAVE area",
820                       __FUNCTION__);
821       }
822     }
823   }
824   return m_fpr_type;
825 }
826 
827 bool NativeRegisterContextLinux_x86_64::IsFPR(uint32_t reg_index) const {
828   return (m_reg_info.first_fpr <= reg_index &&
829           reg_index <= m_reg_info.last_fpr);
830 }
831 
832 bool NativeRegisterContextLinux_x86_64::IsFPR(uint32_t reg_index,
833                                               FPRType fpr_type) const {
834   bool generic_fpr = IsFPR(reg_index);
835 
836   if (fpr_type == eFPRTypeXSAVE)
837     return generic_fpr || IsAVX(reg_index) || IsMPX(reg_index);
838   return generic_fpr;
839 }
840 
841 Error NativeRegisterContextLinux_x86_64::WriteFPR() {
842   const FPRType fpr_type = GetFPRType();
843   const lldb_private::ArchSpec &target_arch =
844       GetRegisterInfoInterface().GetTargetArchitecture();
845   switch (fpr_type) {
846   case FPRType::eFPRTypeFXSAVE:
847     // For 32-bit inferiors on x86_32/x86_64 architectures,
848     // FXSAVE area can be written using PTRACE_SETREGSET ptrace api
849     // For 64-bit inferiors on x86_64 architectures,
850     // FXSAVE area can be written using PTRACE_SETFPREGS ptrace api
851     switch (target_arch.GetMachine()) {
852     case llvm::Triple::x86:
853       return WriteRegisterSet(&m_iovec, sizeof(m_fpr.xstate.xsave),
854                               NT_PRXFPREG);
855     case llvm::Triple::x86_64:
856       return NativeRegisterContextLinux::WriteFPR();
857     default:
858       assert(false && "Unhandled target architecture.");
859       break;
860     }
861   case FPRType::eFPRTypeXSAVE:
862     return WriteRegisterSet(&m_iovec, sizeof(m_fpr.xstate.xsave),
863                             NT_X86_XSTATE);
864   default:
865     return Error("Unrecognized FPR type");
866   }
867 }
868 
869 bool NativeRegisterContextLinux_x86_64::IsAVX(uint32_t reg_index) const {
870   return (m_reg_info.first_ymm <= reg_index &&
871           reg_index <= m_reg_info.last_ymm);
872 }
873 
874 bool NativeRegisterContextLinux_x86_64::CopyXSTATEtoYMM(
875     uint32_t reg_index, lldb::ByteOrder byte_order) {
876   if (!IsAVX(reg_index))
877     return false;
878 
879   if (byte_order == lldb::eByteOrderLittle) {
880     ::memcpy(m_ymm_set.ymm[reg_index - m_reg_info.first_ymm].bytes,
881              m_fpr.xstate.fxsave.xmm[reg_index - m_reg_info.first_ymm].bytes,
882              sizeof(XMMReg));
883     ::memcpy(m_ymm_set.ymm[reg_index - m_reg_info.first_ymm].bytes +
884                  sizeof(XMMReg),
885              m_fpr.xstate.xsave.ymmh[reg_index - m_reg_info.first_ymm].bytes,
886              sizeof(YMMHReg));
887     return true;
888   }
889 
890   if (byte_order == lldb::eByteOrderBig) {
891     ::memcpy(m_ymm_set.ymm[reg_index - m_reg_info.first_ymm].bytes +
892                  sizeof(XMMReg),
893              m_fpr.xstate.fxsave.xmm[reg_index - m_reg_info.first_ymm].bytes,
894              sizeof(XMMReg));
895     ::memcpy(m_ymm_set.ymm[reg_index - m_reg_info.first_ymm].bytes,
896              m_fpr.xstate.xsave.ymmh[reg_index - m_reg_info.first_ymm].bytes,
897              sizeof(YMMHReg));
898     return true;
899   }
900   return false; // unsupported or invalid byte order
901 }
902 
903 bool NativeRegisterContextLinux_x86_64::CopyYMMtoXSTATE(
904     uint32_t reg, lldb::ByteOrder byte_order) {
905   if (!IsAVX(reg))
906     return false;
907 
908   if (byte_order == lldb::eByteOrderLittle) {
909     ::memcpy(m_fpr.xstate.fxsave.xmm[reg - m_reg_info.first_ymm].bytes,
910              m_ymm_set.ymm[reg - m_reg_info.first_ymm].bytes, sizeof(XMMReg));
911     ::memcpy(m_fpr.xstate.xsave.ymmh[reg - m_reg_info.first_ymm].bytes,
912              m_ymm_set.ymm[reg - m_reg_info.first_ymm].bytes + sizeof(XMMReg),
913              sizeof(YMMHReg));
914     return true;
915   }
916 
917   if (byte_order == lldb::eByteOrderBig) {
918     ::memcpy(m_fpr.xstate.fxsave.xmm[reg - m_reg_info.first_ymm].bytes,
919              m_ymm_set.ymm[reg - m_reg_info.first_ymm].bytes + sizeof(XMMReg),
920              sizeof(XMMReg));
921     ::memcpy(m_fpr.xstate.xsave.ymmh[reg - m_reg_info.first_ymm].bytes,
922              m_ymm_set.ymm[reg - m_reg_info.first_ymm].bytes, sizeof(YMMHReg));
923     return true;
924   }
925   return false; // unsupported or invalid byte order
926 }
927 
928 void *NativeRegisterContextLinux_x86_64::GetFPRBuffer() {
929   const FPRType fpr_type = GetFPRType();
930   switch (fpr_type) {
931   case FPRType::eFPRTypeFXSAVE:
932     return &m_fpr.xstate.fxsave;
933   case FPRType::eFPRTypeXSAVE:
934     return &m_iovec;
935   default:
936     return nullptr;
937   }
938 }
939 
940 size_t NativeRegisterContextLinux_x86_64::GetFPRSize() {
941   const FPRType fpr_type = GetFPRType();
942   switch (fpr_type) {
943   case FPRType::eFPRTypeFXSAVE:
944     return sizeof(m_fpr.xstate.fxsave);
945   case FPRType::eFPRTypeXSAVE:
946     return sizeof(m_iovec);
947   default:
948     return 0;
949   }
950 }
951 
952 Error NativeRegisterContextLinux_x86_64::ReadFPR() {
953   const FPRType fpr_type = GetFPRType();
954   const lldb_private::ArchSpec &target_arch =
955       GetRegisterInfoInterface().GetTargetArchitecture();
956   switch (fpr_type) {
957   case FPRType::eFPRTypeFXSAVE:
958     // For 32-bit inferiors on x86_32/x86_64 architectures,
959     // FXSAVE area can be read using PTRACE_GETREGSET ptrace api
960     // For 64-bit inferiors on x86_64 architectures,
961     // FXSAVE area can be read using PTRACE_GETFPREGS ptrace api
962     switch (target_arch.GetMachine()) {
963     case llvm::Triple::x86:
964       return ReadRegisterSet(&m_iovec, sizeof(m_fpr.xstate.xsave), NT_PRXFPREG);
965     case llvm::Triple::x86_64:
966       return NativeRegisterContextLinux::ReadFPR();
967     default:
968       assert(false && "Unhandled target architecture.");
969       break;
970     }
971   case FPRType::eFPRTypeXSAVE:
972     return ReadRegisterSet(&m_iovec, sizeof(m_fpr.xstate.xsave), NT_X86_XSTATE);
973   default:
974     return Error("Unrecognized FPR type");
975   }
976 }
977 
978 bool NativeRegisterContextLinux_x86_64::IsMPX(uint32_t reg_index) const {
979     return (m_reg_info.first_mpxr <= reg_index &&
980             reg_index <= m_reg_info.last_mpxc);
981 }
982 
983 bool NativeRegisterContextLinux_x86_64::CopyXSTATEtoMPX(uint32_t reg) {
984   if (!IsMPX(reg))
985     return false;
986 
987   if (reg >= m_reg_info.first_mpxr && reg <= m_reg_info.last_mpxr) {
988     ::memcpy(m_mpx_set.mpxr[reg - m_reg_info.first_mpxr].bytes,
989              m_fpr.xstate.xsave.mpxr[reg - m_reg_info.first_mpxr].bytes,
990              sizeof(MPXReg));
991   } else {
992     ::memcpy(m_mpx_set.mpxc[reg - m_reg_info.first_mpxc].bytes,
993              m_fpr.xstate.xsave.mpxc[reg - m_reg_info.first_mpxc].bytes,
994              sizeof(MPXCsr));
995   }
996   return true;
997 }
998 
999 bool NativeRegisterContextLinux_x86_64::CopyMPXtoXSTATE(uint32_t reg) {
1000   if (!IsMPX(reg))
1001     return false;
1002 
1003   if (reg >= m_reg_info.first_mpxr && reg <= m_reg_info.last_mpxr) {
1004     ::memcpy(m_fpr.xstate.xsave.mpxr[reg - m_reg_info.first_mpxr].bytes,
1005              m_mpx_set.mpxr[reg - m_reg_info.first_mpxr].bytes, sizeof(MPXReg));
1006   } else {
1007     ::memcpy(m_fpr.xstate.xsave.mpxc[reg - m_reg_info.first_mpxc].bytes,
1008              m_mpx_set.mpxc[reg - m_reg_info.first_mpxc].bytes, sizeof(MPXCsr));
1009   }
1010   return true;
1011 }
1012 
1013 Error NativeRegisterContextLinux_x86_64::IsWatchpointHit(uint32_t wp_index,
1014                                                          bool &is_hit) {
1015   if (wp_index >= NumSupportedHardwareWatchpoints())
1016     return Error("Watchpoint index out of range");
1017 
1018   RegisterValue reg_value;
1019   Error error = ReadRegisterRaw(m_reg_info.first_dr + 6, reg_value);
1020   if (error.Fail()) {
1021     is_hit = false;
1022     return error;
1023   }
1024 
1025   uint64_t status_bits = reg_value.GetAsUInt64();
1026 
1027   is_hit = status_bits & (1 << wp_index);
1028 
1029   return error;
1030 }
1031 
1032 Error NativeRegisterContextLinux_x86_64::GetWatchpointHitIndex(
1033     uint32_t &wp_index, lldb::addr_t trap_addr) {
1034   uint32_t num_hw_wps = NumSupportedHardwareWatchpoints();
1035   for (wp_index = 0; wp_index < num_hw_wps; ++wp_index) {
1036     bool is_hit;
1037     Error error = IsWatchpointHit(wp_index, is_hit);
1038     if (error.Fail()) {
1039       wp_index = LLDB_INVALID_INDEX32;
1040       return error;
1041     } else if (is_hit) {
1042       return error;
1043     }
1044   }
1045   wp_index = LLDB_INVALID_INDEX32;
1046   return Error();
1047 }
1048 
1049 Error NativeRegisterContextLinux_x86_64::IsWatchpointVacant(uint32_t wp_index,
1050                                                             bool &is_vacant) {
1051   if (wp_index >= NumSupportedHardwareWatchpoints())
1052     return Error("Watchpoint index out of range");
1053 
1054   RegisterValue reg_value;
1055   Error error = ReadRegisterRaw(m_reg_info.first_dr + 7, reg_value);
1056   if (error.Fail()) {
1057     is_vacant = false;
1058     return error;
1059   }
1060 
1061   uint64_t control_bits = reg_value.GetAsUInt64();
1062 
1063   is_vacant = !(control_bits & (1 << (2 * wp_index)));
1064 
1065   return error;
1066 }
1067 
1068 Error NativeRegisterContextLinux_x86_64::SetHardwareWatchpointWithIndex(
1069     lldb::addr_t addr, size_t size, uint32_t watch_flags, uint32_t wp_index) {
1070 
1071   if (wp_index >= NumSupportedHardwareWatchpoints())
1072     return Error("Watchpoint index out of range");
1073 
1074   // Read only watchpoints aren't supported on x86_64. Fall back to read/write
1075   // waitchpoints instead.
1076   // TODO: Add logic to detect when a write happens and ignore that watchpoint
1077   // hit.
1078   if (watch_flags == 0x2)
1079     watch_flags = 0x3;
1080 
1081   if (watch_flags != 0x1 && watch_flags != 0x3)
1082     return Error("Invalid read/write bits for watchpoint");
1083 
1084   if (size != 1 && size != 2 && size != 4 && size != 8)
1085     return Error("Invalid size for watchpoint");
1086 
1087   bool is_vacant;
1088   Error error = IsWatchpointVacant(wp_index, is_vacant);
1089   if (error.Fail())
1090     return error;
1091   if (!is_vacant)
1092     return Error("Watchpoint index not vacant");
1093 
1094   RegisterValue reg_value;
1095   error = ReadRegisterRaw(m_reg_info.first_dr + 7, reg_value);
1096   if (error.Fail())
1097     return error;
1098 
1099   // for watchpoints 0, 1, 2, or 3, respectively,
1100   // set bits 1, 3, 5, or 7
1101   uint64_t enable_bit = 1 << (2 * wp_index);
1102 
1103   // set bits 16-17, 20-21, 24-25, or 28-29
1104   // with 0b01 for write, and 0b11 for read/write
1105   uint64_t rw_bits = watch_flags << (16 + 4 * wp_index);
1106 
1107   // set bits 18-19, 22-23, 26-27, or 30-31
1108   // with 0b00, 0b01, 0b10, or 0b11
1109   // for 1, 2, 8 (if supported), or 4 bytes, respectively
1110   uint64_t size_bits = (size == 8 ? 0x2 : size - 1) << (18 + 4 * wp_index);
1111 
1112   uint64_t bit_mask = (0x3 << (2 * wp_index)) | (0xF << (16 + 4 * wp_index));
1113 
1114   uint64_t control_bits = reg_value.GetAsUInt64() & ~bit_mask;
1115 
1116   control_bits |= enable_bit | rw_bits | size_bits;
1117 
1118   error = WriteRegisterRaw(m_reg_info.first_dr + wp_index, RegisterValue(addr));
1119   if (error.Fail())
1120     return error;
1121 
1122   error =
1123       WriteRegisterRaw(m_reg_info.first_dr + 7, RegisterValue(control_bits));
1124   if (error.Fail())
1125     return error;
1126 
1127   error.Clear();
1128   return error;
1129 }
1130 
1131 bool NativeRegisterContextLinux_x86_64::ClearHardwareWatchpoint(
1132     uint32_t wp_index) {
1133   if (wp_index >= NumSupportedHardwareWatchpoints())
1134     return false;
1135 
1136   RegisterValue reg_value;
1137 
1138   // for watchpoints 0, 1, 2, or 3, respectively,
1139   // clear bits 0, 1, 2, or 3 of the debug status register (DR6)
1140   Error error = ReadRegisterRaw(m_reg_info.first_dr + 6, reg_value);
1141   if (error.Fail())
1142     return false;
1143   uint64_t bit_mask = 1 << wp_index;
1144   uint64_t status_bits = reg_value.GetAsUInt64() & ~bit_mask;
1145   error = WriteRegisterRaw(m_reg_info.first_dr + 6, RegisterValue(status_bits));
1146   if (error.Fail())
1147     return false;
1148 
1149   // for watchpoints 0, 1, 2, or 3, respectively,
1150   // clear bits {0-1,16-19}, {2-3,20-23}, {4-5,24-27}, or {6-7,28-31}
1151   // of the debug control register (DR7)
1152   error = ReadRegisterRaw(m_reg_info.first_dr + 7, reg_value);
1153   if (error.Fail())
1154     return false;
1155   bit_mask = (0x3 << (2 * wp_index)) | (0xF << (16 + 4 * wp_index));
1156   uint64_t control_bits = reg_value.GetAsUInt64() & ~bit_mask;
1157   return WriteRegisterRaw(m_reg_info.first_dr + 7, RegisterValue(control_bits))
1158       .Success();
1159 }
1160 
1161 Error NativeRegisterContextLinux_x86_64::ClearAllHardwareWatchpoints() {
1162   RegisterValue reg_value;
1163 
1164   // clear bits {0-4} of the debug status register (DR6)
1165   Error error = ReadRegisterRaw(m_reg_info.first_dr + 6, reg_value);
1166   if (error.Fail())
1167     return error;
1168   uint64_t bit_mask = 0xF;
1169   uint64_t status_bits = reg_value.GetAsUInt64() & ~bit_mask;
1170   error = WriteRegisterRaw(m_reg_info.first_dr + 6, RegisterValue(status_bits));
1171   if (error.Fail())
1172     return error;
1173 
1174   // clear bits {0-7,16-31} of the debug control register (DR7)
1175   error = ReadRegisterRaw(m_reg_info.first_dr + 7, reg_value);
1176   if (error.Fail())
1177     return error;
1178   bit_mask = 0xFF | (0xFFFF << 16);
1179   uint64_t control_bits = reg_value.GetAsUInt64() & ~bit_mask;
1180   return WriteRegisterRaw(m_reg_info.first_dr + 7, RegisterValue(control_bits));
1181 }
1182 
1183 uint32_t NativeRegisterContextLinux_x86_64::SetHardwareWatchpoint(
1184     lldb::addr_t addr, size_t size, uint32_t watch_flags) {
1185   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1186   const uint32_t num_hw_watchpoints = NumSupportedHardwareWatchpoints();
1187   for (uint32_t wp_index = 0; wp_index < num_hw_watchpoints; ++wp_index) {
1188     bool is_vacant;
1189     Error error = IsWatchpointVacant(wp_index, is_vacant);
1190     if (is_vacant) {
1191       error = SetHardwareWatchpointWithIndex(addr, size, watch_flags, wp_index);
1192       if (error.Success())
1193         return wp_index;
1194     }
1195     if (error.Fail() && log) {
1196       log->Printf("NativeRegisterContextLinux_x86_64::%s Error: %s",
1197                   __FUNCTION__, error.AsCString());
1198     }
1199   }
1200   return LLDB_INVALID_INDEX32;
1201 }
1202 
1203 lldb::addr_t
1204 NativeRegisterContextLinux_x86_64::GetWatchpointAddress(uint32_t wp_index) {
1205   if (wp_index >= NumSupportedHardwareWatchpoints())
1206     return LLDB_INVALID_ADDRESS;
1207   RegisterValue reg_value;
1208   if (ReadRegisterRaw(m_reg_info.first_dr + wp_index, reg_value).Fail())
1209     return LLDB_INVALID_ADDRESS;
1210   return reg_value.GetAsUInt64();
1211 }
1212 
1213 uint32_t NativeRegisterContextLinux_x86_64::NumSupportedHardwareWatchpoints() {
1214   // Available debug address registers: dr0, dr1, dr2, dr3
1215   return 4;
1216 }
1217 
1218 #endif // defined(__i386__) || defined(__x86_64__)
1219