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