xref: /openbsd-src/gnu/llvm/lldb/source/Plugins/Process/Linux/NativeRegisterContextLinux_arm.cpp (revision 061da546b983eb767bad15e67af1174fb0bcf31c)
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 std::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   ::memcpy(dst, &m_gpr_arm, GetGPRSize());
289   dst += GetGPRSize();
290   ::memcpy(dst, &m_fpr, sizeof(m_fpr));
291 
292   return error;
293 }
294 
295 Status NativeRegisterContextLinux_arm::WriteAllRegisterValues(
296     const lldb::DataBufferSP &data_sp) {
297   Status error;
298 
299   if (!data_sp) {
300     error.SetErrorStringWithFormat(
301         "NativeRegisterContextLinux_x86_64::%s invalid data_sp provided",
302         __FUNCTION__);
303     return error;
304   }
305 
306   if (data_sp->GetByteSize() != REG_CONTEXT_SIZE) {
307     error.SetErrorStringWithFormat(
308         "NativeRegisterContextLinux_x86_64::%s data_sp contained mismatched "
309         "data size, expected %" PRIu64 ", actual %" PRIu64,
310         __FUNCTION__, (uint64_t)REG_CONTEXT_SIZE, data_sp->GetByteSize());
311     return error;
312   }
313 
314   uint8_t *src = data_sp->GetBytes();
315   if (src == nullptr) {
316     error.SetErrorStringWithFormat("NativeRegisterContextLinux_x86_64::%s "
317                                    "DataBuffer::GetBytes() returned a null "
318                                    "pointer",
319                                    __FUNCTION__);
320     return error;
321   }
322   ::memcpy(&m_gpr_arm, src, GetRegisterInfoInterface().GetGPRSize());
323 
324   error = WriteGPR();
325   if (error.Fail())
326     return error;
327 
328   src += GetRegisterInfoInterface().GetGPRSize();
329   ::memcpy(&m_fpr, src, sizeof(m_fpr));
330 
331   error = WriteFPR();
332   if (error.Fail())
333     return error;
334 
335   return error;
336 }
337 
338 bool NativeRegisterContextLinux_arm::IsGPR(unsigned reg) const {
339   return reg <= m_reg_info.last_gpr; // GPR's come first.
340 }
341 
342 bool NativeRegisterContextLinux_arm::IsFPR(unsigned reg) const {
343   return (m_reg_info.first_fpr <= reg && reg <= m_reg_info.last_fpr);
344 }
345 
346 uint32_t NativeRegisterContextLinux_arm::NumSupportedHardwareBreakpoints() {
347   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_BREAKPOINTS));
348 
349   LLDB_LOGF(log, "NativeRegisterContextLinux_arm::%s()", __FUNCTION__);
350 
351   Status error;
352 
353   // Read hardware breakpoint and watchpoint information.
354   error = ReadHardwareDebugInfo();
355 
356   if (error.Fail())
357     return 0;
358 
359   LLDB_LOG(log, "{0}", m_max_hbp_supported);
360   return m_max_hbp_supported;
361 }
362 
363 uint32_t
364 NativeRegisterContextLinux_arm::SetHardwareBreakpoint(lldb::addr_t addr,
365                                                       size_t size) {
366   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_BREAKPOINTS));
367   LLDB_LOG(log, "addr: {0:x}, size: {1:x}", addr, size);
368 
369   // Read hardware breakpoint and watchpoint information.
370   Status error = ReadHardwareDebugInfo();
371 
372   if (error.Fail())
373     return LLDB_INVALID_INDEX32;
374 
375   uint32_t control_value = 0, bp_index = 0;
376 
377   // Setup address and control values.
378   // Use size to get a hint of arm vs thumb modes.
379   switch (size) {
380   case 2:
381     control_value = (0x3 << 5) | 7;
382     addr &= ~1;
383     break;
384   case 4:
385     control_value = (0xfu << 5) | 7;
386     addr &= ~3;
387     break;
388   default:
389     return LLDB_INVALID_INDEX32;
390   }
391 
392   // Iterate over stored breakpoints and find a free bp_index
393   bp_index = LLDB_INVALID_INDEX32;
394   for (uint32_t i = 0; i < m_max_hbp_supported; i++) {
395     if ((m_hbr_regs[i].control & 1) == 0) {
396       bp_index = i; // Mark last free slot
397     } else if (m_hbr_regs[i].address == addr) {
398       return LLDB_INVALID_INDEX32; // We do not support duplicate breakpoints.
399     }
400   }
401 
402   if (bp_index == LLDB_INVALID_INDEX32)
403     return LLDB_INVALID_INDEX32;
404 
405   // Update breakpoint in local cache
406   m_hbr_regs[bp_index].real_addr = addr;
407   m_hbr_regs[bp_index].address = addr;
408   m_hbr_regs[bp_index].control = control_value;
409 
410   // PTRACE call to set corresponding hardware breakpoint register.
411   error = WriteHardwareDebugRegs(eDREGTypeBREAK, bp_index);
412 
413   if (error.Fail()) {
414     m_hbr_regs[bp_index].address = 0;
415     m_hbr_regs[bp_index].control &= ~1;
416 
417     return LLDB_INVALID_INDEX32;
418   }
419 
420   return bp_index;
421 }
422 
423 bool NativeRegisterContextLinux_arm::ClearHardwareBreakpoint(uint32_t hw_idx) {
424   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_BREAKPOINTS));
425   LLDB_LOG(log, "hw_idx: {0}", hw_idx);
426 
427   // Read hardware breakpoint and watchpoint information.
428   Status error = ReadHardwareDebugInfo();
429 
430   if (error.Fail())
431     return false;
432 
433   if (hw_idx >= m_max_hbp_supported)
434     return false;
435 
436   // Create a backup we can revert to in case of failure.
437   lldb::addr_t tempAddr = m_hbr_regs[hw_idx].address;
438   uint32_t tempControl = m_hbr_regs[hw_idx].control;
439 
440   m_hbr_regs[hw_idx].control &= ~1;
441   m_hbr_regs[hw_idx].address = 0;
442 
443   // PTRACE call to clear corresponding hardware breakpoint register.
444   error = WriteHardwareDebugRegs(eDREGTypeBREAK, hw_idx);
445 
446   if (error.Fail()) {
447     m_hbr_regs[hw_idx].control = tempControl;
448     m_hbr_regs[hw_idx].address = tempAddr;
449 
450     return false;
451   }
452 
453   return true;
454 }
455 
456 Status NativeRegisterContextLinux_arm::GetHardwareBreakHitIndex(
457     uint32_t &bp_index, lldb::addr_t trap_addr) {
458   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_BREAKPOINTS));
459 
460   LLDB_LOGF(log, "NativeRegisterContextLinux_arm64::%s()", __FUNCTION__);
461 
462   lldb::addr_t break_addr;
463 
464   for (bp_index = 0; bp_index < m_max_hbp_supported; ++bp_index) {
465     break_addr = m_hbr_regs[bp_index].address;
466 
467     if ((m_hbr_regs[bp_index].control & 0x1) && (trap_addr == break_addr)) {
468       m_hbr_regs[bp_index].hit_addr = trap_addr;
469       return Status();
470     }
471   }
472 
473   bp_index = LLDB_INVALID_INDEX32;
474   return Status();
475 }
476 
477 Status NativeRegisterContextLinux_arm::ClearAllHardwareBreakpoints() {
478   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_BREAKPOINTS));
479 
480   LLDB_LOGF(log, "NativeRegisterContextLinux_arm::%s()", __FUNCTION__);
481 
482   Status error;
483 
484   // Read hardware breakpoint and watchpoint information.
485   error = ReadHardwareDebugInfo();
486 
487   if (error.Fail())
488     return error;
489 
490   lldb::addr_t tempAddr = 0;
491   uint32_t tempControl = 0;
492 
493   for (uint32_t i = 0; i < m_max_hbp_supported; i++) {
494     if (m_hbr_regs[i].control & 0x01) {
495       // Create a backup we can revert to in case of failure.
496       tempAddr = m_hbr_regs[i].address;
497       tempControl = m_hbr_regs[i].control;
498 
499       // Clear breakpoints in local cache
500       m_hbr_regs[i].control &= ~1;
501       m_hbr_regs[i].address = 0;
502 
503       // Ptrace call to update hardware debug registers
504       error = WriteHardwareDebugRegs(eDREGTypeBREAK, i);
505 
506       if (error.Fail()) {
507         m_hbr_regs[i].control = tempControl;
508         m_hbr_regs[i].address = tempAddr;
509 
510         return error;
511       }
512     }
513   }
514 
515   return Status();
516 }
517 
518 uint32_t NativeRegisterContextLinux_arm::NumSupportedHardwareWatchpoints() {
519   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_WATCHPOINTS));
520 
521   // Read hardware breakpoint and watchpoint information.
522   Status error = ReadHardwareDebugInfo();
523 
524   if (error.Fail())
525     return 0;
526 
527   LLDB_LOG(log, "{0}", m_max_hwp_supported);
528   return m_max_hwp_supported;
529 }
530 
531 uint32_t NativeRegisterContextLinux_arm::SetHardwareWatchpoint(
532     lldb::addr_t addr, size_t size, uint32_t watch_flags) {
533   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_WATCHPOINTS));
534   LLDB_LOG(log, "addr: {0:x}, size: {1:x} watch_flags: {2:x}", addr, size,
535            watch_flags);
536 
537   // Read hardware breakpoint and watchpoint information.
538   Status error = ReadHardwareDebugInfo();
539 
540   if (error.Fail())
541     return LLDB_INVALID_INDEX32;
542 
543   uint32_t control_value = 0, wp_index = 0, addr_word_offset = 0, byte_mask = 0;
544   lldb::addr_t real_addr = addr;
545 
546   // Check if we are setting watchpoint other than read/write/access Also
547   // update watchpoint flag to match Arm write-read bit configuration.
548   switch (watch_flags) {
549   case 1:
550     watch_flags = 2;
551     break;
552   case 2:
553     watch_flags = 1;
554     break;
555   case 3:
556     break;
557   default:
558     return LLDB_INVALID_INDEX32;
559   }
560 
561   // Can't watch zero bytes
562   // Can't watch more than 4 bytes per WVR/WCR pair
563 
564   if (size == 0 || size > 4)
565     return LLDB_INVALID_INDEX32;
566 
567   // Check 4-byte alignment for hardware watchpoint target address. Below is a
568   // hack to recalculate address and size in order to make sure we can watch
569   // non 4-byte alligned addresses as well.
570   if (addr & 0x03) {
571     uint8_t watch_mask = (addr & 0x03) + size;
572 
573     if (watch_mask > 0x04)
574       return LLDB_INVALID_INDEX32;
575     else if (watch_mask <= 0x02)
576       size = 2;
577     else if (watch_mask <= 0x04)
578       size = 4;
579 
580     addr = addr & (~0x03);
581   }
582 
583   // We can only watch up to four bytes that follow a 4 byte aligned address
584   // per watchpoint register pair, so make sure we can properly encode this.
585   addr_word_offset = addr % 4;
586   byte_mask = ((1u << size) - 1u) << addr_word_offset;
587 
588   // Check if we need multiple watchpoint register
589   if (byte_mask > 0xfu)
590     return LLDB_INVALID_INDEX32;
591 
592   // Setup control value
593   // Make the byte_mask into a valid Byte Address Select mask
594   control_value = byte_mask << 5;
595 
596   // Turn on appropriate watchpoint flags read or write
597   control_value |= (watch_flags << 3);
598 
599   // Enable this watchpoint and make it stop in privileged or user mode;
600   control_value |= 7;
601 
602   // Make sure bits 1:0 are clear in our address
603   addr &= ~((lldb::addr_t)3);
604 
605   // Iterate over stored watchpoints and find a free wp_index
606   wp_index = LLDB_INVALID_INDEX32;
607   for (uint32_t i = 0; i < m_max_hwp_supported; i++) {
608     if ((m_hwp_regs[i].control & 1) == 0) {
609       wp_index = i; // Mark last free slot
610     } else if (m_hwp_regs[i].address == addr) {
611       return LLDB_INVALID_INDEX32; // We do not support duplicate watchpoints.
612     }
613   }
614 
615   if (wp_index == LLDB_INVALID_INDEX32)
616     return LLDB_INVALID_INDEX32;
617 
618   // Update watchpoint in local cache
619   m_hwp_regs[wp_index].real_addr = real_addr;
620   m_hwp_regs[wp_index].address = addr;
621   m_hwp_regs[wp_index].control = control_value;
622 
623   // PTRACE call to set corresponding watchpoint register.
624   error = WriteHardwareDebugRegs(eDREGTypeWATCH, wp_index);
625 
626   if (error.Fail()) {
627     m_hwp_regs[wp_index].address = 0;
628     m_hwp_regs[wp_index].control &= ~1;
629 
630     return LLDB_INVALID_INDEX32;
631   }
632 
633   return wp_index;
634 }
635 
636 bool NativeRegisterContextLinux_arm::ClearHardwareWatchpoint(
637     uint32_t wp_index) {
638   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_WATCHPOINTS));
639   LLDB_LOG(log, "wp_index: {0}", wp_index);
640 
641   // Read hardware breakpoint and watchpoint information.
642   Status error = ReadHardwareDebugInfo();
643 
644   if (error.Fail())
645     return false;
646 
647   if (wp_index >= m_max_hwp_supported)
648     return false;
649 
650   // Create a backup we can revert to in case of failure.
651   lldb::addr_t tempAddr = m_hwp_regs[wp_index].address;
652   uint32_t tempControl = m_hwp_regs[wp_index].control;
653 
654   // Update watchpoint in local cache
655   m_hwp_regs[wp_index].control &= ~1;
656   m_hwp_regs[wp_index].address = 0;
657 
658   // Ptrace call to update hardware debug registers
659   error = WriteHardwareDebugRegs(eDREGTypeWATCH, wp_index);
660 
661   if (error.Fail()) {
662     m_hwp_regs[wp_index].control = tempControl;
663     m_hwp_regs[wp_index].address = tempAddr;
664 
665     return false;
666   }
667 
668   return true;
669 }
670 
671 Status NativeRegisterContextLinux_arm::ClearAllHardwareWatchpoints() {
672   // Read hardware breakpoint and watchpoint information.
673   Status error = ReadHardwareDebugInfo();
674 
675   if (error.Fail())
676     return error;
677 
678   lldb::addr_t tempAddr = 0;
679   uint32_t tempControl = 0;
680 
681   for (uint32_t i = 0; i < m_max_hwp_supported; i++) {
682     if (m_hwp_regs[i].control & 0x01) {
683       // Create a backup we can revert to in case of failure.
684       tempAddr = m_hwp_regs[i].address;
685       tempControl = m_hwp_regs[i].control;
686 
687       // Clear watchpoints in local cache
688       m_hwp_regs[i].control &= ~1;
689       m_hwp_regs[i].address = 0;
690 
691       // Ptrace call to update hardware debug registers
692       error = WriteHardwareDebugRegs(eDREGTypeWATCH, i);
693 
694       if (error.Fail()) {
695         m_hwp_regs[i].control = tempControl;
696         m_hwp_regs[i].address = tempAddr;
697 
698         return error;
699       }
700     }
701   }
702 
703   return Status();
704 }
705 
706 uint32_t NativeRegisterContextLinux_arm::GetWatchpointSize(uint32_t wp_index) {
707   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_WATCHPOINTS));
708   LLDB_LOG(log, "wp_index: {0}", wp_index);
709 
710   switch ((m_hwp_regs[wp_index].control >> 5) & 0x0f) {
711   case 0x01:
712     return 1;
713   case 0x03:
714     return 2;
715   case 0x07:
716     return 3;
717   case 0x0f:
718     return 4;
719   default:
720     return 0;
721   }
722 }
723 bool NativeRegisterContextLinux_arm::WatchpointIsEnabled(uint32_t wp_index) {
724   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_WATCHPOINTS));
725   LLDB_LOG(log, "wp_index: {0}", wp_index);
726 
727   if ((m_hwp_regs[wp_index].control & 0x1) == 0x1)
728     return true;
729   else
730     return false;
731 }
732 
733 Status
734 NativeRegisterContextLinux_arm::GetWatchpointHitIndex(uint32_t &wp_index,
735                                                       lldb::addr_t trap_addr) {
736   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_WATCHPOINTS));
737   LLDB_LOG(log, "wp_index: {0}, trap_addr: {1:x}", wp_index, trap_addr);
738 
739   uint32_t watch_size;
740   lldb::addr_t watch_addr;
741 
742   for (wp_index = 0; wp_index < m_max_hwp_supported; ++wp_index) {
743     watch_size = GetWatchpointSize(wp_index);
744     watch_addr = m_hwp_regs[wp_index].address;
745 
746     if (WatchpointIsEnabled(wp_index) && trap_addr >= watch_addr &&
747         trap_addr < watch_addr + watch_size) {
748       m_hwp_regs[wp_index].hit_addr = trap_addr;
749       return Status();
750     }
751   }
752 
753   wp_index = LLDB_INVALID_INDEX32;
754   return Status();
755 }
756 
757 lldb::addr_t
758 NativeRegisterContextLinux_arm::GetWatchpointAddress(uint32_t wp_index) {
759   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_WATCHPOINTS));
760   LLDB_LOG(log, "wp_index: {0}", wp_index);
761 
762   if (wp_index >= m_max_hwp_supported)
763     return LLDB_INVALID_ADDRESS;
764 
765   if (WatchpointIsEnabled(wp_index))
766     return m_hwp_regs[wp_index].real_addr;
767   else
768     return LLDB_INVALID_ADDRESS;
769 }
770 
771 lldb::addr_t
772 NativeRegisterContextLinux_arm::GetWatchpointHitAddress(uint32_t wp_index) {
773   Log *log(ProcessPOSIXLog::GetLogIfAllCategoriesSet(POSIX_LOG_WATCHPOINTS));
774   LLDB_LOG(log, "wp_index: {0}", wp_index);
775 
776   if (wp_index >= m_max_hwp_supported)
777     return LLDB_INVALID_ADDRESS;
778 
779   if (WatchpointIsEnabled(wp_index))
780     return m_hwp_regs[wp_index].hit_addr;
781   else
782     return LLDB_INVALID_ADDRESS;
783 }
784 
785 Status NativeRegisterContextLinux_arm::ReadHardwareDebugInfo() {
786   Status error;
787 
788   if (!m_refresh_hwdebug_info) {
789     return Status();
790   }
791 
792   unsigned int cap_val;
793 
794   error = NativeProcessLinux::PtraceWrapper(PTRACE_GETHBPREGS, m_thread.GetID(),
795                                             nullptr, &cap_val,
796                                             sizeof(unsigned int));
797 
798   if (error.Fail())
799     return error;
800 
801   m_max_hwp_supported = (cap_val >> 8) & 0xff;
802   m_max_hbp_supported = cap_val & 0xff;
803   m_refresh_hwdebug_info = false;
804 
805   return error;
806 }
807 
808 Status NativeRegisterContextLinux_arm::WriteHardwareDebugRegs(int hwbType,
809                                                               int hwb_index) {
810   Status error;
811 
812   lldb::addr_t *addr_buf;
813   uint32_t *ctrl_buf;
814 
815   if (hwbType == eDREGTypeWATCH) {
816     addr_buf = &m_hwp_regs[hwb_index].address;
817     ctrl_buf = &m_hwp_regs[hwb_index].control;
818 
819     error = NativeProcessLinux::PtraceWrapper(
820         PTRACE_SETHBPREGS, m_thread.GetID(),
821         (PTRACE_TYPE_ARG3)(intptr_t) - ((hwb_index << 1) + 1), addr_buf,
822         sizeof(unsigned int));
823 
824     if (error.Fail())
825       return error;
826 
827     error = NativeProcessLinux::PtraceWrapper(
828         PTRACE_SETHBPREGS, m_thread.GetID(),
829         (PTRACE_TYPE_ARG3)(intptr_t) - ((hwb_index << 1) + 2), ctrl_buf,
830         sizeof(unsigned int));
831   } else {
832     addr_buf = &m_hbr_regs[hwb_index].address;
833     ctrl_buf = &m_hbr_regs[hwb_index].control;
834 
835     error = NativeProcessLinux::PtraceWrapper(
836         PTRACE_SETHBPREGS, m_thread.GetID(),
837         (PTRACE_TYPE_ARG3)(intptr_t)((hwb_index << 1) + 1), addr_buf,
838         sizeof(unsigned int));
839 
840     if (error.Fail())
841       return error;
842 
843     error = NativeProcessLinux::PtraceWrapper(
844         PTRACE_SETHBPREGS, m_thread.GetID(),
845         (PTRACE_TYPE_ARG3)(intptr_t)((hwb_index << 1) + 2), ctrl_buf,
846         sizeof(unsigned int));
847   }
848 
849   return error;
850 }
851 
852 uint32_t NativeRegisterContextLinux_arm::CalculateFprOffset(
853     const RegisterInfo *reg_info) const {
854   return reg_info->byte_offset -
855          GetRegisterInfoAtIndex(m_reg_info.first_fpr)->byte_offset;
856 }
857 
858 Status NativeRegisterContextLinux_arm::DoReadRegisterValue(
859     uint32_t offset, const char *reg_name, uint32_t size,
860     RegisterValue &value) {
861   // PTRACE_PEEKUSER don't work in the aarch64 linux kernel used on android
862   // devices (always return "Bad address"). To avoid using PTRACE_PEEKUSER we
863   // read out the full GPR register set instead. This approach is about 4 times
864   // slower but the performance overhead is negligible in comparision to
865   // processing time in lldb-server.
866   assert(offset % 4 == 0 && "Try to write a register with unaligned offset");
867   if (offset + sizeof(uint32_t) > sizeof(m_gpr_arm))
868     return Status("Register isn't fit into the size of the GPR area");
869 
870   Status error = ReadGPR();
871   if (error.Fail())
872     return error;
873 
874   value.SetUInt32(m_gpr_arm[offset / sizeof(uint32_t)]);
875   return Status();
876 }
877 
878 Status NativeRegisterContextLinux_arm::DoWriteRegisterValue(
879     uint32_t offset, const char *reg_name, const RegisterValue &value) {
880   // PTRACE_POKEUSER don't work in the aarch64 linux kernel used on android
881   // devices (always return "Bad address"). To avoid using PTRACE_POKEUSER we
882   // read out the full GPR register set, modify the requested register and
883   // write it back. This approach is about 4 times slower but the performance
884   // overhead is negligible in comparision to processing time in lldb-server.
885   assert(offset % 4 == 0 && "Try to write a register with unaligned offset");
886   if (offset + sizeof(uint32_t) > sizeof(m_gpr_arm))
887     return Status("Register isn't fit into the size of the GPR area");
888 
889   Status error = ReadGPR();
890   if (error.Fail())
891     return error;
892 
893   uint32_t reg_value = value.GetAsUInt32();
894   // As precaution for an undefined behavior encountered while setting PC we
895   // will clear thumb bit of new PC if we are already in thumb mode; that is
896   // CPSR thumb mode bit is set.
897   if (offset / sizeof(uint32_t) == gpr_pc_arm) {
898     // Check if we are already in thumb mode and thumb bit of current PC is
899     // read out to be zero and thumb bit of next PC is read out to be one.
900     if ((m_gpr_arm[gpr_cpsr_arm] & 0x20) && !(m_gpr_arm[gpr_pc_arm] & 0x01) &&
901         (value.GetAsUInt32() & 0x01)) {
902       reg_value &= (~1ull);
903     }
904   }
905 
906   m_gpr_arm[offset / sizeof(uint32_t)] = reg_value;
907   return WriteGPR();
908 }
909 
910 Status NativeRegisterContextLinux_arm::ReadGPR() {
911 #ifdef __arm__
912   return NativeRegisterContextLinux::ReadGPR();
913 #else  // __aarch64__
914   struct iovec ioVec;
915   ioVec.iov_base = GetGPRBuffer();
916   ioVec.iov_len = GetGPRSize();
917 
918   return ReadRegisterSet(&ioVec, GetGPRSize(), NT_PRSTATUS);
919 #endif // __arm__
920 }
921 
922 Status NativeRegisterContextLinux_arm::WriteGPR() {
923 #ifdef __arm__
924   return NativeRegisterContextLinux::WriteGPR();
925 #else  // __aarch64__
926   struct iovec ioVec;
927   ioVec.iov_base = GetGPRBuffer();
928   ioVec.iov_len = GetGPRSize();
929 
930   return WriteRegisterSet(&ioVec, GetGPRSize(), NT_PRSTATUS);
931 #endif // __arm__
932 }
933 
934 Status NativeRegisterContextLinux_arm::ReadFPR() {
935 #ifdef __arm__
936   return NativeProcessLinux::PtraceWrapper(PTRACE_GETVFPREGS, m_thread.GetID(),
937                                            nullptr, GetFPRBuffer(),
938                                            GetFPRSize());
939 #else  // __aarch64__
940   struct iovec ioVec;
941   ioVec.iov_base = GetFPRBuffer();
942   ioVec.iov_len = GetFPRSize();
943 
944   return ReadRegisterSet(&ioVec, GetFPRSize(), NT_ARM_VFP);
945 #endif // __arm__
946 }
947 
948 Status NativeRegisterContextLinux_arm::WriteFPR() {
949 #ifdef __arm__
950   return NativeProcessLinux::PtraceWrapper(PTRACE_SETVFPREGS, m_thread.GetID(),
951                                            nullptr, GetFPRBuffer(),
952                                            GetFPRSize());
953 #else  // __aarch64__
954   struct iovec ioVec;
955   ioVec.iov_base = GetFPRBuffer();
956   ioVec.iov_len = GetFPRSize();
957 
958   return WriteRegisterSet(&ioVec, GetFPRSize(), NT_ARM_VFP);
959 #endif // __arm__
960 }
961 
962 #endif // defined(__arm__) || defined(__arm64__) || defined(__aarch64__)
963