1 //===-- NativeRegisterContextLinux_arm.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(__arm__) || defined(__arm64__) || defined(__aarch64__)
10 
11 #include "NativeRegisterContextLinux_arm.h"
12 
13 #include "Plugins/Process/Linux/NativeProcessLinux.h"
14 #include "Plugins/Process/Linux/Procfs.h"
15 #include "Plugins/Process/POSIX/ProcessPOSIXLog.h"
16 #include "Plugins/Process/Utility/RegisterInfoPOSIX_arm.h"
17 #include "lldb/Utility/DataBufferHeap.h"
18 #include "lldb/Utility/Log.h"
19 #include "lldb/Utility/RegisterValue.h"
20 #include "lldb/Utility/Status.h"
21 
22 #include <elf.h>
23 #include <sys/socket.h>
24 
25 #define REG_CONTEXT_SIZE (GetGPRSize() + sizeof(m_fpr))
26 
27 #ifndef PTRACE_GETVFPREGS
28 #define PTRACE_GETVFPREGS 27
29 #define PTRACE_SETVFPREGS 28
30 #endif
31 #ifndef PTRACE_GETHBPREGS
32 #define PTRACE_GETHBPREGS 29
33 #define PTRACE_SETHBPREGS 30
34 #endif
35 #if !defined(PTRACE_TYPE_ARG3)
36 #define PTRACE_TYPE_ARG3 void *
37 #endif
38 #if !defined(PTRACE_TYPE_ARG4)
39 #define PTRACE_TYPE_ARG4 void *
40 #endif
41 
42 using namespace lldb;
43 using namespace lldb_private;
44 using namespace lldb_private::process_linux;
45 
46 // arm general purpose registers.
47 static const uint32_t g_gpr_regnums_arm[] = {
48     gpr_r0_arm,         gpr_r1_arm,   gpr_r2_arm,  gpr_r3_arm, gpr_r4_arm,
49     gpr_r5_arm,         gpr_r6_arm,   gpr_r7_arm,  gpr_r8_arm, gpr_r9_arm,
50     gpr_r10_arm,        gpr_r11_arm,  gpr_r12_arm, gpr_sp_arm, gpr_lr_arm,
51     gpr_pc_arm,         gpr_cpsr_arm,
52     LLDB_INVALID_REGNUM // register sets need to end with this flag
53 };
54 static_assert(((sizeof g_gpr_regnums_arm / sizeof g_gpr_regnums_arm[0]) - 1) ==
55                   k_num_gpr_registers_arm,
56               "g_gpr_regnums_arm has wrong number of register infos");
57 
58 // arm floating point registers.
59 static const uint32_t g_fpu_regnums_arm[] = {
60     fpu_s0_arm,         fpu_s1_arm,  fpu_s2_arm,    fpu_s3_arm,  fpu_s4_arm,
61     fpu_s5_arm,         fpu_s6_arm,  fpu_s7_arm,    fpu_s8_arm,  fpu_s9_arm,
62     fpu_s10_arm,        fpu_s11_arm, fpu_s12_arm,   fpu_s13_arm, fpu_s14_arm,
63     fpu_s15_arm,        fpu_s16_arm, fpu_s17_arm,   fpu_s18_arm, fpu_s19_arm,
64     fpu_s20_arm,        fpu_s21_arm, fpu_s22_arm,   fpu_s23_arm, fpu_s24_arm,
65     fpu_s25_arm,        fpu_s26_arm, fpu_s27_arm,   fpu_s28_arm, fpu_s29_arm,
66     fpu_s30_arm,        fpu_s31_arm, fpu_fpscr_arm, fpu_d0_arm,  fpu_d1_arm,
67     fpu_d2_arm,         fpu_d3_arm,  fpu_d4_arm,    fpu_d5_arm,  fpu_d6_arm,
68     fpu_d7_arm,         fpu_d8_arm,  fpu_d9_arm,    fpu_d10_arm, fpu_d11_arm,
69     fpu_d12_arm,        fpu_d13_arm, fpu_d14_arm,   fpu_d15_arm, fpu_d16_arm,
70     fpu_d17_arm,        fpu_d18_arm, fpu_d19_arm,   fpu_d20_arm, fpu_d21_arm,
71     fpu_d22_arm,        fpu_d23_arm, fpu_d24_arm,   fpu_d25_arm, fpu_d26_arm,
72     fpu_d27_arm,        fpu_d28_arm, fpu_d29_arm,   fpu_d30_arm, fpu_d31_arm,
73     fpu_q0_arm,         fpu_q1_arm,  fpu_q2_arm,    fpu_q3_arm,  fpu_q4_arm,
74     fpu_q5_arm,         fpu_q6_arm,  fpu_q7_arm,    fpu_q8_arm,  fpu_q9_arm,
75     fpu_q10_arm,        fpu_q11_arm, fpu_q12_arm,   fpu_q13_arm, fpu_q14_arm,
76     fpu_q15_arm,
77     LLDB_INVALID_REGNUM // register sets need to end with this flag
78 };
79 static_assert(((sizeof g_fpu_regnums_arm / sizeof g_fpu_regnums_arm[0]) - 1) ==
80                   k_num_fpr_registers_arm,
81               "g_fpu_regnums_arm has wrong number of register infos");
82 
83 namespace {
84 // Number of register sets provided by this context.
85 enum { k_num_register_sets = 2 };
86 }
87 
88 // Register sets for arm.
89 static const RegisterSet g_reg_sets_arm[k_num_register_sets] = {
90     {"General Purpose Registers", "gpr", k_num_gpr_registers_arm,
91      g_gpr_regnums_arm},
92     {"Floating Point Registers", "fpu", k_num_fpr_registers_arm,
93      g_fpu_regnums_arm}};
94 
95 #if defined(__arm__)
96 
97 std::unique_ptr<NativeRegisterContextLinux>
98 NativeRegisterContextLinux::CreateHostNativeRegisterContextLinux(
99     const ArchSpec &target_arch, NativeThreadProtocol &native_thread) {
100   return llvm::make_unique<NativeRegisterContextLinux_arm>(target_arch,
101                                                            native_thread);
102 }
103 
104 #endif // defined(__arm__)
105 
106 NativeRegisterContextLinux_arm::NativeRegisterContextLinux_arm(
107     const ArchSpec &target_arch, NativeThreadProtocol &native_thread)
108     : NativeRegisterContextLinux(native_thread,
109                                  new RegisterInfoPOSIX_arm(target_arch)) {
110   switch (target_arch.GetMachine()) {
111   case llvm::Triple::arm:
112     m_reg_info.num_registers = k_num_registers_arm;
113     m_reg_info.num_gpr_registers = k_num_gpr_registers_arm;
114     m_reg_info.num_fpr_registers = k_num_fpr_registers_arm;
115     m_reg_info.last_gpr = k_last_gpr_arm;
116     m_reg_info.first_fpr = k_first_fpr_arm;
117     m_reg_info.last_fpr = k_last_fpr_arm;
118     m_reg_info.first_fpr_v = fpu_s0_arm;
119     m_reg_info.last_fpr_v = fpu_s31_arm;
120     m_reg_info.gpr_flags = gpr_cpsr_arm;
121     break;
122   default:
123     assert(false && "Unhandled target architecture.");
124     break;
125   }
126 
127   ::memset(&m_fpr, 0, sizeof(m_fpr));
128   ::memset(&m_gpr_arm, 0, sizeof(m_gpr_arm));
129   ::memset(&m_hwp_regs, 0, sizeof(m_hwp_regs));
130   ::memset(&m_hbr_regs, 0, sizeof(m_hbr_regs));
131 
132   // 16 is just a maximum value, query hardware for actual watchpoint count
133   m_max_hwp_supported = 16;
134   m_max_hbp_supported = 16;
135   m_refresh_hwdebug_info = true;
136 }
137 
138 uint32_t NativeRegisterContextLinux_arm::GetRegisterSetCount() const {
139   return k_num_register_sets;
140 }
141 
142 uint32_t NativeRegisterContextLinux_arm::GetUserRegisterCount() const {
143   uint32_t count = 0;
144   for (uint32_t set_index = 0; set_index < k_num_register_sets; ++set_index)
145     count += g_reg_sets_arm[set_index].num_registers;
146   return count;
147 }
148 
149 const RegisterSet *
150 NativeRegisterContextLinux_arm::GetRegisterSet(uint32_t set_index) const {
151   if (set_index < k_num_register_sets)
152     return &g_reg_sets_arm[set_index];
153 
154   return nullptr;
155 }
156 
157 Status
158 NativeRegisterContextLinux_arm::ReadRegister(const RegisterInfo *reg_info,
159                                              RegisterValue &reg_value) {
160   Status error;
161 
162   if (!reg_info) {
163     error.SetErrorString("reg_info NULL");
164     return error;
165   }
166 
167   const uint32_t reg = reg_info->kinds[lldb::eRegisterKindLLDB];
168 
169   if (IsFPR(reg)) {
170     error = ReadFPR();
171     if (error.Fail())
172       return error;
173   } else {
174     uint32_t full_reg = reg;
175     bool is_subreg = reg_info->invalidate_regs &&
176                      (reg_info->invalidate_regs[0] != LLDB_INVALID_REGNUM);
177 
178     if (is_subreg) {
179       // Read the full aligned 64-bit register.
180       full_reg = reg_info->invalidate_regs[0];
181     }
182 
183     error = ReadRegisterRaw(full_reg, reg_value);
184 
185     if (error.Success()) {
186       // If our read was not aligned (for ah,bh,ch,dh), shift our returned
187       // value one byte to the right.
188       if (is_subreg && (reg_info->byte_offset & 0x1))
189         reg_value.SetUInt64(reg_value.GetAsUInt64() >> 8);
190 
191       // If our return byte size was greater than the return value reg size,
192       // then use the type specified by reg_info rather than the uint64_t
193       // default
194       if (reg_value.GetByteSize() > reg_info->byte_size)
195         reg_value.SetType(reg_info);
196     }
197     return error;
198   }
199 
200   // Get pointer to m_fpr variable and set the data from it.
201   uint32_t fpr_offset = CalculateFprOffset(reg_info);
202   assert(fpr_offset < sizeof m_fpr);
203   uint8_t *src = (uint8_t *)&m_fpr + fpr_offset;
204   switch (reg_info->byte_size) {
205   case 2:
206     reg_value.SetUInt16(*(uint16_t *)src);
207     break;
208   case 4:
209     reg_value.SetUInt32(*(uint32_t *)src);
210     break;
211   case 8:
212     reg_value.SetUInt64(*(uint64_t *)src);
213     break;
214   case 16:
215     reg_value.SetBytes(src, 16, GetByteOrder());
216     break;
217   default:
218     assert(false && "Unhandled data size.");
219     error.SetErrorStringWithFormat("unhandled byte size: %" PRIu32,
220                                    reg_info->byte_size);
221     break;
222   }
223 
224   return error;
225 }
226 
227 Status
228 NativeRegisterContextLinux_arm::WriteRegister(const RegisterInfo *reg_info,
229                                               const RegisterValue &reg_value) {
230   if (!reg_info)
231     return Status("reg_info NULL");
232 
233   const uint32_t reg_index = reg_info->kinds[lldb::eRegisterKindLLDB];
234   if (reg_index == LLDB_INVALID_REGNUM)
235     return Status("no lldb regnum for %s", reg_info && reg_info->name
236                                                ? reg_info->name
237                                                : "<unknown register>");
238 
239   if (IsGPR(reg_index))
240     return WriteRegisterRaw(reg_index, reg_value);
241 
242   if (IsFPR(reg_index)) {
243     // Get pointer to m_fpr variable and set the data to it.
244     uint32_t fpr_offset = CalculateFprOffset(reg_info);
245     assert(fpr_offset < sizeof m_fpr);
246     uint8_t *dst = (uint8_t *)&m_fpr + fpr_offset;
247     switch (reg_info->byte_size) {
248     case 2:
249       *(uint16_t *)dst = reg_value.GetAsUInt16();
250       break;
251     case 4:
252       *(uint32_t *)dst = reg_value.GetAsUInt32();
253       break;
254     case 8:
255       *(uint64_t *)dst = reg_value.GetAsUInt64();
256       break;
257     default:
258       assert(false && "Unhandled data size.");
259       return Status("unhandled register data size %" PRIu32,
260                     reg_info->byte_size);
261     }
262 
263     Status error = WriteFPR();
264     if (error.Fail())
265       return error;
266 
267     return Status();
268   }
269 
270   return Status("failed - register wasn't recognized to be a GPR or an FPR, "
271                 "write strategy unknown");
272 }
273 
274 Status NativeRegisterContextLinux_arm::ReadAllRegisterValues(
275     lldb::DataBufferSP &data_sp) {
276   Status error;
277 
278   data_sp.reset(new DataBufferHeap(REG_CONTEXT_SIZE, 0));
279   error = ReadGPR();
280   if (error.Fail())
281     return error;
282 
283   error = ReadFPR();
284   if (error.Fail())
285     return error;
286 
287   uint8_t *dst = data_sp->GetBytes();
288   if (dst == nullptr) {
289     error.SetErrorStringWithFormat("DataBufferHeap instance of size %" PRIu64
290                                    " returned a null pointer",
291                                    (uint64_t)REG_CONTEXT_SIZE);
292     return error;
293   }
294 
295   ::memcpy(dst, &m_gpr_arm, GetGPRSize());
296   dst += GetGPRSize();
297   ::memcpy(dst, &m_fpr, sizeof(m_fpr));
298 
299   return error;
300 }
301 
302 Status NativeRegisterContextLinux_arm::WriteAllRegisterValues(
303     const lldb::DataBufferSP &data_sp) {
304   Status error;
305 
306   if (!data_sp) {
307     error.SetErrorStringWithFormat(
308         "NativeRegisterContextLinux_x86_64::%s invalid data_sp provided",
309         __FUNCTION__);
310     return error;
311   }
312 
313   if (data_sp->GetByteSize() != REG_CONTEXT_SIZE) {
314     error.SetErrorStringWithFormat(
315         "NativeRegisterContextLinux_x86_64::%s data_sp contained mismatched "
316         "data size, expected %" PRIu64 ", actual %" PRIu64,
317         __FUNCTION__, (uint64_t)REG_CONTEXT_SIZE, data_sp->GetByteSize());
318     return error;
319   }
320 
321   uint8_t *src = data_sp->GetBytes();
322   if (src == nullptr) {
323     error.SetErrorStringWithFormat("NativeRegisterContextLinux_x86_64::%s "
324                                    "DataBuffer::GetBytes() returned a null "
325                                    "pointer",
326                                    __FUNCTION__);
327     return error;
328   }
329   ::memcpy(&m_gpr_arm, src, GetRegisterInfoInterface().GetGPRSize());
330 
331   error = WriteGPR();
332   if (error.Fail())
333     return error;
334 
335   src += GetRegisterInfoInterface().GetGPRSize();
336   ::memcpy(&m_fpr, src, sizeof(m_fpr));
337 
338   error = WriteFPR();
339   if (error.Fail())
340     return error;
341 
342   return error;
343 }
344 
345 bool NativeRegisterContextLinux_arm::IsGPR(unsigned reg) const {
346   return reg <= m_reg_info.last_gpr; // GPR's come first.
347 }
348 
349 bool NativeRegisterContextLinux_arm::IsFPR(unsigned reg) const {
350   return (m_reg_info.first_fpr <= reg && reg <= m_reg_info.last_fpr);
351 }
352 
353 uint32_t NativeRegisterContextLinux_arm::NumSupportedHardwareBreakpoints() {
354   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_BREAKPOINTS));
355 
356   if (log)
357     log->Printf("NativeRegisterContextLinux_arm::%s()", __FUNCTION__);
358 
359   Status error;
360 
361   // Read hardware breakpoint and watchpoint information.
362   error = ReadHardwareDebugInfo();
363 
364   if (error.Fail())
365     return 0;
366 
367   LLDB_LOG(log, "{0}", m_max_hbp_supported);
368   return m_max_hbp_supported;
369 }
370 
371 uint32_t
372 NativeRegisterContextLinux_arm::SetHardwareBreakpoint(lldb::addr_t addr,
373                                                       size_t size) {
374   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_BREAKPOINTS));
375   LLDB_LOG(log, "addr: {0:x}, size: {1:x}", addr, size);
376 
377   // Read hardware breakpoint and watchpoint information.
378   Status error = ReadHardwareDebugInfo();
379 
380   if (error.Fail())
381     return LLDB_INVALID_INDEX32;
382 
383   uint32_t control_value = 0, bp_index = 0;
384 
385   // Setup address and control values.
386   // Use size to get a hint of arm vs thumb modes.
387   switch (size) {
388   case 2:
389     control_value = (0x3 << 5) | 7;
390     addr &= ~1;
391     break;
392   case 4:
393     control_value = (0xfu << 5) | 7;
394     addr &= ~3;
395     break;
396   default:
397     return LLDB_INVALID_INDEX32;
398   }
399 
400   // Iterate over stored breakpoints and find a free bp_index
401   bp_index = LLDB_INVALID_INDEX32;
402   for (uint32_t i = 0; i < m_max_hbp_supported; i++) {
403     if ((m_hbr_regs[i].control & 1) == 0) {
404       bp_index = i; // Mark last free slot
405     } else if (m_hbr_regs[i].address == addr) {
406       return LLDB_INVALID_INDEX32; // We do not support duplicate breakpoints.
407     }
408   }
409 
410   if (bp_index == LLDB_INVALID_INDEX32)
411     return LLDB_INVALID_INDEX32;
412 
413   // Update breakpoint in local cache
414   m_hbr_regs[bp_index].real_addr = addr;
415   m_hbr_regs[bp_index].address = addr;
416   m_hbr_regs[bp_index].control = control_value;
417 
418   // PTRACE call to set corresponding hardware breakpoint register.
419   error = WriteHardwareDebugRegs(eDREGTypeBREAK, bp_index);
420 
421   if (error.Fail()) {
422     m_hbr_regs[bp_index].address = 0;
423     m_hbr_regs[bp_index].control &= ~1;
424 
425     return LLDB_INVALID_INDEX32;
426   }
427 
428   return bp_index;
429 }
430 
431 bool NativeRegisterContextLinux_arm::ClearHardwareBreakpoint(uint32_t hw_idx) {
432   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_BREAKPOINTS));
433   LLDB_LOG(log, "hw_idx: {0}", hw_idx);
434 
435   // Read hardware breakpoint and watchpoint information.
436   Status error = ReadHardwareDebugInfo();
437 
438   if (error.Fail())
439     return false;
440 
441   if (hw_idx >= m_max_hbp_supported)
442     return false;
443 
444   // Create a backup we can revert to in case of failure.
445   lldb::addr_t tempAddr = m_hbr_regs[hw_idx].address;
446   uint32_t tempControl = m_hbr_regs[hw_idx].control;
447 
448   m_hbr_regs[hw_idx].control &= ~1;
449   m_hbr_regs[hw_idx].address = 0;
450 
451   // PTRACE call to clear corresponding hardware breakpoint register.
452   error = WriteHardwareDebugRegs(eDREGTypeBREAK, hw_idx);
453 
454   if (error.Fail()) {
455     m_hbr_regs[hw_idx].control = tempControl;
456     m_hbr_regs[hw_idx].address = tempAddr;
457 
458     return false;
459   }
460 
461   return true;
462 }
463 
464 Status NativeRegisterContextLinux_arm::GetHardwareBreakHitIndex(
465     uint32_t &bp_index, lldb::addr_t trap_addr) {
466   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_BREAKPOINTS));
467 
468   if (log)
469     log->Printf("NativeRegisterContextLinux_arm64::%s()", __FUNCTION__);
470 
471   lldb::addr_t break_addr;
472 
473   for (bp_index = 0; bp_index < m_max_hbp_supported; ++bp_index) {
474     break_addr = m_hbr_regs[bp_index].address;
475 
476     if ((m_hbr_regs[bp_index].control & 0x1) && (trap_addr == break_addr)) {
477       m_hbr_regs[bp_index].hit_addr = trap_addr;
478       return Status();
479     }
480   }
481 
482   bp_index = LLDB_INVALID_INDEX32;
483   return Status();
484 }
485 
486 Status NativeRegisterContextLinux_arm::ClearAllHardwareBreakpoints() {
487   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_BREAKPOINTS));
488 
489   if (log)
490     log->Printf("NativeRegisterContextLinux_arm::%s()", __FUNCTION__);
491 
492   Status error;
493 
494   // Read hardware breakpoint and watchpoint information.
495   error = ReadHardwareDebugInfo();
496 
497   if (error.Fail())
498     return error;
499 
500   lldb::addr_t tempAddr = 0;
501   uint32_t tempControl = 0;
502 
503   for (uint32_t i = 0; i < m_max_hbp_supported; i++) {
504     if (m_hbr_regs[i].control & 0x01) {
505       // Create a backup we can revert to in case of failure.
506       tempAddr = m_hbr_regs[i].address;
507       tempControl = m_hbr_regs[i].control;
508 
509       // Clear breakpoints in local cache
510       m_hbr_regs[i].control &= ~1;
511       m_hbr_regs[i].address = 0;
512 
513       // Ptrace call to update hardware debug registers
514       error = WriteHardwareDebugRegs(eDREGTypeBREAK, i);
515 
516       if (error.Fail()) {
517         m_hbr_regs[i].control = tempControl;
518         m_hbr_regs[i].address = tempAddr;
519 
520         return error;
521       }
522     }
523   }
524 
525   return Status();
526 }
527 
528 uint32_t NativeRegisterContextLinux_arm::NumSupportedHardwareWatchpoints() {
529   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_WATCHPOINTS));
530 
531   // Read hardware breakpoint and watchpoint information.
532   Status error = ReadHardwareDebugInfo();
533 
534   if (error.Fail())
535     return 0;
536 
537   LLDB_LOG(log, "{0}", m_max_hwp_supported);
538   return m_max_hwp_supported;
539 }
540 
541 uint32_t NativeRegisterContextLinux_arm::SetHardwareWatchpoint(
542     lldb::addr_t addr, size_t size, uint32_t watch_flags) {
543   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_WATCHPOINTS));
544   LLDB_LOG(log, "addr: {0:x}, size: {1:x} watch_flags: {2:x}", addr, size,
545            watch_flags);
546 
547   // Read hardware breakpoint and watchpoint information.
548   Status error = ReadHardwareDebugInfo();
549 
550   if (error.Fail())
551     return LLDB_INVALID_INDEX32;
552 
553   uint32_t control_value = 0, wp_index = 0, addr_word_offset = 0, byte_mask = 0;
554   lldb::addr_t real_addr = addr;
555 
556   // Check if we are setting watchpoint other than read/write/access Also
557   // update watchpoint flag to match Arm write-read bit configuration.
558   switch (watch_flags) {
559   case 1:
560     watch_flags = 2;
561     break;
562   case 2:
563     watch_flags = 1;
564     break;
565   case 3:
566     break;
567   default:
568     return LLDB_INVALID_INDEX32;
569   }
570 
571   // Can't watch zero bytes
572   // Can't watch more than 4 bytes per WVR/WCR pair
573 
574   if (size == 0 || size > 4)
575     return LLDB_INVALID_INDEX32;
576 
577   // Check 4-byte alignment for hardware watchpoint target address. Below is a
578   // hack to recalculate address and size in order to make sure we can watch
579   // non 4-byte alligned addresses as well.
580   if (addr & 0x03) {
581     uint8_t watch_mask = (addr & 0x03) + size;
582 
583     if (watch_mask > 0x04)
584       return LLDB_INVALID_INDEX32;
585     else if (watch_mask <= 0x02)
586       size = 2;
587     else if (watch_mask <= 0x04)
588       size = 4;
589 
590     addr = addr & (~0x03);
591   }
592 
593   // We can only watch up to four bytes that follow a 4 byte aligned address
594   // per watchpoint register pair, so make sure we can properly encode this.
595   addr_word_offset = addr % 4;
596   byte_mask = ((1u << size) - 1u) << addr_word_offset;
597 
598   // Check if we need multiple watchpoint register
599   if (byte_mask > 0xfu)
600     return LLDB_INVALID_INDEX32;
601 
602   // Setup control value
603   // Make the byte_mask into a valid Byte Address Select mask
604   control_value = byte_mask << 5;
605 
606   // Turn on appropriate watchpoint flags read or write
607   control_value |= (watch_flags << 3);
608 
609   // Enable this watchpoint and make it stop in privileged or user mode;
610   control_value |= 7;
611 
612   // Make sure bits 1:0 are clear in our address
613   addr &= ~((lldb::addr_t)3);
614 
615   // Iterate over stored watchpoints and find a free wp_index
616   wp_index = LLDB_INVALID_INDEX32;
617   for (uint32_t i = 0; i < m_max_hwp_supported; i++) {
618     if ((m_hwp_regs[i].control & 1) == 0) {
619       wp_index = i; // Mark last free slot
620     } else if (m_hwp_regs[i].address == addr) {
621       return LLDB_INVALID_INDEX32; // We do not support duplicate watchpoints.
622     }
623   }
624 
625   if (wp_index == LLDB_INVALID_INDEX32)
626     return LLDB_INVALID_INDEX32;
627 
628   // Update watchpoint in local cache
629   m_hwp_regs[wp_index].real_addr = real_addr;
630   m_hwp_regs[wp_index].address = addr;
631   m_hwp_regs[wp_index].control = control_value;
632 
633   // PTRACE call to set corresponding watchpoint register.
634   error = WriteHardwareDebugRegs(eDREGTypeWATCH, wp_index);
635 
636   if (error.Fail()) {
637     m_hwp_regs[wp_index].address = 0;
638     m_hwp_regs[wp_index].control &= ~1;
639 
640     return LLDB_INVALID_INDEX32;
641   }
642 
643   return wp_index;
644 }
645 
646 bool NativeRegisterContextLinux_arm::ClearHardwareWatchpoint(
647     uint32_t wp_index) {
648   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_WATCHPOINTS));
649   LLDB_LOG(log, "wp_index: {0}", wp_index);
650 
651   // Read hardware breakpoint and watchpoint information.
652   Status error = ReadHardwareDebugInfo();
653 
654   if (error.Fail())
655     return false;
656 
657   if (wp_index >= m_max_hwp_supported)
658     return false;
659 
660   // Create a backup we can revert to in case of failure.
661   lldb::addr_t tempAddr = m_hwp_regs[wp_index].address;
662   uint32_t tempControl = m_hwp_regs[wp_index].control;
663 
664   // Update watchpoint in local cache
665   m_hwp_regs[wp_index].control &= ~1;
666   m_hwp_regs[wp_index].address = 0;
667 
668   // Ptrace call to update hardware debug registers
669   error = WriteHardwareDebugRegs(eDREGTypeWATCH, wp_index);
670 
671   if (error.Fail()) {
672     m_hwp_regs[wp_index].control = tempControl;
673     m_hwp_regs[wp_index].address = tempAddr;
674 
675     return false;
676   }
677 
678   return true;
679 }
680 
681 Status NativeRegisterContextLinux_arm::ClearAllHardwareWatchpoints() {
682   // Read hardware breakpoint and watchpoint information.
683   Status error = ReadHardwareDebugInfo();
684 
685   if (error.Fail())
686     return error;
687 
688   lldb::addr_t tempAddr = 0;
689   uint32_t tempControl = 0;
690 
691   for (uint32_t i = 0; i < m_max_hwp_supported; i++) {
692     if (m_hwp_regs[i].control & 0x01) {
693       // Create a backup we can revert to in case of failure.
694       tempAddr = m_hwp_regs[i].address;
695       tempControl = m_hwp_regs[i].control;
696 
697       // Clear watchpoints in local cache
698       m_hwp_regs[i].control &= ~1;
699       m_hwp_regs[i].address = 0;
700 
701       // Ptrace call to update hardware debug registers
702       error = WriteHardwareDebugRegs(eDREGTypeWATCH, i);
703 
704       if (error.Fail()) {
705         m_hwp_regs[i].control = tempControl;
706         m_hwp_regs[i].address = tempAddr;
707 
708         return error;
709       }
710     }
711   }
712 
713   return Status();
714 }
715 
716 uint32_t NativeRegisterContextLinux_arm::GetWatchpointSize(uint32_t wp_index) {
717   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_WATCHPOINTS));
718   LLDB_LOG(log, "wp_index: {0}", wp_index);
719 
720   switch ((m_hwp_regs[wp_index].control >> 5) & 0x0f) {
721   case 0x01:
722     return 1;
723   case 0x03:
724     return 2;
725   case 0x07:
726     return 3;
727   case 0x0f:
728     return 4;
729   default:
730     return 0;
731   }
732 }
733 bool NativeRegisterContextLinux_arm::WatchpointIsEnabled(uint32_t wp_index) {
734   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_WATCHPOINTS));
735   LLDB_LOG(log, "wp_index: {0}", wp_index);
736 
737   if ((m_hwp_regs[wp_index].control & 0x1) == 0x1)
738     return true;
739   else
740     return false;
741 }
742 
743 Status
744 NativeRegisterContextLinux_arm::GetWatchpointHitIndex(uint32_t &wp_index,
745                                                       lldb::addr_t trap_addr) {
746   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_WATCHPOINTS));
747   LLDB_LOG(log, "wp_index: {0}, trap_addr: {1:x}", wp_index, trap_addr);
748 
749   uint32_t watch_size;
750   lldb::addr_t watch_addr;
751 
752   for (wp_index = 0; wp_index < m_max_hwp_supported; ++wp_index) {
753     watch_size = GetWatchpointSize(wp_index);
754     watch_addr = m_hwp_regs[wp_index].address;
755 
756     if (WatchpointIsEnabled(wp_index) && trap_addr >= watch_addr &&
757         trap_addr < watch_addr + watch_size) {
758       m_hwp_regs[wp_index].hit_addr = trap_addr;
759       return Status();
760     }
761   }
762 
763   wp_index = LLDB_INVALID_INDEX32;
764   return Status();
765 }
766 
767 lldb::addr_t
768 NativeRegisterContextLinux_arm::GetWatchpointAddress(uint32_t wp_index) {
769   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_WATCHPOINTS));
770   LLDB_LOG(log, "wp_index: {0}", wp_index);
771 
772   if (wp_index >= m_max_hwp_supported)
773     return LLDB_INVALID_ADDRESS;
774 
775   if (WatchpointIsEnabled(wp_index))
776     return m_hwp_regs[wp_index].real_addr;
777   else
778     return LLDB_INVALID_ADDRESS;
779 }
780 
781 lldb::addr_t
782 NativeRegisterContextLinux_arm::GetWatchpointHitAddress(uint32_t wp_index) {
783   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_WATCHPOINTS));
784   LLDB_LOG(log, "wp_index: {0}", wp_index);
785 
786   if (wp_index >= m_max_hwp_supported)
787     return LLDB_INVALID_ADDRESS;
788 
789   if (WatchpointIsEnabled(wp_index))
790     return m_hwp_regs[wp_index].hit_addr;
791   else
792     return LLDB_INVALID_ADDRESS;
793 }
794 
795 Status NativeRegisterContextLinux_arm::ReadHardwareDebugInfo() {
796   Status error;
797 
798   if (!m_refresh_hwdebug_info) {
799     return Status();
800   }
801 
802   unsigned int cap_val;
803 
804   error = NativeProcessLinux::PtraceWrapper(PTRACE_GETHBPREGS, m_thread.GetID(),
805                                             nullptr, &cap_val,
806                                             sizeof(unsigned int));
807 
808   if (error.Fail())
809     return error;
810 
811   m_max_hwp_supported = (cap_val >> 8) & 0xff;
812   m_max_hbp_supported = cap_val & 0xff;
813   m_refresh_hwdebug_info = false;
814 
815   return error;
816 }
817 
818 Status NativeRegisterContextLinux_arm::WriteHardwareDebugRegs(int hwbType,
819                                                               int hwb_index) {
820   Status error;
821 
822   lldb::addr_t *addr_buf;
823   uint32_t *ctrl_buf;
824 
825   if (hwbType == eDREGTypeWATCH) {
826     addr_buf = &m_hwp_regs[hwb_index].address;
827     ctrl_buf = &m_hwp_regs[hwb_index].control;
828 
829     error = NativeProcessLinux::PtraceWrapper(
830         PTRACE_SETHBPREGS, m_thread.GetID(),
831         (PTRACE_TYPE_ARG3)(intptr_t) - ((hwb_index << 1) + 1), addr_buf,
832         sizeof(unsigned int));
833 
834     if (error.Fail())
835       return error;
836 
837     error = NativeProcessLinux::PtraceWrapper(
838         PTRACE_SETHBPREGS, m_thread.GetID(),
839         (PTRACE_TYPE_ARG3)(intptr_t) - ((hwb_index << 1) + 2), ctrl_buf,
840         sizeof(unsigned int));
841   } else {
842     addr_buf = &m_hbr_regs[hwb_index].address;
843     ctrl_buf = &m_hbr_regs[hwb_index].control;
844 
845     error = NativeProcessLinux::PtraceWrapper(
846         PTRACE_SETHBPREGS, m_thread.GetID(),
847         (PTRACE_TYPE_ARG3)(intptr_t)((hwb_index << 1) + 1), addr_buf,
848         sizeof(unsigned int));
849 
850     if (error.Fail())
851       return error;
852 
853     error = NativeProcessLinux::PtraceWrapper(
854         PTRACE_SETHBPREGS, m_thread.GetID(),
855         (PTRACE_TYPE_ARG3)(intptr_t)((hwb_index << 1) + 2), ctrl_buf,
856         sizeof(unsigned int));
857   }
858 
859   return error;
860 }
861 
862 uint32_t NativeRegisterContextLinux_arm::CalculateFprOffset(
863     const RegisterInfo *reg_info) const {
864   return reg_info->byte_offset -
865          GetRegisterInfoAtIndex(m_reg_info.first_fpr)->byte_offset;
866 }
867 
868 Status NativeRegisterContextLinux_arm::DoReadRegisterValue(
869     uint32_t offset, const char *reg_name, uint32_t size,
870     RegisterValue &value) {
871   // PTRACE_PEEKUSER don't work in the aarch64 linux kernel used on android
872   // devices (always return "Bad address"). To avoid using PTRACE_PEEKUSER we
873   // read out the full GPR register set instead. This approach is about 4 times
874   // slower but the performance overhead is negligible in comparision to
875   // processing time in lldb-server.
876   assert(offset % 4 == 0 && "Try to write a register with unaligned offset");
877   if (offset + sizeof(uint32_t) > sizeof(m_gpr_arm))
878     return Status("Register isn't fit into the size of the GPR area");
879 
880   Status error = DoReadGPR(m_gpr_arm, sizeof(m_gpr_arm));
881   if (error.Fail())
882     return error;
883 
884   value.SetUInt32(m_gpr_arm[offset / sizeof(uint32_t)]);
885   return Status();
886 }
887 
888 Status NativeRegisterContextLinux_arm::DoWriteRegisterValue(
889     uint32_t offset, const char *reg_name, const RegisterValue &value) {
890   // PTRACE_POKEUSER don't work in the aarch64 linux kernel used on android
891   // devices (always return "Bad address"). To avoid using PTRACE_POKEUSER we
892   // read out the full GPR register set, modify the requested register and
893   // write it back. This approach is about 4 times slower but the performance
894   // overhead is negligible in comparision to processing time in lldb-server.
895   assert(offset % 4 == 0 && "Try to write a register with unaligned offset");
896   if (offset + sizeof(uint32_t) > sizeof(m_gpr_arm))
897     return Status("Register isn't fit into the size of the GPR area");
898 
899   Status error = DoReadGPR(m_gpr_arm, sizeof(m_gpr_arm));
900   if (error.Fail())
901     return error;
902 
903   uint32_t reg_value = value.GetAsUInt32();
904   // As precaution for an undefined behavior encountered while setting PC we
905   // will clear thumb bit of new PC if we are already in thumb mode; that is
906   // CPSR thumb mode bit is set.
907   if (offset / sizeof(uint32_t) == gpr_pc_arm) {
908     // Check if we are already in thumb mode and thumb bit of current PC is
909     // read out to be zero and thumb bit of next PC is read out to be one.
910     if ((m_gpr_arm[gpr_cpsr_arm] & 0x20) && !(m_gpr_arm[gpr_pc_arm] & 0x01) &&
911         (value.GetAsUInt32() & 0x01)) {
912       reg_value &= (~1ull);
913     }
914   }
915 
916   m_gpr_arm[offset / sizeof(uint32_t)] = reg_value;
917   return DoWriteGPR(m_gpr_arm, sizeof(m_gpr_arm));
918 }
919 
920 Status NativeRegisterContextLinux_arm::DoReadGPR(void *buf, size_t buf_size) {
921 #ifdef __arm__
922   return NativeRegisterContextLinux::DoReadGPR(buf, buf_size);
923 #else  // __aarch64__
924   struct iovec ioVec;
925   ioVec.iov_base = buf;
926   ioVec.iov_len = buf_size;
927 
928   return ReadRegisterSet(&ioVec, buf_size, NT_PRSTATUS);
929 #endif // __arm__
930 }
931 
932 Status NativeRegisterContextLinux_arm::DoWriteGPR(void *buf, size_t buf_size) {
933 #ifdef __arm__
934   return NativeRegisterContextLinux::DoWriteGPR(buf, buf_size);
935 #else  // __aarch64__
936   struct iovec ioVec;
937   ioVec.iov_base = buf;
938   ioVec.iov_len = buf_size;
939 
940   return WriteRegisterSet(&ioVec, buf_size, NT_PRSTATUS);
941 #endif // __arm__
942 }
943 
944 Status NativeRegisterContextLinux_arm::DoReadFPR(void *buf, size_t buf_size) {
945 #ifdef __arm__
946   return NativeProcessLinux::PtraceWrapper(PTRACE_GETVFPREGS, m_thread.GetID(),
947                                            nullptr, buf, buf_size);
948 #else  // __aarch64__
949   struct iovec ioVec;
950   ioVec.iov_base = buf;
951   ioVec.iov_len = buf_size;
952 
953   return ReadRegisterSet(&ioVec, buf_size, NT_ARM_VFP);
954 #endif // __arm__
955 }
956 
957 Status NativeRegisterContextLinux_arm::DoWriteFPR(void *buf, size_t buf_size) {
958 #ifdef __arm__
959   return NativeProcessLinux::PtraceWrapper(PTRACE_SETVFPREGS, m_thread.GetID(),
960                                            nullptr, buf, buf_size);
961 #else  // __aarch64__
962   struct iovec ioVec;
963   ioVec.iov_base = buf;
964   ioVec.iov_len = buf_size;
965 
966   return WriteRegisterSet(&ioVec, buf_size, NT_ARM_VFP);
967 #endif // __arm__
968 }
969 
970 #endif // defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
971