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