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