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 // ----------------------------------------------------------------------------
222 // Required MPX define.
223 // ----------------------------------------------------------------------------
224 
225 // Support MPX extensions also if compiled with compiler without MPX support.
226 #ifndef bit_MPX
227 #define bit_MPX 0x4000
228 #endif
229 
230 // ----------------------------------------------------------------------------
231 // XCR0 extended register sets masks.
232 // ----------------------------------------------------------------------------
233 #define mask_XSTATE_AVX (1ULL << 2)
234 #define mask_XSTATE_BNDREGS (1ULL << 3)
235 #define mask_XSTATE_BNDCFG (1ULL << 4)
236 #define mask_XSTATE_MPX (mask_XSTATE_BNDREGS | mask_XSTATE_BNDCFG)
237 
238 NativeRegisterContextLinux *
239 NativeRegisterContextLinux::CreateHostNativeRegisterContextLinux(
240     const ArchSpec &target_arch, NativeThreadProtocol &native_thread,
241     uint32_t concrete_frame_idx) {
242   return new NativeRegisterContextLinux_x86_64(target_arch, native_thread,
243                                                concrete_frame_idx);
244 }
245 
246 // ----------------------------------------------------------------------------
247 // NativeRegisterContextLinux_x86_64 members.
248 // ----------------------------------------------------------------------------
249 
250 static RegisterInfoInterface *
251 CreateRegisterInfoInterface(const ArchSpec &target_arch) {
252   if (HostInfo::GetArchitecture().GetAddressByteSize() == 4) {
253     // 32-bit hosts run with a RegisterContextLinux_i386 context.
254     return new RegisterContextLinux_i386(target_arch);
255   } else {
256     assert((HostInfo::GetArchitecture().GetAddressByteSize() == 8) &&
257            "Register setting path assumes this is a 64-bit host");
258     // X86_64 hosts know how to work with 64-bit and 32-bit EXEs using the
259     // x86_64 register context.
260     return new RegisterContextLinux_x86_64(target_arch);
261   }
262 }
263 
264 NativeRegisterContextLinux_x86_64::NativeRegisterContextLinux_x86_64(
265     const ArchSpec &target_arch, NativeThreadProtocol &native_thread,
266     uint32_t concrete_frame_idx)
267     : NativeRegisterContextLinux(native_thread, concrete_frame_idx,
268                                  CreateRegisterInfoInterface(target_arch)),
269       m_xstate_type(XStateType::Invalid), m_fpr(), m_iovec(), m_ymm_set(),
270       m_mpx_set(), m_reg_info(), m_gpr_x86_64() {
271   // Set up data about ranges of valid registers.
272   switch (target_arch.GetMachine()) {
273   case llvm::Triple::x86:
274     m_reg_info.num_registers = k_num_registers_i386;
275     m_reg_info.num_gpr_registers = k_num_gpr_registers_i386;
276     m_reg_info.num_fpr_registers = k_num_fpr_registers_i386;
277     m_reg_info.num_avx_registers = k_num_avx_registers_i386;
278     m_reg_info.num_mpx_registers = k_num_mpx_registers_i386;
279     m_reg_info.last_gpr = k_last_gpr_i386;
280     m_reg_info.first_fpr = k_first_fpr_i386;
281     m_reg_info.last_fpr = k_last_fpr_i386;
282     m_reg_info.first_st = lldb_st0_i386;
283     m_reg_info.last_st = lldb_st7_i386;
284     m_reg_info.first_mm = lldb_mm0_i386;
285     m_reg_info.last_mm = lldb_mm7_i386;
286     m_reg_info.first_xmm = lldb_xmm0_i386;
287     m_reg_info.last_xmm = lldb_xmm7_i386;
288     m_reg_info.first_ymm = lldb_ymm0_i386;
289     m_reg_info.last_ymm = lldb_ymm7_i386;
290     m_reg_info.first_mpxr = lldb_bnd0_i386;
291     m_reg_info.last_mpxr = lldb_bnd3_i386;
292     m_reg_info.first_mpxc = lldb_bndcfgu_i386;
293     m_reg_info.last_mpxc = lldb_bndstatus_i386;
294     m_reg_info.first_dr = lldb_dr0_i386;
295     m_reg_info.gpr_flags = lldb_eflags_i386;
296     break;
297   case llvm::Triple::x86_64:
298     m_reg_info.num_registers = k_num_registers_x86_64;
299     m_reg_info.num_gpr_registers = k_num_gpr_registers_x86_64;
300     m_reg_info.num_fpr_registers = k_num_fpr_registers_x86_64;
301     m_reg_info.num_avx_registers = k_num_avx_registers_x86_64;
302     m_reg_info.num_mpx_registers = k_num_mpx_registers_x86_64;
303     m_reg_info.last_gpr = k_last_gpr_x86_64;
304     m_reg_info.first_fpr = k_first_fpr_x86_64;
305     m_reg_info.last_fpr = k_last_fpr_x86_64;
306     m_reg_info.first_st = lldb_st0_x86_64;
307     m_reg_info.last_st = lldb_st7_x86_64;
308     m_reg_info.first_mm = lldb_mm0_x86_64;
309     m_reg_info.last_mm = lldb_mm7_x86_64;
310     m_reg_info.first_xmm = lldb_xmm0_x86_64;
311     m_reg_info.last_xmm = lldb_xmm15_x86_64;
312     m_reg_info.first_ymm = lldb_ymm0_x86_64;
313     m_reg_info.last_ymm = lldb_ymm15_x86_64;
314     m_reg_info.first_mpxr = lldb_bnd0_x86_64;
315     m_reg_info.last_mpxr = lldb_bnd3_x86_64;
316     m_reg_info.first_mpxc = lldb_bndcfgu_x86_64;
317     m_reg_info.last_mpxc = lldb_bndstatus_x86_64;
318     m_reg_info.first_dr = lldb_dr0_x86_64;
319     m_reg_info.gpr_flags = lldb_rflags_x86_64;
320     break;
321   default:
322     assert(false && "Unhandled target architecture.");
323     break;
324   }
325 
326   // Initialize m_iovec to point to the buffer and buffer size
327   // using the conventions of Berkeley style UIO structures, as required
328   // by PTRACE extensions.
329   m_iovec.iov_base = &m_fpr.xstate.xsave;
330   m_iovec.iov_len = sizeof(m_fpr.xstate.xsave);
331 
332   // Clear out the FPR state.
333   ::memset(&m_fpr, 0, sizeof(FPR));
334 
335   // Store byte offset of fctrl (i.e. first register of FPR)
336   const RegisterInfo *reg_info_fctrl = GetRegisterInfoByName("fctrl");
337   m_fctrl_offset_in_userarea = reg_info_fctrl->byte_offset;
338 }
339 
340 // CONSIDER after local and llgs debugging are merged, register set support can
341 // be moved into a base x86-64 class with IsRegisterSetAvailable made virtual.
342 uint32_t NativeRegisterContextLinux_x86_64::GetRegisterSetCount() const {
343   uint32_t sets = 0;
344   for (uint32_t set_index = 0; set_index < k_num_register_sets; ++set_index) {
345     if (IsRegisterSetAvailable(set_index))
346       ++sets;
347   }
348 
349   return sets;
350 }
351 
352 uint32_t NativeRegisterContextLinux_x86_64::GetUserRegisterCount() const {
353   uint32_t count = 0;
354   for (uint32_t set_index = 0; set_index < k_num_register_sets; ++set_index) {
355     const RegisterSet *set = GetRegisterSet(set_index);
356     if (set)
357       count += set->num_registers;
358   }
359   return count;
360 }
361 
362 const RegisterSet *
363 NativeRegisterContextLinux_x86_64::GetRegisterSet(uint32_t set_index) const {
364   if (!IsRegisterSetAvailable(set_index))
365     return nullptr;
366 
367   switch (GetRegisterInfoInterface().GetTargetArchitecture().GetMachine()) {
368   case llvm::Triple::x86:
369     return &g_reg_sets_i386[set_index];
370   case llvm::Triple::x86_64:
371     return &g_reg_sets_x86_64[set_index];
372   default:
373     assert(false && "Unhandled target architecture.");
374     return nullptr;
375   }
376 
377   return nullptr;
378 }
379 
380 Error NativeRegisterContextLinux_x86_64::ReadRegister(
381     const RegisterInfo *reg_info, RegisterValue &reg_value) {
382   Error error;
383 
384   if (!reg_info) {
385     error.SetErrorString("reg_info NULL");
386     return error;
387   }
388 
389   const uint32_t reg = reg_info->kinds[lldb::eRegisterKindLLDB];
390   if (reg == LLDB_INVALID_REGNUM) {
391     // This is likely an internal register for lldb use only and should not be
392     // directly queried.
393     error.SetErrorStringWithFormat("register \"%s\" is an internal-only lldb "
394                                    "register, cannot read directly",
395                                    reg_info->name);
396     return error;
397   }
398 
399   if (IsFPR(reg) || IsAVX(reg) || IsMPX(reg)) {
400     error = ReadFPR();
401     if (error.Fail())
402       return error;
403   } else {
404     uint32_t full_reg = reg;
405     bool is_subreg = reg_info->invalidate_regs &&
406                      (reg_info->invalidate_regs[0] != LLDB_INVALID_REGNUM);
407 
408     if (is_subreg) {
409       // Read the full aligned 64-bit register.
410       full_reg = reg_info->invalidate_regs[0];
411     }
412 
413     error = ReadRegisterRaw(full_reg, reg_value);
414 
415     if (error.Success()) {
416       // If our read was not aligned (for ah,bh,ch,dh), shift our returned value
417       // one byte to the right.
418       if (is_subreg && (reg_info->byte_offset & 0x1))
419         reg_value.SetUInt64(reg_value.GetAsUInt64() >> 8);
420 
421       // If our return byte size was greater than the return value reg size,
422       // then
423       // use the type specified by reg_info rather than the uint64_t default
424       if (reg_value.GetByteSize() > reg_info->byte_size)
425         reg_value.SetType(reg_info);
426     }
427     return error;
428   }
429 
430   if (reg_info->encoding == lldb::eEncodingVector) {
431     lldb::ByteOrder byte_order = GetByteOrder();
432 
433     if (byte_order != lldb::eByteOrderInvalid) {
434       if (reg >= m_reg_info.first_st && reg <= m_reg_info.last_st)
435         reg_value.SetBytes(
436             m_fpr.xstate.fxsave.stmm[reg - m_reg_info.first_st].bytes,
437             reg_info->byte_size, byte_order);
438       if (reg >= m_reg_info.first_mm && reg <= m_reg_info.last_mm)
439         reg_value.SetBytes(
440             m_fpr.xstate.fxsave.stmm[reg - m_reg_info.first_mm].bytes,
441             reg_info->byte_size, byte_order);
442       if (reg >= m_reg_info.first_xmm && reg <= m_reg_info.last_xmm)
443         reg_value.SetBytes(
444             m_fpr.xstate.fxsave.xmm[reg - m_reg_info.first_xmm].bytes,
445             reg_info->byte_size, byte_order);
446       if (reg >= m_reg_info.first_ymm && reg <= m_reg_info.last_ymm) {
447         // Concatenate ymm using the register halves in xmm.bytes and ymmh.bytes
448         if (CopyXSTATEtoYMM(reg, byte_order))
449           reg_value.SetBytes(m_ymm_set.ymm[reg - m_reg_info.first_ymm].bytes,
450                              reg_info->byte_size, byte_order);
451         else {
452           error.SetErrorString("failed to copy ymm register value");
453           return error;
454         }
455       }
456       if (reg >= m_reg_info.first_mpxr && reg <= m_reg_info.last_mpxr) {
457         if (CopyXSTATEtoMPX(reg))
458           reg_value.SetBytes(m_mpx_set.mpxr[reg - m_reg_info.first_mpxr].bytes,
459                              reg_info->byte_size, byte_order);
460         else {
461           error.SetErrorString("failed to copy mpx register value");
462           return error;
463         }
464       }
465       if (reg >= m_reg_info.first_mpxc && reg <= m_reg_info.last_mpxc) {
466         if (CopyXSTATEtoMPX(reg))
467           reg_value.SetBytes(m_mpx_set.mpxc[reg - m_reg_info.first_mpxc].bytes,
468                              reg_info->byte_size, byte_order);
469         else {
470           error.SetErrorString("failed to copy mpx register value");
471           return error;
472         }
473       }
474 
475       if (reg_value.GetType() != RegisterValue::eTypeBytes)
476         error.SetErrorString(
477             "write failed - type was expected to be RegisterValue::eTypeBytes");
478 
479       return error;
480     }
481 
482     error.SetErrorString("byte order is invalid");
483     return error;
484   }
485 
486   // Get pointer to m_fpr.xstate.fxsave variable and set the data from it.
487 
488   // Byte offsets of all registers are calculated wrt 'UserArea' structure.
489   // However, ReadFPR() reads fpu registers {using ptrace(PTRACE_GETFPREGS,..)}
490   // and stores them in 'm_fpr' (of type FPR structure). To extract values of
491   // fpu
492   // registers, m_fpr should be read at byte offsets calculated wrt to FPR
493   // structure.
494 
495   // Since, FPR structure is also one of the member of UserArea structure.
496   // byte_offset(fpu wrt FPR) = byte_offset(fpu wrt UserArea) -
497   // byte_offset(fctrl wrt UserArea)
498   assert((reg_info->byte_offset - m_fctrl_offset_in_userarea) < sizeof(m_fpr));
499   uint8_t *src =
500       (uint8_t *)&m_fpr + reg_info->byte_offset - m_fctrl_offset_in_userarea;
501   switch (reg_info->byte_size) {
502   case 1:
503     reg_value.SetUInt8(*(uint8_t *)src);
504     break;
505   case 2:
506     reg_value.SetUInt16(*(uint16_t *)src);
507     break;
508   case 4:
509     reg_value.SetUInt32(*(uint32_t *)src);
510     break;
511   case 8:
512     reg_value.SetUInt64(*(uint64_t *)src);
513     break;
514   default:
515     assert(false && "Unhandled data size.");
516     error.SetErrorStringWithFormat("unhandled byte size: %" PRIu32,
517                                    reg_info->byte_size);
518     break;
519   }
520 
521   return error;
522 }
523 
524 Error NativeRegisterContextLinux_x86_64::WriteRegister(
525     const RegisterInfo *reg_info, const RegisterValue &reg_value) {
526   assert(reg_info && "reg_info is null");
527 
528   const uint32_t reg_index = reg_info->kinds[lldb::eRegisterKindLLDB];
529   if (reg_index == LLDB_INVALID_REGNUM)
530     return Error("no lldb regnum for %s", reg_info && reg_info->name
531                                               ? reg_info->name
532                                               : "<unknown register>");
533 
534   if (IsGPR(reg_index))
535     return WriteRegisterRaw(reg_index, reg_value);
536 
537   if (IsFPR(reg_index) || IsAVX(reg_index) || IsMPX(reg_index)) {
538     if (reg_info->encoding == lldb::eEncodingVector) {
539       if (reg_index >= m_reg_info.first_st && reg_index <= m_reg_info.last_st)
540         ::memcpy(
541             m_fpr.xstate.fxsave.stmm[reg_index - m_reg_info.first_st].bytes,
542             reg_value.GetBytes(), reg_value.GetByteSize());
543 
544       if (reg_index >= m_reg_info.first_mm && reg_index <= m_reg_info.last_mm)
545         ::memcpy(
546             m_fpr.xstate.fxsave.stmm[reg_index - m_reg_info.first_mm].bytes,
547             reg_value.GetBytes(), reg_value.GetByteSize());
548 
549       if (reg_index >= m_reg_info.first_xmm && reg_index <= m_reg_info.last_xmm)
550         ::memcpy(
551             m_fpr.xstate.fxsave.xmm[reg_index - m_reg_info.first_xmm].bytes,
552             reg_value.GetBytes(), reg_value.GetByteSize());
553 
554       if (reg_index >= m_reg_info.first_ymm &&
555           reg_index <= m_reg_info.last_ymm) {
556         // Store ymm register content, and split into the register halves in
557         // xmm.bytes and ymmh.bytes
558         ::memcpy(m_ymm_set.ymm[reg_index - m_reg_info.first_ymm].bytes,
559                  reg_value.GetBytes(), reg_value.GetByteSize());
560         if (!CopyYMMtoXSTATE(reg_index, GetByteOrder()))
561           return Error("CopyYMMtoXSTATE() failed");
562       }
563 
564       if (reg_index >= m_reg_info.first_mpxr &&
565           reg_index <= m_reg_info.last_mpxr) {
566         ::memcpy(m_mpx_set.mpxr[reg_index - m_reg_info.first_mpxr].bytes,
567                  reg_value.GetBytes(), reg_value.GetByteSize());
568         if (!CopyMPXtoXSTATE(reg_index))
569           return Error("CopyMPXtoXSTATE() failed");
570       }
571 
572       if (reg_index >= m_reg_info.first_mpxc &&
573           reg_index <= m_reg_info.last_mpxc) {
574         ::memcpy(m_mpx_set.mpxc[reg_index - m_reg_info.first_mpxc].bytes,
575                  reg_value.GetBytes(), reg_value.GetByteSize());
576         if (!CopyMPXtoXSTATE(reg_index))
577           return Error("CopyMPXtoXSTATE() failed");
578       }
579     } else {
580       // Get pointer to m_fpr.xstate.fxsave variable and set the data to it.
581 
582       // Byte offsets of all registers are calculated wrt 'UserArea' structure.
583       // However, WriteFPR() takes m_fpr (of type FPR structure) and writes only
584       // fpu
585       // registers using ptrace(PTRACE_SETFPREGS,..) API. Hence fpu registers
586       // should
587       // be written in m_fpr at byte offsets calculated wrt FPR structure.
588 
589       // Since, FPR structure is also one of the member of UserArea structure.
590       // byte_offset(fpu wrt FPR) = byte_offset(fpu wrt UserArea) -
591       // byte_offset(fctrl wrt UserArea)
592       assert((reg_info->byte_offset - m_fctrl_offset_in_userarea) <
593              sizeof(m_fpr));
594       uint8_t *dst = (uint8_t *)&m_fpr + reg_info->byte_offset -
595                      m_fctrl_offset_in_userarea;
596       switch (reg_info->byte_size) {
597       case 1:
598         *(uint8_t *)dst = reg_value.GetAsUInt8();
599         break;
600       case 2:
601         *(uint16_t *)dst = reg_value.GetAsUInt16();
602         break;
603       case 4:
604         *(uint32_t *)dst = reg_value.GetAsUInt32();
605         break;
606       case 8:
607         *(uint64_t *)dst = reg_value.GetAsUInt64();
608         break;
609       default:
610         assert(false && "Unhandled data size.");
611         return Error("unhandled register data size %" PRIu32,
612                      reg_info->byte_size);
613       }
614     }
615 
616     Error error = WriteFPR();
617     if (error.Fail())
618       return error;
619 
620     if (IsAVX(reg_index)) {
621       if (!CopyYMMtoXSTATE(reg_index, GetByteOrder()))
622         return Error("CopyYMMtoXSTATE() failed");
623     }
624 
625     if (IsMPX(reg_index)) {
626       if (!CopyMPXtoXSTATE(reg_index))
627         return Error("CopyMPXtoXSTATE() failed");
628     }
629     return Error();
630   }
631   return Error("failed - register wasn't recognized to be a GPR or an FPR, "
632                "write strategy unknown");
633 }
634 
635 Error NativeRegisterContextLinux_x86_64::ReadAllRegisterValues(
636     lldb::DataBufferSP &data_sp) {
637   Error error;
638 
639   data_sp.reset(new DataBufferHeap(REG_CONTEXT_SIZE, 0));
640   if (!data_sp) {
641     error.SetErrorStringWithFormat(
642         "failed to allocate DataBufferHeap instance of size %" PRIu64,
643         REG_CONTEXT_SIZE);
644     return error;
645   }
646 
647   error = ReadGPR();
648   if (error.Fail())
649     return error;
650 
651   error = ReadFPR();
652   if (error.Fail())
653     return error;
654 
655   uint8_t *dst = data_sp->GetBytes();
656   if (dst == nullptr) {
657     error.SetErrorStringWithFormat("DataBufferHeap instance of size %" PRIu64
658                                    " returned a null pointer",
659                                    REG_CONTEXT_SIZE);
660     return error;
661   }
662 
663   ::memcpy(dst, &m_gpr_x86_64, GetRegisterInfoInterface().GetGPRSize());
664   dst += GetRegisterInfoInterface().GetGPRSize();
665   if (m_xstate_type == XStateType::FXSAVE)
666     ::memcpy(dst, &m_fpr.xstate.fxsave, sizeof(m_fpr.xstate.fxsave));
667   else if (m_xstate_type == XStateType::XSAVE) {
668     lldb::ByteOrder byte_order = GetByteOrder();
669 
670     if (IsCPUFeatureAvailable(RegSet::avx)) {
671       // Assemble the YMM register content from the register halves.
672       for (uint32_t reg = m_reg_info.first_ymm; reg <= m_reg_info.last_ymm;
673            ++reg) {
674         if (!CopyXSTATEtoYMM(reg, byte_order)) {
675           error.SetErrorStringWithFormat(
676               "NativeRegisterContextLinux_x86_64::%s "
677               "CopyXSTATEtoYMM() failed for reg num "
678               "%" PRIu32,
679               __FUNCTION__, reg);
680           return error;
681         }
682       }
683     }
684 
685     if (IsCPUFeatureAvailable(RegSet::mpx)) {
686       for (uint32_t reg = m_reg_info.first_mpxr; reg <= m_reg_info.last_mpxc;
687            ++reg) {
688         if (!CopyXSTATEtoMPX(reg)) {
689           error.SetErrorStringWithFormat(
690               "NativeRegisterContextLinux_x86_64::%s "
691               "CopyXSTATEtoMPX() failed for reg num "
692               "%" PRIu32,
693               __FUNCTION__, reg);
694           return error;
695         }
696       }
697     }
698     // Copy the extended register state including the assembled ymm registers.
699     ::memcpy(dst, &m_fpr, sizeof(m_fpr));
700   } else {
701     assert(false && "how do we save the floating point registers?");
702     error.SetErrorString("unsure how to save the floating point registers");
703   }
704   /** The following code is specific to Linux x86 based architectures,
705    *  where the register orig_eax (32 bit)/orig_rax (64 bit) is set to
706    *  -1 to solve the bug 23659, such a setting prevents the automatic
707    *  decrement of the instruction pointer which was causing the SIGILL
708    *  exception.
709    * **/
710 
711   RegisterValue value((uint64_t)-1);
712   const RegisterInfo *reg_info =
713       GetRegisterInfoInterface().GetDynamicRegisterInfo("orig_eax");
714   if (reg_info == nullptr)
715     reg_info = GetRegisterInfoInterface().GetDynamicRegisterInfo("orig_rax");
716 
717   if (reg_info != nullptr)
718     return DoWriteRegisterValue(reg_info->byte_offset, reg_info->name, value);
719 
720   return error;
721 }
722 
723 Error NativeRegisterContextLinux_x86_64::WriteAllRegisterValues(
724     const lldb::DataBufferSP &data_sp) {
725   Error error;
726 
727   if (!data_sp) {
728     error.SetErrorStringWithFormat(
729         "NativeRegisterContextLinux_x86_64::%s invalid data_sp provided",
730         __FUNCTION__);
731     return error;
732   }
733 
734   if (data_sp->GetByteSize() != REG_CONTEXT_SIZE) {
735     error.SetErrorStringWithFormat(
736         "NativeRegisterContextLinux_x86_64::%s data_sp contained mismatched "
737         "data size, expected %" PRIu64 ", actual %" PRIu64,
738         __FUNCTION__, REG_CONTEXT_SIZE, data_sp->GetByteSize());
739     return error;
740   }
741 
742   uint8_t *src = data_sp->GetBytes();
743   if (src == nullptr) {
744     error.SetErrorStringWithFormat("NativeRegisterContextLinux_x86_64::%s "
745                                    "DataBuffer::GetBytes() returned a null "
746                                    "pointer",
747                                    __FUNCTION__);
748     return error;
749   }
750   ::memcpy(&m_gpr_x86_64, src, GetRegisterInfoInterface().GetGPRSize());
751 
752   error = WriteGPR();
753   if (error.Fail())
754     return error;
755 
756   src += GetRegisterInfoInterface().GetGPRSize();
757   if (m_xstate_type == XStateType::FXSAVE)
758     ::memcpy(&m_fpr.xstate.fxsave, src, sizeof(m_fpr.xstate.fxsave));
759   else if (m_xstate_type == XStateType::XSAVE)
760     ::memcpy(&m_fpr.xstate.xsave, src, sizeof(m_fpr.xstate.xsave));
761 
762   error = WriteFPR();
763   if (error.Fail())
764     return error;
765 
766   if (m_xstate_type == XStateType::XSAVE) {
767     lldb::ByteOrder byte_order = GetByteOrder();
768 
769     if (IsCPUFeatureAvailable(RegSet::avx)) {
770       // Parse the YMM register content from the register halves.
771       for (uint32_t reg = m_reg_info.first_ymm; reg <= m_reg_info.last_ymm;
772            ++reg) {
773         if (!CopyYMMtoXSTATE(reg, byte_order)) {
774           error.SetErrorStringWithFormat(
775               "NativeRegisterContextLinux_x86_64::%s "
776               "CopyYMMtoXSTATE() failed for reg num "
777               "%" PRIu32,
778               __FUNCTION__, reg);
779           return error;
780         }
781       }
782     }
783 
784     if (IsCPUFeatureAvailable(RegSet::mpx)) {
785       for (uint32_t reg = m_reg_info.first_mpxr; reg <= m_reg_info.last_mpxc;
786            ++reg) {
787         if (!CopyMPXtoXSTATE(reg)) {
788           error.SetErrorStringWithFormat(
789               "NativeRegisterContextLinux_x86_64::%s "
790               "CopyMPXtoXSTATE() failed for reg num "
791               "%" PRIu32,
792               __FUNCTION__, reg);
793           return error;
794         }
795       }
796     }
797   }
798 
799   return error;
800 }
801 
802 bool NativeRegisterContextLinux_x86_64::IsCPUFeatureAvailable(
803     RegSet feature_code) const {
804   if (m_xstate_type == XStateType::Invalid) {
805     if (const_cast<NativeRegisterContextLinux_x86_64 *>(this)->ReadFPR().Fail())
806       return false;
807   }
808   switch (feature_code) {
809   case RegSet::gpr:
810   case RegSet::fpu:
811     return true;
812   case RegSet::avx: // Check if CPU has AVX and if there is kernel support, by
813                     // reading in the XCR0 area of XSAVE.
814     if ((m_fpr.xstate.xsave.i387.xcr0 & mask_XSTATE_AVX) == mask_XSTATE_AVX)
815       return true;
816      break;
817   case RegSet::mpx: // Check if CPU has MPX and if there is kernel support, by
818                     // reading in the XCR0 area of XSAVE.
819     if ((m_fpr.xstate.xsave.i387.xcr0 & mask_XSTATE_MPX) == mask_XSTATE_MPX)
820       return true;
821     break;
822   }
823   return false;
824 }
825 
826 bool NativeRegisterContextLinux_x86_64::IsRegisterSetAvailable(
827     uint32_t set_index) const {
828   uint32_t num_sets = k_num_register_sets - k_num_extended_register_sets;
829 
830   switch (static_cast<RegSet>(set_index)) {
831   case RegSet::gpr:
832   case RegSet::fpu:
833     return (set_index < num_sets);
834   case RegSet::avx:
835     return IsCPUFeatureAvailable(RegSet::avx);
836   case RegSet::mpx:
837     return IsCPUFeatureAvailable(RegSet::mpx);
838   }
839   return false;
840 }
841 
842 bool NativeRegisterContextLinux_x86_64::IsGPR(uint32_t reg_index) const {
843   // GPRs come first.
844   return reg_index <= m_reg_info.last_gpr;
845 }
846 
847 bool NativeRegisterContextLinux_x86_64::IsFPR(uint32_t reg_index) const {
848   return (m_reg_info.first_fpr <= reg_index &&
849           reg_index <= m_reg_info.last_fpr);
850 }
851 
852 Error NativeRegisterContextLinux_x86_64::WriteFPR() {
853   switch (m_xstate_type) {
854   case XStateType::FXSAVE:
855       return WriteRegisterSet(&m_iovec, sizeof(m_fpr.xstate.xsave),
856                               NT_PRXFPREG);
857   case XStateType::XSAVE:
858     return WriteRegisterSet(&m_iovec, sizeof(m_fpr.xstate.xsave),
859                             NT_X86_XSTATE);
860   default:
861     return Error("Unrecognized FPR type.");
862   }
863 }
864 
865 bool NativeRegisterContextLinux_x86_64::IsAVX(uint32_t reg_index) const {
866   if (!IsCPUFeatureAvailable(RegSet::avx))
867     return false;
868   return (m_reg_info.first_ymm <= reg_index &&
869           reg_index <= m_reg_info.last_ymm);
870 }
871 
872 bool NativeRegisterContextLinux_x86_64::CopyXSTATEtoYMM(
873     uint32_t reg_index, lldb::ByteOrder byte_order) {
874   if (!IsAVX(reg_index))
875     return false;
876 
877   if (byte_order == lldb::eByteOrderLittle) {
878     ::memcpy(m_ymm_set.ymm[reg_index - m_reg_info.first_ymm].bytes,
879              m_fpr.xstate.fxsave.xmm[reg_index - m_reg_info.first_ymm].bytes,
880              sizeof(XMMReg));
881     ::memcpy(m_ymm_set.ymm[reg_index - m_reg_info.first_ymm].bytes +
882                  sizeof(XMMReg),
883              m_fpr.xstate.xsave.ymmh[reg_index - m_reg_info.first_ymm].bytes,
884              sizeof(YMMHReg));
885     return true;
886   }
887 
888   if (byte_order == lldb::eByteOrderBig) {
889     ::memcpy(m_ymm_set.ymm[reg_index - m_reg_info.first_ymm].bytes +
890                  sizeof(XMMReg),
891              m_fpr.xstate.fxsave.xmm[reg_index - m_reg_info.first_ymm].bytes,
892              sizeof(XMMReg));
893     ::memcpy(m_ymm_set.ymm[reg_index - m_reg_info.first_ymm].bytes,
894              m_fpr.xstate.xsave.ymmh[reg_index - m_reg_info.first_ymm].bytes,
895              sizeof(YMMHReg));
896     return true;
897   }
898   return false; // unsupported or invalid byte order
899 }
900 
901 bool NativeRegisterContextLinux_x86_64::CopyYMMtoXSTATE(
902     uint32_t reg, lldb::ByteOrder byte_order) {
903   if (!IsAVX(reg))
904     return false;
905 
906   if (byte_order == lldb::eByteOrderLittle) {
907     ::memcpy(m_fpr.xstate.fxsave.xmm[reg - m_reg_info.first_ymm].bytes,
908              m_ymm_set.ymm[reg - m_reg_info.first_ymm].bytes, sizeof(XMMReg));
909     ::memcpy(m_fpr.xstate.xsave.ymmh[reg - m_reg_info.first_ymm].bytes,
910              m_ymm_set.ymm[reg - m_reg_info.first_ymm].bytes + sizeof(XMMReg),
911              sizeof(YMMHReg));
912     return true;
913   }
914 
915   if (byte_order == lldb::eByteOrderBig) {
916     ::memcpy(m_fpr.xstate.fxsave.xmm[reg - m_reg_info.first_ymm].bytes,
917              m_ymm_set.ymm[reg - m_reg_info.first_ymm].bytes + sizeof(XMMReg),
918              sizeof(XMMReg));
919     ::memcpy(m_fpr.xstate.xsave.ymmh[reg - m_reg_info.first_ymm].bytes,
920              m_ymm_set.ymm[reg - m_reg_info.first_ymm].bytes, sizeof(YMMHReg));
921     return true;
922   }
923   return false; // unsupported or invalid byte order
924 }
925 
926 void *NativeRegisterContextLinux_x86_64::GetFPRBuffer() {
927   switch (m_xstate_type) {
928   case XStateType::FXSAVE:
929     return &m_fpr.xstate.fxsave;
930   case XStateType::XSAVE:
931     return &m_iovec;
932   default:
933     return nullptr;
934   }
935 }
936 
937 size_t NativeRegisterContextLinux_x86_64::GetFPRSize() {
938   switch (m_xstate_type) {
939   case XStateType::FXSAVE:
940     return sizeof(m_fpr.xstate.fxsave);
941   case XStateType::XSAVE:
942     return sizeof(m_iovec);
943   default:
944     return 0;
945   }
946 }
947 
948 Error NativeRegisterContextLinux_x86_64::ReadFPR() {
949   Error error;
950 
951   // Probe XSAVE and if it is not supported fall back to FXSAVE.
952   if (m_xstate_type != XStateType::FXSAVE) {
953     error =
954         ReadRegisterSet(&m_iovec, sizeof(m_fpr.xstate.xsave), NT_X86_XSTATE);
955     if (!error.Fail()) {
956       m_xstate_type = XStateType::XSAVE;
957       return error;
958     }
959   }
960   error = ReadRegisterSet(&m_iovec, sizeof(m_fpr.xstate.xsave), NT_PRXFPREG);
961   if (!error.Fail()) {
962     m_xstate_type = XStateType::FXSAVE;
963     return error;
964   }
965   return Error("Unrecognized FPR type.");
966 }
967 
968 bool NativeRegisterContextLinux_x86_64::IsMPX(uint32_t reg_index) const {
969   if (!IsCPUFeatureAvailable(RegSet::mpx))
970     return false;
971   return (m_reg_info.first_mpxr <= reg_index &&
972           reg_index <= m_reg_info.last_mpxc);
973 }
974 
975 bool NativeRegisterContextLinux_x86_64::CopyXSTATEtoMPX(uint32_t reg) {
976   if (!IsMPX(reg))
977     return false;
978 
979   if (reg >= m_reg_info.first_mpxr && reg <= m_reg_info.last_mpxr) {
980     ::memcpy(m_mpx_set.mpxr[reg - m_reg_info.first_mpxr].bytes,
981              m_fpr.xstate.xsave.mpxr[reg - m_reg_info.first_mpxr].bytes,
982              sizeof(MPXReg));
983   } else {
984     ::memcpy(m_mpx_set.mpxc[reg - m_reg_info.first_mpxc].bytes,
985              m_fpr.xstate.xsave.mpxc[reg - m_reg_info.first_mpxc].bytes,
986              sizeof(MPXCsr));
987   }
988   return true;
989 }
990 
991 bool NativeRegisterContextLinux_x86_64::CopyMPXtoXSTATE(uint32_t reg) {
992   if (!IsMPX(reg))
993     return false;
994 
995   if (reg >= m_reg_info.first_mpxr && reg <= m_reg_info.last_mpxr) {
996     ::memcpy(m_fpr.xstate.xsave.mpxr[reg - m_reg_info.first_mpxr].bytes,
997              m_mpx_set.mpxr[reg - m_reg_info.first_mpxr].bytes, sizeof(MPXReg));
998   } else {
999     ::memcpy(m_fpr.xstate.xsave.mpxc[reg - m_reg_info.first_mpxc].bytes,
1000              m_mpx_set.mpxc[reg - m_reg_info.first_mpxc].bytes, sizeof(MPXCsr));
1001   }
1002   return true;
1003 }
1004 
1005 Error NativeRegisterContextLinux_x86_64::IsWatchpointHit(uint32_t wp_index,
1006                                                          bool &is_hit) {
1007   if (wp_index >= NumSupportedHardwareWatchpoints())
1008     return Error("Watchpoint index out of range");
1009 
1010   RegisterValue reg_value;
1011   Error error = ReadRegisterRaw(m_reg_info.first_dr + 6, reg_value);
1012   if (error.Fail()) {
1013     is_hit = false;
1014     return error;
1015   }
1016 
1017   uint64_t status_bits = reg_value.GetAsUInt64();
1018 
1019   is_hit = status_bits & (1 << wp_index);
1020 
1021   return error;
1022 }
1023 
1024 Error NativeRegisterContextLinux_x86_64::GetWatchpointHitIndex(
1025     uint32_t &wp_index, lldb::addr_t trap_addr) {
1026   uint32_t num_hw_wps = NumSupportedHardwareWatchpoints();
1027   for (wp_index = 0; wp_index < num_hw_wps; ++wp_index) {
1028     bool is_hit;
1029     Error error = IsWatchpointHit(wp_index, is_hit);
1030     if (error.Fail()) {
1031       wp_index = LLDB_INVALID_INDEX32;
1032       return error;
1033     } else if (is_hit) {
1034       return error;
1035     }
1036   }
1037   wp_index = LLDB_INVALID_INDEX32;
1038   return Error();
1039 }
1040 
1041 Error NativeRegisterContextLinux_x86_64::IsWatchpointVacant(uint32_t wp_index,
1042                                                             bool &is_vacant) {
1043   if (wp_index >= NumSupportedHardwareWatchpoints())
1044     return Error("Watchpoint index out of range");
1045 
1046   RegisterValue reg_value;
1047   Error error = ReadRegisterRaw(m_reg_info.first_dr + 7, reg_value);
1048   if (error.Fail()) {
1049     is_vacant = false;
1050     return error;
1051   }
1052 
1053   uint64_t control_bits = reg_value.GetAsUInt64();
1054 
1055   is_vacant = !(control_bits & (1 << (2 * wp_index)));
1056 
1057   return error;
1058 }
1059 
1060 Error NativeRegisterContextLinux_x86_64::SetHardwareWatchpointWithIndex(
1061     lldb::addr_t addr, size_t size, uint32_t watch_flags, uint32_t wp_index) {
1062 
1063   if (wp_index >= NumSupportedHardwareWatchpoints())
1064     return Error("Watchpoint index out of range");
1065 
1066   // Read only watchpoints aren't supported on x86_64. Fall back to read/write
1067   // waitchpoints instead.
1068   // TODO: Add logic to detect when a write happens and ignore that watchpoint
1069   // hit.
1070   if (watch_flags == 0x2)
1071     watch_flags = 0x3;
1072 
1073   if (watch_flags != 0x1 && watch_flags != 0x3)
1074     return Error("Invalid read/write bits for watchpoint");
1075 
1076   if (size != 1 && size != 2 && size != 4 && size != 8)
1077     return Error("Invalid size for watchpoint");
1078 
1079   bool is_vacant;
1080   Error error = IsWatchpointVacant(wp_index, is_vacant);
1081   if (error.Fail())
1082     return error;
1083   if (!is_vacant)
1084     return Error("Watchpoint index not vacant");
1085 
1086   RegisterValue reg_value;
1087   error = ReadRegisterRaw(m_reg_info.first_dr + 7, reg_value);
1088   if (error.Fail())
1089     return error;
1090 
1091   // for watchpoints 0, 1, 2, or 3, respectively,
1092   // set bits 1, 3, 5, or 7
1093   uint64_t enable_bit = 1 << (2 * wp_index);
1094 
1095   // set bits 16-17, 20-21, 24-25, or 28-29
1096   // with 0b01 for write, and 0b11 for read/write
1097   uint64_t rw_bits = watch_flags << (16 + 4 * wp_index);
1098 
1099   // set bits 18-19, 22-23, 26-27, or 30-31
1100   // with 0b00, 0b01, 0b10, or 0b11
1101   // for 1, 2, 8 (if supported), or 4 bytes, respectively
1102   uint64_t size_bits = (size == 8 ? 0x2 : size - 1) << (18 + 4 * wp_index);
1103 
1104   uint64_t bit_mask = (0x3 << (2 * wp_index)) | (0xF << (16 + 4 * wp_index));
1105 
1106   uint64_t control_bits = reg_value.GetAsUInt64() & ~bit_mask;
1107 
1108   control_bits |= enable_bit | rw_bits | size_bits;
1109 
1110   error = WriteRegisterRaw(m_reg_info.first_dr + wp_index, RegisterValue(addr));
1111   if (error.Fail())
1112     return error;
1113 
1114   error =
1115       WriteRegisterRaw(m_reg_info.first_dr + 7, RegisterValue(control_bits));
1116   if (error.Fail())
1117     return error;
1118 
1119   error.Clear();
1120   return error;
1121 }
1122 
1123 bool NativeRegisterContextLinux_x86_64::ClearHardwareWatchpoint(
1124     uint32_t wp_index) {
1125   if (wp_index >= NumSupportedHardwareWatchpoints())
1126     return false;
1127 
1128   RegisterValue reg_value;
1129 
1130   // for watchpoints 0, 1, 2, or 3, respectively,
1131   // clear bits 0, 1, 2, or 3 of the debug status register (DR6)
1132   Error error = ReadRegisterRaw(m_reg_info.first_dr + 6, reg_value);
1133   if (error.Fail())
1134     return false;
1135   uint64_t bit_mask = 1 << wp_index;
1136   uint64_t status_bits = reg_value.GetAsUInt64() & ~bit_mask;
1137   error = WriteRegisterRaw(m_reg_info.first_dr + 6, RegisterValue(status_bits));
1138   if (error.Fail())
1139     return false;
1140 
1141   // for watchpoints 0, 1, 2, or 3, respectively,
1142   // clear bits {0-1,16-19}, {2-3,20-23}, {4-5,24-27}, or {6-7,28-31}
1143   // of the debug control register (DR7)
1144   error = ReadRegisterRaw(m_reg_info.first_dr + 7, reg_value);
1145   if (error.Fail())
1146     return false;
1147   bit_mask = (0x3 << (2 * wp_index)) | (0xF << (16 + 4 * wp_index));
1148   uint64_t control_bits = reg_value.GetAsUInt64() & ~bit_mask;
1149   return WriteRegisterRaw(m_reg_info.first_dr + 7, RegisterValue(control_bits))
1150       .Success();
1151 }
1152 
1153 Error NativeRegisterContextLinux_x86_64::ClearAllHardwareWatchpoints() {
1154   RegisterValue reg_value;
1155 
1156   // clear bits {0-4} of the debug status register (DR6)
1157   Error error = ReadRegisterRaw(m_reg_info.first_dr + 6, reg_value);
1158   if (error.Fail())
1159     return error;
1160   uint64_t bit_mask = 0xF;
1161   uint64_t status_bits = reg_value.GetAsUInt64() & ~bit_mask;
1162   error = WriteRegisterRaw(m_reg_info.first_dr + 6, RegisterValue(status_bits));
1163   if (error.Fail())
1164     return error;
1165 
1166   // clear bits {0-7,16-31} of the debug control register (DR7)
1167   error = ReadRegisterRaw(m_reg_info.first_dr + 7, reg_value);
1168   if (error.Fail())
1169     return error;
1170   bit_mask = 0xFF | (0xFFFF << 16);
1171   uint64_t control_bits = reg_value.GetAsUInt64() & ~bit_mask;
1172   return WriteRegisterRaw(m_reg_info.first_dr + 7, RegisterValue(control_bits));
1173 }
1174 
1175 uint32_t NativeRegisterContextLinux_x86_64::SetHardwareWatchpoint(
1176     lldb::addr_t addr, size_t size, uint32_t watch_flags) {
1177   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1178   const uint32_t num_hw_watchpoints = NumSupportedHardwareWatchpoints();
1179   for (uint32_t wp_index = 0; wp_index < num_hw_watchpoints; ++wp_index) {
1180     bool is_vacant;
1181     Error error = IsWatchpointVacant(wp_index, is_vacant);
1182     if (is_vacant) {
1183       error = SetHardwareWatchpointWithIndex(addr, size, watch_flags, wp_index);
1184       if (error.Success())
1185         return wp_index;
1186     }
1187     if (error.Fail() && log) {
1188       log->Printf("NativeRegisterContextLinux_x86_64::%s Error: %s",
1189                   __FUNCTION__, error.AsCString());
1190     }
1191   }
1192   return LLDB_INVALID_INDEX32;
1193 }
1194 
1195 lldb::addr_t
1196 NativeRegisterContextLinux_x86_64::GetWatchpointAddress(uint32_t wp_index) {
1197   if (wp_index >= NumSupportedHardwareWatchpoints())
1198     return LLDB_INVALID_ADDRESS;
1199   RegisterValue reg_value;
1200   if (ReadRegisterRaw(m_reg_info.first_dr + wp_index, reg_value).Fail())
1201     return LLDB_INVALID_ADDRESS;
1202   return reg_value.GetAsUInt64();
1203 }
1204 
1205 uint32_t NativeRegisterContextLinux_x86_64::NumSupportedHardwareWatchpoints() {
1206   // Available debug address registers: dr0, dr1, dr2, dr3
1207   return 4;
1208 }
1209 
1210 #endif // defined(__i386__) || defined(__x86_64__)
1211