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