1 //===-- DNBArchImpl.cpp -----------------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  Created by Greg Clayton on 6/25/07.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #if defined (__arm__) || defined (__arm64__) || defined (__aarch64__)
15 
16 #include "MacOSX/arm/DNBArchImpl.h"
17 #include "MacOSX/MachProcess.h"
18 #include "MacOSX/MachThread.h"
19 #include "DNBBreakpoint.h"
20 #include "DNBLog.h"
21 #include "DNBRegisterInfo.h"
22 #include "DNB.h"
23 #include "ARM_GCC_Registers.h"
24 #include "ARM_DWARF_Registers.h"
25 
26 #include <inttypes.h>
27 #include <sys/sysctl.h>
28 
29 // BCR address match type
30 #define BCR_M_IMVA_MATCH        ((uint32_t)(0u << 21))
31 #define BCR_M_CONTEXT_ID_MATCH  ((uint32_t)(1u << 21))
32 #define BCR_M_IMVA_MISMATCH     ((uint32_t)(2u << 21))
33 #define BCR_M_RESERVED          ((uint32_t)(3u << 21))
34 
35 // Link a BVR/BCR or WVR/WCR pair to another
36 #define E_ENABLE_LINKING        ((uint32_t)(1u << 20))
37 
38 // Byte Address Select
39 #define BAS_IMVA_PLUS_0         ((uint32_t)(1u << 5))
40 #define BAS_IMVA_PLUS_1         ((uint32_t)(1u << 6))
41 #define BAS_IMVA_PLUS_2         ((uint32_t)(1u << 7))
42 #define BAS_IMVA_PLUS_3         ((uint32_t)(1u << 8))
43 #define BAS_IMVA_0_1            ((uint32_t)(3u << 5))
44 #define BAS_IMVA_2_3            ((uint32_t)(3u << 7))
45 #define BAS_IMVA_ALL            ((uint32_t)(0xfu << 5))
46 
47 // Break only in privileged or user mode
48 #define S_RSVD                  ((uint32_t)(0u << 1))
49 #define S_PRIV                  ((uint32_t)(1u << 1))
50 #define S_USER                  ((uint32_t)(2u << 1))
51 #define S_PRIV_USER             ((S_PRIV) | (S_USER))
52 
53 #define BCR_ENABLE              ((uint32_t)(1u))
54 #define WCR_ENABLE              ((uint32_t)(1u))
55 
56 // Watchpoint load/store
57 #define WCR_LOAD                ((uint32_t)(1u << 3))
58 #define WCR_STORE               ((uint32_t)(1u << 4))
59 
60 // Definitions for the Debug Status and Control Register fields:
61 // [5:2] => Method of debug entry
62 //#define WATCHPOINT_OCCURRED     ((uint32_t)(2u))
63 // I'm seeing this, instead.
64 #define WATCHPOINT_OCCURRED     ((uint32_t)(10u))
65 
66 // 0xE120BE70
67 static const uint8_t g_arm_breakpoint_opcode[] = { 0x70, 0xBE, 0x20, 0xE1 };
68 static const uint8_t g_thumb_breakpoint_opcode[] = { 0x70, 0xBE };
69 
70 // A watchpoint may need to be implemented using two watchpoint registers.
71 // e.g. watching an 8-byte region when the device can only watch 4-bytes.
72 //
73 // This stores the lo->hi mappings.  It's safe to initialize to all 0's
74 // since hi > lo and therefore LoHi[i] cannot be 0.
75 static uint32_t LoHi[16] = { 0 };
76 
77 // ARM constants used during decoding
78 #define REG_RD          0
79 #define LDM_REGLIST     1
80 #define PC_REG          15
81 #define PC_REGLIST_BIT  0x8000
82 
83 // ARM conditions
84 #define COND_EQ     0x0
85 #define COND_NE     0x1
86 #define COND_CS     0x2
87 #define COND_HS     0x2
88 #define COND_CC     0x3
89 #define COND_LO     0x3
90 #define COND_MI     0x4
91 #define COND_PL     0x5
92 #define COND_VS     0x6
93 #define COND_VC     0x7
94 #define COND_HI     0x8
95 #define COND_LS     0x9
96 #define COND_GE     0xA
97 #define COND_LT     0xB
98 #define COND_GT     0xC
99 #define COND_LE     0xD
100 #define COND_AL     0xE
101 #define COND_UNCOND 0xF
102 
103 #define MASK_CPSR_T (1u << 5)
104 #define MASK_CPSR_J (1u << 24)
105 
106 #define MNEMONIC_STRING_SIZE 32
107 #define OPERAND_STRING_SIZE 128
108 
109 // Returns true if the first 16 bit opcode of a thumb instruction indicates
110 // the instruction will be a 32 bit thumb opcode
111 static bool
112 IsThumb32Opcode (uint16_t opcode)
113 {
114     if (((opcode & 0xE000) == 0xE000) && (opcode & 0x1800))
115         return true;
116     return false;
117 }
118 
119 void
120 DNBArchMachARM::Initialize()
121 {
122     DNBArchPluginInfo arch_plugin_info =
123     {
124         CPU_TYPE_ARM,
125         DNBArchMachARM::Create,
126         DNBArchMachARM::GetRegisterSetInfo,
127         DNBArchMachARM::SoftwareBreakpointOpcode
128     };
129 
130     // Register this arch plug-in with the main protocol class
131     DNBArchProtocol::RegisterArchPlugin (arch_plugin_info);
132 }
133 
134 
135 DNBArchProtocol *
136 DNBArchMachARM::Create (MachThread *thread)
137 {
138     DNBArchMachARM *obj = new DNBArchMachARM (thread);
139     return obj;
140 }
141 
142 const uint8_t * const
143 DNBArchMachARM::SoftwareBreakpointOpcode (nub_size_t byte_size)
144 {
145     switch (byte_size)
146     {
147     case 2: return g_thumb_breakpoint_opcode;
148     case 4: return g_arm_breakpoint_opcode;
149     }
150     return NULL;
151 }
152 
153 uint32_t
154 DNBArchMachARM::GetCPUType()
155 {
156     return CPU_TYPE_ARM;
157 }
158 
159 uint64_t
160 DNBArchMachARM::GetPC(uint64_t failValue)
161 {
162     // Get program counter
163     if (GetGPRState(false) == KERN_SUCCESS)
164         return m_state.context.gpr.__pc;
165     return failValue;
166 }
167 
168 kern_return_t
169 DNBArchMachARM::SetPC(uint64_t value)
170 {
171     // Get program counter
172     kern_return_t err = GetGPRState(false);
173     if (err == KERN_SUCCESS)
174     {
175         m_state.context.gpr.__pc = (uint32_t) value;
176         err = SetGPRState();
177     }
178     return err == KERN_SUCCESS;
179 }
180 
181 uint64_t
182 DNBArchMachARM::GetSP(uint64_t failValue)
183 {
184     // Get stack pointer
185     if (GetGPRState(false) == KERN_SUCCESS)
186         return m_state.context.gpr.__sp;
187     return failValue;
188 }
189 
190 kern_return_t
191 DNBArchMachARM::GetGPRState(bool force)
192 {
193     int set = e_regSetGPR;
194     // Check if we have valid cached registers
195     if (!force && m_state.GetError(set, Read) == KERN_SUCCESS)
196         return KERN_SUCCESS;
197 
198     // Read the registers from our thread
199     mach_msg_type_number_t count = ARM_THREAD_STATE_COUNT;
200     kern_return_t kret = ::thread_get_state(m_thread->MachPortNumber(), ARM_THREAD_STATE, (thread_state_t)&m_state.context.gpr, &count);
201     uint32_t *r = &m_state.context.gpr.__r[0];
202     DNBLogThreadedIf(LOG_THREAD, "thread_get_state(0x%4.4x, %u, &gpr, %u) => 0x%8.8x (count = %u) regs r0=%8.8x r1=%8.8x r2=%8.8x r3=%8.8x r4=%8.8x r5=%8.8x r6=%8.8x r7=%8.8x r8=%8.8x r9=%8.8x r10=%8.8x r11=%8.8x s12=%8.8x sp=%8.8x lr=%8.8x pc=%8.8x cpsr=%8.8x",
203                      m_thread->MachPortNumber(),
204                      ARM_THREAD_STATE,
205                      ARM_THREAD_STATE_COUNT,
206                      kret,
207                      count,
208                      r[0],
209                      r[1],
210                      r[2],
211                      r[3],
212                      r[4],
213                      r[5],
214                      r[6],
215                      r[7],
216                      r[8],
217                      r[9],
218                      r[10],
219                      r[11],
220                      r[12],
221                      r[13],
222                      r[14],
223                      r[15],
224                      r[16]);
225     m_state.SetError(set, Read, kret);
226     return kret;
227 }
228 
229 kern_return_t
230 DNBArchMachARM::GetVFPState(bool force)
231 {
232     int set = e_regSetVFP;
233     // Check if we have valid cached registers
234     if (!force && m_state.GetError(set, Read) == KERN_SUCCESS)
235         return KERN_SUCCESS;
236 
237     // Read the registers from our thread
238     mach_msg_type_number_t count = ARM_VFP_STATE_COUNT;
239     kern_return_t kret = ::thread_get_state(m_thread->MachPortNumber(), ARM_VFP_STATE, (thread_state_t)&m_state.context.vfp, &count);
240     if (DNBLogEnabledForAny (LOG_THREAD))
241     {
242         uint32_t *r = &m_state.context.vfp.__r[0];
243         DNBLogThreaded ("thread_get_state(0x%4.4x, %u, &gpr, %u) => 0x%8.8x (count => %u)",
244                         m_thread->MachPortNumber(),
245                         ARM_THREAD_STATE,
246                         ARM_THREAD_STATE_COUNT,
247                         kret,
248                         count);
249         DNBLogThreaded("   s0=%8.8x  s1=%8.8x  s2=%8.8x  s3=%8.8x  s4=%8.8x  s5=%8.8x  s6=%8.8x  s7=%8.8x",r[ 0],r[ 1],r[ 2],r[ 3],r[ 4],r[ 5],r[ 6],r[ 7]);
250         DNBLogThreaded("   s8=%8.8x  s9=%8.8x s10=%8.8x s11=%8.8x s12=%8.8x s13=%8.8x s14=%8.8x s15=%8.8x",r[ 8],r[ 9],r[10],r[11],r[12],r[13],r[14],r[15]);
251         DNBLogThreaded("  s16=%8.8x s17=%8.8x s18=%8.8x s19=%8.8x s20=%8.8x s21=%8.8x s22=%8.8x s23=%8.8x",r[16],r[17],r[18],r[19],r[20],r[21],r[22],r[23]);
252         DNBLogThreaded("  s24=%8.8x s25=%8.8x s26=%8.8x s27=%8.8x s28=%8.8x s29=%8.8x s30=%8.8x s31=%8.8x",r[24],r[25],r[26],r[27],r[28],r[29],r[30],r[31]);
253         DNBLogThreaded("  s32=%8.8x s33=%8.8x s34=%8.8x s35=%8.8x s36=%8.8x s37=%8.8x s38=%8.8x s39=%8.8x",r[32],r[33],r[34],r[35],r[36],r[37],r[38],r[39]);
254         DNBLogThreaded("  s40=%8.8x s41=%8.8x s42=%8.8x s43=%8.8x s44=%8.8x s45=%8.8x s46=%8.8x s47=%8.8x",r[40],r[41],r[42],r[43],r[44],r[45],r[46],r[47]);
255         DNBLogThreaded("  s48=%8.8x s49=%8.8x s50=%8.8x s51=%8.8x s52=%8.8x s53=%8.8x s54=%8.8x s55=%8.8x",r[48],r[49],r[50],r[51],r[52],r[53],r[54],r[55]);
256         DNBLogThreaded("  s56=%8.8x s57=%8.8x s58=%8.8x s59=%8.8x s60=%8.8x s61=%8.8x s62=%8.8x s63=%8.8x fpscr=%8.8x",r[56],r[57],r[58],r[59],r[60],r[61],r[62],r[63],r[64]);
257     }
258     m_state.SetError(set, Read, kret);
259     return kret;
260 }
261 
262 kern_return_t
263 DNBArchMachARM::GetEXCState(bool force)
264 {
265     int set = e_regSetEXC;
266     // Check if we have valid cached registers
267     if (!force && m_state.GetError(set, Read) == KERN_SUCCESS)
268         return KERN_SUCCESS;
269 
270     // Read the registers from our thread
271     mach_msg_type_number_t count = ARM_EXCEPTION_STATE_COUNT;
272     kern_return_t kret = ::thread_get_state(m_thread->MachPortNumber(), ARM_EXCEPTION_STATE, (thread_state_t)&m_state.context.exc, &count);
273     m_state.SetError(set, Read, kret);
274     return kret;
275 }
276 
277 static void
278 DumpDBGState(const DNBArchMachARM::DBG& dbg)
279 {
280     uint32_t i = 0;
281     for (i=0; i<16; i++)
282     {
283         DNBLogThreadedIf(LOG_STEP, "BVR%-2u/BCR%-2u = { 0x%8.8x, 0x%8.8x } WVR%-2u/WCR%-2u = { 0x%8.8x, 0x%8.8x }",
284             i, i, dbg.__bvr[i], dbg.__bcr[i],
285             i, i, dbg.__wvr[i], dbg.__wcr[i]);
286     }
287 }
288 
289 kern_return_t
290 DNBArchMachARM::GetDBGState(bool force)
291 {
292     int set = e_regSetDBG;
293 
294     // Check if we have valid cached registers
295     if (!force && m_state.GetError(set, Read) == KERN_SUCCESS)
296         return KERN_SUCCESS;
297 
298     // Read the registers from our thread
299 #if defined (ARM_DEBUG_STATE32) && (defined (__arm64__) || defined (__aarch64__))
300     mach_msg_type_number_t count = ARM_DEBUG_STATE32_COUNT;
301     kern_return_t kret = ::thread_get_state(m_thread->MachPortNumber(), ARM_DEBUG_STATE32, (thread_state_t)&m_state.dbg, &count);
302 #else
303     mach_msg_type_number_t count = ARM_DEBUG_STATE_COUNT;
304     kern_return_t kret = ::thread_get_state(m_thread->MachPortNumber(), ARM_DEBUG_STATE, (thread_state_t)&m_state.dbg, &count);
305 #endif
306     m_state.SetError(set, Read, kret);
307 
308     return kret;
309 }
310 
311 kern_return_t
312 DNBArchMachARM::SetGPRState()
313 {
314     int set = e_regSetGPR;
315     kern_return_t kret = ::thread_set_state(m_thread->MachPortNumber(), ARM_THREAD_STATE, (thread_state_t)&m_state.context.gpr, ARM_THREAD_STATE_COUNT);
316     m_state.SetError(set, Write, kret);         // Set the current write error for this register set
317     m_state.InvalidateRegisterSetState(set);    // Invalidate the current register state in case registers are read back differently
318     return kret;                                // Return the error code
319 }
320 
321 kern_return_t
322 DNBArchMachARM::SetVFPState()
323 {
324     int set = e_regSetVFP;
325     kern_return_t kret = ::thread_set_state (m_thread->MachPortNumber(), ARM_VFP_STATE, (thread_state_t)&m_state.context.vfp, ARM_VFP_STATE_COUNT);
326     m_state.SetError(set, Write, kret);         // Set the current write error for this register set
327     m_state.InvalidateRegisterSetState(set);    // Invalidate the current register state in case registers are read back differently
328     return kret;                                // Return the error code
329 }
330 
331 kern_return_t
332 DNBArchMachARM::SetEXCState()
333 {
334     int set = e_regSetEXC;
335     kern_return_t kret = ::thread_set_state (m_thread->MachPortNumber(), ARM_EXCEPTION_STATE, (thread_state_t)&m_state.context.exc, ARM_EXCEPTION_STATE_COUNT);
336     m_state.SetError(set, Write, kret);         // Set the current write error for this register set
337     m_state.InvalidateRegisterSetState(set);    // Invalidate the current register state in case registers are read back differently
338     return kret;                                // Return the error code
339 }
340 
341 kern_return_t
342 DNBArchMachARM::SetDBGState(bool also_set_on_task)
343 {
344     int set = e_regSetDBG;
345 #if defined (ARM_DEBUG_STATE32) && (defined (__arm64__) || defined (__aarch64__))
346     kern_return_t kret = ::thread_set_state (m_thread->MachPortNumber(), ARM_DEBUG_STATE32, (thread_state_t)&m_state.dbg, ARM_DEBUG_STATE32_COUNT);
347     if (also_set_on_task)
348     {
349         kern_return_t task_kret = ::task_set_state (m_thread->Process()->Task().TaskPort(), ARM_DEBUG_STATE32, (thread_state_t)&m_state.dbg, ARM_DEBUG_STATE32_COUNT);
350         if (task_kret != KERN_SUCCESS)
351              DNBLogThreadedIf(LOG_WATCHPOINTS, "DNBArchMachARM::SetDBGState failed to set debug control register state: 0x%8.8x.", kret);
352     }
353 #else
354     kern_return_t kret = ::thread_set_state (m_thread->MachPortNumber(), ARM_DEBUG_STATE, (thread_state_t)&m_state.dbg, ARM_DEBUG_STATE_COUNT);
355     if (also_set_on_task)
356     {
357         kern_return_t task_kret = ::task_set_state (m_thread->Process()->Task().TaskPort(), ARM_DEBUG_STATE, (thread_state_t)&m_state.dbg, ARM_DEBUG_STATE_COUNT);
358         if (task_kret != KERN_SUCCESS)
359              DNBLogThreadedIf(LOG_WATCHPOINTS, "DNBArchMachARM::SetDBGState failed to set debug control register state: 0x%8.8x.", kret);
360     }
361 #endif
362 
363     m_state.SetError(set, Write, kret);         // Set the current write error for this register set
364     m_state.InvalidateRegisterSetState(set);    // Invalidate the current register state in case registers are read back differently
365     return kret;                                // Return the error code
366 }
367 
368 void
369 DNBArchMachARM::ThreadWillResume()
370 {
371     // Do we need to step this thread? If so, let the mach thread tell us so.
372     if (m_thread->IsStepping())
373     {
374         // This is the primary thread, let the arch do anything it needs
375         if (NumSupportedHardwareBreakpoints() > 0)
376         {
377             if (EnableHardwareSingleStep(true) != KERN_SUCCESS)
378             {
379                 DNBLogThreaded("DNBArchMachARM::ThreadWillResume() failed to enable hardware single step");
380             }
381         }
382     }
383 
384     // Disable the triggered watchpoint temporarily before we resume.
385     // Plus, we try to enable hardware single step to execute past the instruction which triggered our watchpoint.
386     if (m_watchpoint_did_occur)
387     {
388         if (m_watchpoint_hw_index >= 0)
389         {
390             kern_return_t kret = GetDBGState(false);
391             if (kret == KERN_SUCCESS && !IsWatchpointEnabled(m_state.dbg, m_watchpoint_hw_index)) {
392                 // The watchpoint might have been disabled by the user.  We don't need to do anything at all
393                 // to enable hardware single stepping.
394                 m_watchpoint_did_occur = false;
395                 m_watchpoint_hw_index = -1;
396                 return;
397             }
398 
399             DisableHardwareWatchpoint(m_watchpoint_hw_index, false);
400             DNBLogThreadedIf(LOG_WATCHPOINTS, "DNBArchMachARM::ThreadWillResume() DisableHardwareWatchpoint(%d) called",
401                              m_watchpoint_hw_index);
402 
403             // Enable hardware single step to move past the watchpoint-triggering instruction.
404             m_watchpoint_resume_single_step_enabled = (EnableHardwareSingleStep(true) == KERN_SUCCESS);
405 
406             // If we are not able to enable single step to move past the watchpoint-triggering instruction,
407             // at least we should reset the two watchpoint member variables so that the next time around
408             // this callback function is invoked, the enclosing logical branch is skipped.
409             if (!m_watchpoint_resume_single_step_enabled) {
410                 // Reset the two watchpoint member variables.
411                 m_watchpoint_did_occur = false;
412                 m_watchpoint_hw_index = -1;
413                 DNBLogThreadedIf(LOG_WATCHPOINTS, "DNBArchMachARM::ThreadWillResume() failed to enable single step");
414             }
415             else
416                 DNBLogThreadedIf(LOG_WATCHPOINTS, "DNBArchMachARM::ThreadWillResume() succeeded to enable single step");
417         }
418     }
419 }
420 
421 bool
422 DNBArchMachARM::ThreadDidStop()
423 {
424     bool success = true;
425 
426     m_state.InvalidateRegisterSetState (e_regSetALL);
427 
428     if (m_watchpoint_resume_single_step_enabled)
429     {
430         // Great!  We now disable the hardware single step as well as re-enable the hardware watchpoint.
431         // See also ThreadWillResume().
432         if (EnableHardwareSingleStep(false) == KERN_SUCCESS)
433         {
434             if (m_watchpoint_did_occur && m_watchpoint_hw_index >= 0)
435             {
436                 ReenableHardwareWatchpoint(m_watchpoint_hw_index);
437                 m_watchpoint_resume_single_step_enabled = false;
438                 m_watchpoint_did_occur = false;
439                 m_watchpoint_hw_index = -1;
440             }
441             else
442             {
443                 DNBLogError("internal error detected: m_watchpoint_resume_step_enabled is true but (m_watchpoint_did_occur && m_watchpoint_hw_index >= 0) does not hold!");
444             }
445         }
446         else
447         {
448             DNBLogError("internal error detected: m_watchpoint_resume_step_enabled is true but unable to disable single step!");
449         }
450     }
451 
452     // Are we stepping a single instruction?
453     if (GetGPRState(true) == KERN_SUCCESS)
454     {
455         // We are single stepping, was this the primary thread?
456         if (m_thread->IsStepping())
457         {
458             success = EnableHardwareSingleStep(false) == KERN_SUCCESS;
459         }
460         else
461         {
462             // The MachThread will automatically restore the suspend count
463             // in ThreadDidStop(), so we don't need to do anything here if
464             // we weren't the primary thread the last time
465         }
466     }
467     return success;
468 }
469 
470 bool
471 DNBArchMachARM::NotifyException(MachException::Data& exc)
472 {
473     switch (exc.exc_type)
474     {
475         default:
476             break;
477         case EXC_BREAKPOINT:
478             if (exc.exc_data.size() == 2 && exc.exc_data[0] == EXC_ARM_DA_DEBUG)
479             {
480                 // The data break address is passed as exc_data[1].
481                 nub_addr_t addr = exc.exc_data[1];
482                 // Find the hardware index with the side effect of possibly massaging the
483                 // addr to return the starting address as seen from the debugger side.
484                 uint32_t hw_index = GetHardwareWatchpointHit(addr);
485                 DNBLogThreadedIf(LOG_WATCHPOINTS, "DNBArchMachARM::NotifyException watchpoint %d was hit on address 0x%llx", hw_index, (uint64_t) addr);
486                 const int num_watchpoints = NumSupportedHardwareWatchpoints ();
487                 for (int i = 0; i < num_watchpoints; i++)
488                 {
489                     if (LoHi[i] != 0
490                         && LoHi[i] == hw_index
491                         && LoHi[i] != i
492                         && GetWatchpointAddressByIndex (i) != INVALID_NUB_ADDRESS)
493                     {
494                         addr = GetWatchpointAddressByIndex (i);
495                         DNBLogThreadedIf(LOG_WATCHPOINTS, "DNBArchMachARM::NotifyException It is a linked watchpoint; rewritten to index %d addr 0x%llx", LoHi[i], (uint64_t) addr);
496                     }
497                 }
498                 if (hw_index != INVALID_NUB_HW_INDEX)
499                 {
500                     m_watchpoint_did_occur = true;
501                     m_watchpoint_hw_index = hw_index;
502                     exc.exc_data[1] = addr;
503                     // Piggyback the hw_index in the exc.data.
504                     exc.exc_data.push_back(hw_index);
505                 }
506 
507                 return true;
508             }
509             break;
510     }
511     return false;
512 }
513 
514 bool
515 DNBArchMachARM::StepNotComplete ()
516 {
517     if (m_hw_single_chained_step_addr != INVALID_NUB_ADDRESS)
518     {
519         kern_return_t kret = KERN_INVALID_ARGUMENT;
520         kret = GetGPRState(false);
521         if (kret == KERN_SUCCESS)
522         {
523             if (m_state.context.gpr.__pc == m_hw_single_chained_step_addr)
524             {
525                 DNBLogThreadedIf(LOG_STEP, "Need to step some more at 0x%8.8llx", (uint64_t) m_hw_single_chained_step_addr);
526                 return true;
527             }
528         }
529     }
530 
531     m_hw_single_chained_step_addr = INVALID_NUB_ADDRESS;
532     return false;
533 }
534 
535 // Set the single step bit in the processor status register.
536 kern_return_t
537 DNBArchMachARM::EnableHardwareSingleStep (bool enable)
538 {
539     DNBError err;
540     DNBLogThreadedIf(LOG_STEP, "%s( enable = %d )", __FUNCTION__, enable);
541 
542     err = GetGPRState(false);
543 
544     if (err.Fail())
545     {
546         err.LogThreaded("%s: failed to read the GPR registers", __FUNCTION__);
547         return err.Error();
548     }
549 
550     err = GetDBGState(false);
551 
552     if (err.Fail())
553     {
554         err.LogThreaded("%s: failed to read the DBG registers", __FUNCTION__);
555         return err.Error();
556     }
557 
558 // The use of __arm64__ here is not ideal.  If debugserver is running on
559 // an armv8 device, regardless of whether it was built for arch arm or arch arm64,
560 // it needs to use the MDSCR_EL1 SS bit to single instruction step.
561 
562 #if defined (__arm64__) || defined (__aarch64__)
563     if (enable)
564     {
565         DNBLogThreadedIf(LOG_STEP, "%s: Setting MDSCR_EL1 Single Step bit at pc 0x%llx", __FUNCTION__, (uint64_t) m_state.context.gpr.__pc);
566         m_state.dbg.__mdscr_el1 |= 1;  // Set bit 0 (single step, SS) in the MDSCR_EL1.
567     }
568     else
569     {
570         DNBLogThreadedIf(LOG_STEP, "%s: Clearing MDSCR_EL1 Single Step bit at pc 0x%llx", __FUNCTION__, (uint64_t) m_state.context.gpr.__pc);
571         m_state.dbg.__mdscr_el1 &= ~(1ULL);  // Clear bit 0 (single step, SS) in the MDSCR_EL1.
572     }
573 #else
574     const uint32_t i = 0;
575     if (enable)
576     {
577         m_hw_single_chained_step_addr = INVALID_NUB_ADDRESS;
578 
579         // Save our previous state
580         m_dbg_save = m_state.dbg;
581         // Set a breakpoint that will stop when the PC doesn't match the current one!
582         m_state.dbg.__bvr[i] = m_state.context.gpr.__pc & 0xFFFFFFFCu;      // Set the current PC as the breakpoint address
583         m_state.dbg.__bcr[i] = BCR_M_IMVA_MISMATCH |    // Stop on address mismatch
584                                S_USER |                 // Stop only in user mode
585                                BCR_ENABLE;              // Enable this breakpoint
586         if (m_state.context.gpr.__cpsr & 0x20)
587         {
588             // Thumb breakpoint
589             if (m_state.context.gpr.__pc & 2)
590                 m_state.dbg.__bcr[i] |= BAS_IMVA_2_3;
591             else
592                 m_state.dbg.__bcr[i] |= BAS_IMVA_0_1;
593 
594             uint16_t opcode;
595             if (sizeof(opcode) == m_thread->Process()->Task().ReadMemory(m_state.context.gpr.__pc, sizeof(opcode), &opcode))
596             {
597                 if (IsThumb32Opcode(opcode))
598                 {
599                     // 32 bit thumb opcode...
600                     if (m_state.context.gpr.__pc & 2)
601                     {
602                         // We can't take care of a 32 bit thumb instruction single step
603                         // with just IVA mismatching. We will need to chain an extra
604                         // hardware single step in order to complete this single step...
605                         m_hw_single_chained_step_addr = m_state.context.gpr.__pc + 2;
606                     }
607                     else
608                     {
609                         // Extend the number of bits to ignore for the mismatch
610                         m_state.dbg.__bcr[i] |= BAS_IMVA_ALL;
611                     }
612                 }
613             }
614         }
615         else
616         {
617             // ARM breakpoint
618             m_state.dbg.__bcr[i] |= BAS_IMVA_ALL; // Stop when any address bits change
619         }
620 
621         DNBLogThreadedIf(LOG_STEP, "%s: BVR%u=0x%8.8x  BCR%u=0x%8.8x", __FUNCTION__, i, m_state.dbg.__bvr[i], i, m_state.dbg.__bcr[i]);
622 
623         for (uint32_t j=i+1; j<16; ++j)
624         {
625             // Disable all others
626             m_state.dbg.__bvr[j] = 0;
627             m_state.dbg.__bcr[j] = 0;
628         }
629     }
630     else
631     {
632         // Just restore the state we had before we did single stepping
633         m_state.dbg = m_dbg_save;
634     }
635 #endif
636 
637     return SetDBGState(false);
638 }
639 
640 // return 1 if bit "BIT" is set in "value"
641 static inline uint32_t bit(uint32_t value, uint32_t bit)
642 {
643     return (value >> bit) & 1u;
644 }
645 
646 // return the bitfield "value[msbit:lsbit]".
647 static inline uint32_t bits(uint32_t value, uint32_t msbit, uint32_t lsbit)
648 {
649     assert(msbit >= lsbit);
650     uint32_t shift_left = sizeof(value) * 8 - 1 - msbit;
651     value <<= shift_left;           // shift anything above the msbit off of the unsigned edge
652     value >>= (shift_left + lsbit); // shift it back again down to the lsbit (including undoing any shift from above)
653     return value;                   // return our result
654 }
655 
656 bool
657 DNBArchMachARM::ConditionPassed(uint8_t condition, uint32_t cpsr)
658 {
659     uint32_t cpsr_n = bit(cpsr, 31); // Negative condition code flag
660     uint32_t cpsr_z = bit(cpsr, 30); // Zero condition code flag
661     uint32_t cpsr_c = bit(cpsr, 29); // Carry condition code flag
662     uint32_t cpsr_v = bit(cpsr, 28); // Overflow condition code flag
663 
664     switch (condition) {
665         case COND_EQ: // (0x0)
666             if (cpsr_z == 1) return true;
667             break;
668         case COND_NE: // (0x1)
669             if (cpsr_z == 0) return true;
670             break;
671         case COND_CS: // (0x2)
672             if (cpsr_c == 1) return true;
673             break;
674         case COND_CC: // (0x3)
675             if (cpsr_c == 0) return true;
676             break;
677         case COND_MI: // (0x4)
678             if (cpsr_n == 1) return true;
679             break;
680         case COND_PL: // (0x5)
681             if (cpsr_n == 0) return true;
682             break;
683         case COND_VS: // (0x6)
684             if (cpsr_v == 1) return true;
685             break;
686         case COND_VC: // (0x7)
687             if (cpsr_v == 0) return true;
688             break;
689         case COND_HI: // (0x8)
690             if ((cpsr_c == 1) && (cpsr_z == 0)) return true;
691             break;
692         case COND_LS: // (0x9)
693             if ((cpsr_c == 0) || (cpsr_z == 1)) return true;
694             break;
695         case COND_GE: // (0xA)
696             if (cpsr_n == cpsr_v) return true;
697             break;
698         case COND_LT: // (0xB)
699             if (cpsr_n != cpsr_v) return true;
700             break;
701         case COND_GT: // (0xC)
702             if ((cpsr_z == 0) && (cpsr_n == cpsr_v)) return true;
703             break;
704         case COND_LE: // (0xD)
705             if ((cpsr_z == 1) || (cpsr_n != cpsr_v)) return true;
706             break;
707         default:
708             return true;
709             break;
710     }
711 
712     return false;
713 }
714 
715 uint32_t
716 DNBArchMachARM::NumSupportedHardwareBreakpoints()
717 {
718     // Set the init value to something that will let us know that we need to
719     // autodetect how many breakpoints are supported dynamically...
720     static uint32_t g_num_supported_hw_breakpoints = UINT_MAX;
721     if (g_num_supported_hw_breakpoints == UINT_MAX)
722     {
723         // Set this to zero in case we can't tell if there are any HW breakpoints
724         g_num_supported_hw_breakpoints = 0;
725 
726         size_t len;
727         uint32_t n = 0;
728         len = sizeof (n);
729         if (::sysctlbyname("hw.optional.breakpoint", &n, &len, NULL, 0) == 0)
730         {
731             g_num_supported_hw_breakpoints = n;
732             DNBLogThreadedIf(LOG_THREAD, "hw.optional.breakpoint=%u", n);
733         }
734         else
735         {
736 #if !defined (__arm64__) && !defined (__aarch64__)
737             // Read the DBGDIDR to get the number of available hardware breakpoints
738             // However, in some of our current armv7 processors, hardware
739             // breakpoints/watchpoints were not properly connected. So detect those
740             // cases using a field in a sysctl. For now we are using "hw.cpusubtype"
741             // field to distinguish CPU architectures. This is a hack until we can
742             // get <rdar://problem/6372672> fixed, at which point we will switch to
743             // using a different sysctl string that will tell us how many BRPs
744             // are available to us directly without having to read DBGDIDR.
745             uint32_t register_DBGDIDR;
746 
747             asm("mrc p14, 0, %0, c0, c0, 0" : "=r" (register_DBGDIDR));
748             uint32_t numBRPs = bits(register_DBGDIDR, 27, 24);
749             // Zero is reserved for the BRP count, so don't increment it if it is zero
750             if (numBRPs > 0)
751                 numBRPs++;
752             DNBLogThreadedIf(LOG_THREAD, "DBGDIDR=0x%8.8x (number BRP pairs = %u)", register_DBGDIDR, numBRPs);
753 
754             if (numBRPs > 0)
755             {
756                 uint32_t cpusubtype;
757                 len = sizeof(cpusubtype);
758                 // TODO: remove this hack and change to using hw.optional.xx when implmented
759                 if (::sysctlbyname("hw.cpusubtype", &cpusubtype, &len, NULL, 0) == 0)
760                 {
761                     DNBLogThreadedIf(LOG_THREAD, "hw.cpusubtype=%d", cpusubtype);
762                     if (cpusubtype == CPU_SUBTYPE_ARM_V7)
763                         DNBLogThreadedIf(LOG_THREAD, "Hardware breakpoints disabled for armv7 (rdar://problem/6372672)");
764                     else
765                         g_num_supported_hw_breakpoints = numBRPs;
766                 }
767             }
768 #endif
769         }
770     }
771     return g_num_supported_hw_breakpoints;
772 }
773 
774 
775 uint32_t
776 DNBArchMachARM::NumSupportedHardwareWatchpoints()
777 {
778     // Set the init value to something that will let us know that we need to
779     // autodetect how many watchpoints are supported dynamically...
780     static uint32_t g_num_supported_hw_watchpoints = UINT_MAX;
781     if (g_num_supported_hw_watchpoints == UINT_MAX)
782     {
783         // Set this to zero in case we can't tell if there are any HW breakpoints
784         g_num_supported_hw_watchpoints = 0;
785 
786 
787         size_t len;
788         uint32_t n = 0;
789         len = sizeof (n);
790         if (::sysctlbyname("hw.optional.watchpoint", &n, &len, NULL, 0) == 0)
791         {
792             g_num_supported_hw_watchpoints = n;
793             DNBLogThreadedIf(LOG_THREAD, "hw.optional.watchpoint=%u", n);
794         }
795         else
796         {
797 #if !defined (__arm64__) && !defined (__aarch64__)
798             // Read the DBGDIDR to get the number of available hardware breakpoints
799             // However, in some of our current armv7 processors, hardware
800             // breakpoints/watchpoints were not properly connected. So detect those
801             // cases using a field in a sysctl. For now we are using "hw.cpusubtype"
802             // field to distinguish CPU architectures. This is a hack until we can
803             // get <rdar://problem/6372672> fixed, at which point we will switch to
804             // using a different sysctl string that will tell us how many WRPs
805             // are available to us directly without having to read DBGDIDR.
806 
807             uint32_t register_DBGDIDR;
808             asm("mrc p14, 0, %0, c0, c0, 0" : "=r" (register_DBGDIDR));
809             uint32_t numWRPs = bits(register_DBGDIDR, 31, 28) + 1;
810             DNBLogThreadedIf(LOG_THREAD, "DBGDIDR=0x%8.8x (number WRP pairs = %u)", register_DBGDIDR, numWRPs);
811 
812             if (numWRPs > 0)
813             {
814                 uint32_t cpusubtype;
815                 size_t len;
816                 len = sizeof(cpusubtype);
817                 // TODO: remove this hack and change to using hw.optional.xx when implmented
818                 if (::sysctlbyname("hw.cpusubtype", &cpusubtype, &len, NULL, 0) == 0)
819                 {
820                     DNBLogThreadedIf(LOG_THREAD, "hw.cpusubtype=0x%d", cpusubtype);
821 
822                     if (cpusubtype == CPU_SUBTYPE_ARM_V7)
823                         DNBLogThreadedIf(LOG_THREAD, "Hardware watchpoints disabled for armv7 (rdar://problem/6372672)");
824                     else
825                         g_num_supported_hw_watchpoints = numWRPs;
826                 }
827             }
828 #endif
829         }
830     }
831     return g_num_supported_hw_watchpoints;
832 }
833 
834 
835 uint32_t
836 DNBArchMachARM::EnableHardwareBreakpoint (nub_addr_t addr, nub_size_t size)
837 {
838     // Make sure our address isn't bogus
839     if (addr & 1)
840         return INVALID_NUB_HW_INDEX;
841 
842     kern_return_t kret = GetDBGState(false);
843 
844     if (kret == KERN_SUCCESS)
845     {
846         const uint32_t num_hw_breakpoints = NumSupportedHardwareBreakpoints();
847         uint32_t i;
848         for (i=0; i<num_hw_breakpoints; ++i)
849         {
850             if ((m_state.dbg.__bcr[i] & BCR_ENABLE) == 0)
851                 break; // We found an available hw breakpoint slot (in i)
852         }
853 
854         // See if we found an available hw breakpoint slot above
855         if (i < num_hw_breakpoints)
856         {
857             // Make sure bits 1:0 are clear in our address
858             m_state.dbg.__bvr[i] = addr & ~((nub_addr_t)3);
859 
860             if (size == 2 || addr & 2)
861             {
862                 uint32_t byte_addr_select = (addr & 2) ? BAS_IMVA_2_3 : BAS_IMVA_0_1;
863 
864                 // We have a thumb breakpoint
865                 // We have an ARM breakpoint
866                 m_state.dbg.__bcr[i] =  BCR_M_IMVA_MATCH |  // Stop on address mismatch
867                                         byte_addr_select |  // Set the correct byte address select so we only trigger on the correct opcode
868                                         S_USER |            // Which modes should this breakpoint stop in?
869                                         BCR_ENABLE;         // Enable this hardware breakpoint
870                 DNBLogThreadedIf (LOG_BREAKPOINTS, "DNBArchMachARM::EnableHardwareBreakpoint( addr = 0x%8.8llx, size = %llu ) - BVR%u/BCR%u = 0x%8.8x / 0x%8.8x (Thumb)",
871                                   (uint64_t)addr,
872                                   (uint64_t)size,
873                                   i,
874                                   i,
875                                   m_state.dbg.__bvr[i],
876                                   m_state.dbg.__bcr[i]);
877             }
878             else if (size == 4)
879             {
880                 // We have an ARM breakpoint
881                 m_state.dbg.__bcr[i] =  BCR_M_IMVA_MATCH |  // Stop on address mismatch
882                                         BAS_IMVA_ALL |      // Stop on any of the four bytes following the IMVA
883                                         S_USER |            // Which modes should this breakpoint stop in?
884                                         BCR_ENABLE;         // Enable this hardware breakpoint
885                 DNBLogThreadedIf (LOG_BREAKPOINTS, "DNBArchMachARM::EnableHardwareBreakpoint( addr = 0x%8.8llx, size = %llu ) - BVR%u/BCR%u = 0x%8.8x / 0x%8.8x (ARM)",
886                                   (uint64_t)addr,
887                                   (uint64_t)size,
888                                   i,
889                                   i,
890                                   m_state.dbg.__bvr[i],
891                                   m_state.dbg.__bcr[i]);
892             }
893 
894             kret = SetDBGState(false);
895             DNBLogThreadedIf(LOG_BREAKPOINTS, "DNBArchMachARM::EnableHardwareBreakpoint() SetDBGState() => 0x%8.8x.", kret);
896 
897             if (kret == KERN_SUCCESS)
898                 return i;
899         }
900         else
901         {
902             DNBLogThreadedIf (LOG_BREAKPOINTS, "DNBArchMachARM::EnableHardwareBreakpoint(addr = 0x%8.8llx, size = %llu) => all hardware breakpoint resources are being used.", (uint64_t)addr, (uint64_t)size);
903         }
904     }
905 
906     return INVALID_NUB_HW_INDEX;
907 }
908 
909 bool
910 DNBArchMachARM::DisableHardwareBreakpoint (uint32_t hw_index)
911 {
912     kern_return_t kret = GetDBGState(false);
913 
914     const uint32_t num_hw_points = NumSupportedHardwareBreakpoints();
915     if (kret == KERN_SUCCESS)
916     {
917         if (hw_index < num_hw_points)
918         {
919             m_state.dbg.__bcr[hw_index] = 0;
920             DNBLogThreadedIf(LOG_BREAKPOINTS, "DNBArchMachARM::SetHardwareBreakpoint( %u ) - BVR%u = 0x%8.8x  BCR%u = 0x%8.8x",
921                     hw_index,
922                     hw_index,
923                     m_state.dbg.__bvr[hw_index],
924                     hw_index,
925                     m_state.dbg.__bcr[hw_index]);
926 
927             kret = SetDBGState(false);
928 
929             if (kret == KERN_SUCCESS)
930                 return true;
931         }
932     }
933     return false;
934 }
935 
936 // ARM v7 watchpoints may be either word-size or double-word-size.
937 // It's implementation defined which they can handle.  It looks like on an
938 // armv8 device, armv7 processes can watch dwords.  But on a genuine armv7
939 // device I tried, only word watchpoints are supported.
940 
941 #if defined (__arm64__) || defined (__aarch64__)
942 #define WATCHPOINTS_ARE_DWORD 1
943 #else
944 #undef WATCHPOINTS_ARE_DWORD
945 #endif
946 
947 uint32_t
948 DNBArchMachARM::EnableHardwareWatchpoint (nub_addr_t addr, nub_size_t size, bool read, bool write, bool also_set_on_task)
949 {
950 
951     DNBLogThreadedIf(LOG_WATCHPOINTS, "DNBArchMachARM::EnableHardwareWatchpoint(addr = 0x%8.8llx, size = %zu, read = %u, write = %u)", (uint64_t)addr, size, read, write);
952 
953     const uint32_t num_hw_watchpoints = NumSupportedHardwareWatchpoints();
954 
955     // Can't watch zero bytes
956     if (size == 0)
957         return INVALID_NUB_HW_INDEX;
958 
959     // We must watch for either read or write
960     if (read == false && write == false)
961         return INVALID_NUB_HW_INDEX;
962 
963     // Otherwise, can't watch more than 8 bytes per WVR/WCR pair
964     if (size > 8)
965         return INVALID_NUB_HW_INDEX;
966 
967     // Treat arm watchpoints as having an 8-byte alignment requirement.  You can put a watchpoint on a 4-byte
968     // offset address but you can only watch 4 bytes with that watchpoint.
969 
970     // arm watchpoints on an 8-byte (double word) aligned addr can watch any bytes in that
971     // 8-byte long region of memory.  They can watch the 1st byte, the 2nd byte, 3rd byte, etc, or any
972     // combination therein by setting the bits in the BAS [12:5] (Byte Address Select) field of
973     // the DBGWCRn_EL1 reg for the watchpoint.
974 
975     // If the MASK [28:24] bits in the DBGWCRn_EL1 allow a single watchpoint to monitor a larger region
976     // of memory (16 bytes, 32 bytes, or 2GB) but the Byte Address Select bitfield then selects a larger
977     // range of bytes, instead of individual bytes.  See the ARMv8 Debug Architecture manual for details.
978     // This implementation does not currently use the MASK bits; the largest single region watched by a single
979     // watchpoint right now is 8-bytes.
980 
981 #if defined (WATCHPOINTS_ARE_DWORD)
982     nub_addr_t aligned_wp_address = addr & ~0x7;
983     uint32_t addr_dword_offset = addr & 0x7;
984     const int max_watchpoint_size = 8;
985 #else
986     nub_addr_t aligned_wp_address = addr & ~0x3;
987     uint32_t addr_dword_offset = addr & 0x3;
988     const int max_watchpoint_size = 4;
989 #endif
990 
991     DNBLogThreadedIf(LOG_WATCHPOINTS, "DNBArchMachARM::EnableHardwareWatchpoint aligned_wp_address is 0x%llx and addr_dword_offset is 0x%x", (uint64_t)aligned_wp_address, addr_dword_offset);
992 
993     // Do we need to split up this logical watchpoint into two hardware watchpoint
994     // registers?
995     // e.g. a watchpoint of length 4 on address 6.  We need do this with
996     //   one watchpoint on address 0 with bytes 6 & 7 being monitored
997     //   one watchpoint on address 8 with bytes 0, 1, 2, 3 being monitored
998 
999     if (addr_dword_offset + size > max_watchpoint_size)
1000     {
1001         DNBLogThreadedIf(LOG_WATCHPOINTS, "DNBArchMachARM::EnableHardwareWatchpoint(addr = 0x%8.8llx, size = %zu) needs two hardware watchpoints slots to monitor", (uint64_t)addr, size);
1002         int low_watchpoint_size = max_watchpoint_size - addr_dword_offset;
1003         int high_watchpoint_size = addr_dword_offset + size - max_watchpoint_size;
1004 
1005         uint32_t lo = EnableHardwareWatchpoint(addr, low_watchpoint_size, read, write, also_set_on_task);
1006         if (lo == INVALID_NUB_HW_INDEX)
1007             return INVALID_NUB_HW_INDEX;
1008         uint32_t hi = EnableHardwareWatchpoint (aligned_wp_address + max_watchpoint_size, high_watchpoint_size, read, write, also_set_on_task);
1009         if (hi == INVALID_NUB_HW_INDEX)
1010         {
1011             DisableHardwareWatchpoint (lo, also_set_on_task);
1012             return INVALID_NUB_HW_INDEX;
1013         }
1014         // Tag this lo->hi mapping in our database.
1015         LoHi[lo] = hi;
1016         return lo;
1017     }
1018 
1019     // At this point
1020     //  1 aligned_wp_address is the requested address rounded down to 8-byte alignment
1021     //  2 addr_dword_offset is the offset into that double word (8-byte) region that we are watching
1022     //  3 size is the number of bytes within that 8-byte region that we are watching
1023 
1024     // Set the Byte Address Selects bits DBGWCRn_EL1 bits [12:5] based on the above.
1025     // The bit shift and negation operation will give us 0b11 for 2, 0b1111 for 4, etc, up to 0b11111111 for 8.
1026     // then we shift those bits left by the offset into this dword that we are interested in.
1027     // e.g. if we are watching bytes 4,5,6,7 in a dword we want a BAS of 0b11110000.
1028     uint32_t byte_address_select = ((1 << size) - 1) << addr_dword_offset;
1029 
1030     // Read the debug state
1031     kern_return_t kret = GetDBGState(true);
1032 
1033     if (kret == KERN_SUCCESS)
1034     {
1035         // Check to make sure we have the needed hardware support
1036         uint32_t i = 0;
1037 
1038         for (i=0; i<num_hw_watchpoints; ++i)
1039         {
1040             if ((m_state.dbg.__wcr[i] & WCR_ENABLE) == 0)
1041                 break; // We found an available hw watchpoint slot (in i)
1042         }
1043 
1044         // See if we found an available hw watchpoint slot above
1045         if (i < num_hw_watchpoints)
1046         {
1047             //DumpDBGState(m_state.dbg);
1048 
1049             // Clear any previous LoHi joined-watchpoint that may have been in use
1050             LoHi[i] = 0;
1051 
1052             // shift our Byte Address Select bits up to the correct bit range for the DBGWCRn_EL1
1053             byte_address_select = byte_address_select << 5;
1054 
1055             // Make sure bits 1:0 are clear in our address
1056             m_state.dbg.__wvr[i] = aligned_wp_address;          // DVA (Data Virtual Address)
1057             m_state.dbg.__wcr[i] =  byte_address_select |       // Which bytes that follow the DVA that we will watch
1058                                     S_USER |                    // Stop only in user mode
1059                                     (read ? WCR_LOAD : 0) |     // Stop on read access?
1060                                     (write ? WCR_STORE : 0) |   // Stop on write access?
1061                                     WCR_ENABLE;                 // Enable this watchpoint;
1062 
1063             DNBLogThreadedIf(LOG_WATCHPOINTS, "DNBArchMachARM::EnableHardwareWatchpoint() adding watchpoint on address 0x%llx with control register value 0x%x", (uint64_t) m_state.dbg.__wvr[i], (uint32_t) m_state.dbg.__wcr[i]);
1064 
1065             // The kernel will set the MDE_ENABLE bit in the MDSCR_EL1 for us automatically, don't need to do it here.
1066 
1067             kret = SetDBGState(also_set_on_task);
1068             //DumpDBGState(m_state.dbg);
1069 
1070             DNBLogThreadedIf(LOG_WATCHPOINTS, "DNBArchMachARM::EnableHardwareWatchpoint() SetDBGState() => 0x%8.8x.", kret);
1071 
1072             if (kret == KERN_SUCCESS)
1073                 return i;
1074         }
1075         else
1076         {
1077             DNBLogThreadedIf(LOG_WATCHPOINTS, "DNBArchMachARM::EnableHardwareWatchpoint(): All hardware resources (%u) are in use.", num_hw_watchpoints);
1078         }
1079     }
1080     return INVALID_NUB_HW_INDEX;
1081 }
1082 
1083 bool
1084 DNBArchMachARM::ReenableHardwareWatchpoint (uint32_t hw_index)
1085 {
1086     // If this logical watchpoint # is actually implemented using
1087     // two hardware watchpoint registers, re-enable both of them.
1088 
1089     if (hw_index < NumSupportedHardwareWatchpoints() && LoHi[hw_index])
1090     {
1091         return ReenableHardwareWatchpoint_helper (hw_index) && ReenableHardwareWatchpoint_helper (LoHi[hw_index]);
1092     }
1093     else
1094     {
1095         return ReenableHardwareWatchpoint_helper (hw_index);
1096     }
1097 }
1098 
1099 bool
1100 DNBArchMachARM::ReenableHardwareWatchpoint_helper (uint32_t hw_index)
1101 {
1102     kern_return_t kret = GetDBGState(false);
1103     if (kret != KERN_SUCCESS)
1104         return false;
1105     const uint32_t num_hw_points = NumSupportedHardwareWatchpoints();
1106     if (hw_index >= num_hw_points)
1107         return false;
1108 
1109     m_state.dbg.__wvr[hw_index] = m_disabled_watchpoints[hw_index].addr;
1110     m_state.dbg.__wcr[hw_index] = m_disabled_watchpoints[hw_index].control;
1111 
1112     DNBLogThreadedIf(LOG_WATCHPOINTS, "DNBArchMachARM::EnableHardwareWatchpoint( %u ) - WVR%u = 0x%8.8llx  WCR%u = 0x%8.8llx",
1113                      hw_index,
1114                      hw_index,
1115                      (uint64_t) m_state.dbg.__wvr[hw_index],
1116                      hw_index,
1117                      (uint64_t) m_state.dbg.__wcr[hw_index]);
1118 
1119    // The kernel will set the MDE_ENABLE bit in the MDSCR_EL1 for us automatically, don't need to do it here.
1120 
1121     kret = SetDBGState(false);
1122 
1123     return (kret == KERN_SUCCESS);
1124 }
1125 
1126 bool
1127 DNBArchMachARM::DisableHardwareWatchpoint (uint32_t hw_index, bool also_set_on_task)
1128 {
1129     if (hw_index < NumSupportedHardwareWatchpoints() && LoHi[hw_index])
1130     {
1131         return DisableHardwareWatchpoint_helper (hw_index, also_set_on_task) && DisableHardwareWatchpoint_helper (LoHi[hw_index], also_set_on_task);
1132     }
1133     else
1134     {
1135         return DisableHardwareWatchpoint_helper (hw_index, also_set_on_task);
1136     }
1137 }
1138 
1139 bool
1140 DNBArchMachARM::DisableHardwareWatchpoint_helper (uint32_t hw_index, bool also_set_on_task)
1141 {
1142     kern_return_t kret = GetDBGState(false);
1143     if (kret != KERN_SUCCESS)
1144         return false;
1145 
1146     const uint32_t num_hw_points = NumSupportedHardwareWatchpoints();
1147     if (hw_index >= num_hw_points)
1148         return false;
1149 
1150     m_disabled_watchpoints[hw_index].addr = m_state.dbg.__wvr[hw_index];
1151     m_disabled_watchpoints[hw_index].control = m_state.dbg.__wcr[hw_index];
1152 
1153     m_state.dbg.__wvr[hw_index] = 0;
1154     m_state.dbg.__wcr[hw_index] = 0;
1155     DNBLogThreadedIf(LOG_WATCHPOINTS, "DNBArchMachARM::DisableHardwareWatchpoint( %u ) - WVR%u = 0x%8.8llx  WCR%u = 0x%8.8llx",
1156                      hw_index,
1157                      hw_index,
1158                      (uint64_t) m_state.dbg.__wvr[hw_index],
1159                      hw_index,
1160                      (uint64_t) m_state.dbg.__wcr[hw_index]);
1161 
1162     kret = SetDBGState(also_set_on_task);
1163 
1164     return (kret == KERN_SUCCESS);
1165 }
1166 
1167 // Returns -1 if the trailing bit patterns are not one of:
1168 // { 0b???1, 0b??10, 0b?100, 0b1000 }.
1169 static inline
1170 int32_t
1171 LowestBitSet(uint32_t val)
1172 {
1173     for (unsigned i = 0; i < 4; ++i) {
1174         if (bit(val, i))
1175             return i;
1176     }
1177     return -1;
1178 }
1179 
1180 // Iterate through the debug registers; return the index of the first watchpoint whose address matches.
1181 // As a side effect, the starting address as understood by the debugger is returned which could be
1182 // different from 'addr' passed as an in/out argument.
1183 uint32_t
1184 DNBArchMachARM::GetHardwareWatchpointHit(nub_addr_t &addr)
1185 {
1186     // Read the debug state
1187     kern_return_t kret = GetDBGState(true);
1188     //DumpDBGState(m_state.dbg);
1189     DNBLogThreadedIf(LOG_WATCHPOINTS, "DNBArchMachARM::GetHardwareWatchpointHit() GetDBGState() => 0x%8.8x.", kret);
1190     DNBLogThreadedIf(LOG_WATCHPOINTS, "DNBArchMachARM::GetHardwareWatchpointHit() addr = 0x%llx", (uint64_t)addr);
1191 
1192     // This is the watchpoint value to match against, i.e., word address.
1193 #if defined (WATCHPOINTS_ARE_DWORD)
1194     nub_addr_t wp_val = addr & ~((nub_addr_t)7);
1195 #else
1196     nub_addr_t wp_val = addr & ~((nub_addr_t)3);
1197 #endif
1198     if (kret == KERN_SUCCESS)
1199     {
1200         DBG &debug_state = m_state.dbg;
1201         uint32_t i, num = NumSupportedHardwareWatchpoints();
1202         for (i = 0; i < num; ++i)
1203         {
1204             nub_addr_t wp_addr = GetWatchAddress(debug_state, i);
1205             DNBLogThreadedIf(LOG_WATCHPOINTS,
1206                              "DNBArchMachARM::GetHardwareWatchpointHit() slot: %u (addr = 0x%llx).",
1207                              i, (uint64_t)wp_addr);
1208             if (wp_val == wp_addr) {
1209 #if defined (WATCHPOINTS_ARE_DWORD)
1210                 uint32_t byte_mask = bits(debug_state.__wcr[i], 12, 5);
1211 #else
1212                 uint32_t byte_mask = bits(debug_state.__wcr[i], 8, 5);
1213 #endif
1214 
1215                 // Sanity check the byte_mask, first.
1216                 if (LowestBitSet(byte_mask) < 0)
1217                     continue;
1218 
1219                 // Compute the starting address (from the point of view of the debugger).
1220                 addr = wp_addr + LowestBitSet(byte_mask);
1221                 return i;
1222             }
1223         }
1224     }
1225     return INVALID_NUB_HW_INDEX;
1226 }
1227 
1228 nub_addr_t
1229 DNBArchMachARM::GetWatchpointAddressByIndex (uint32_t hw_index)
1230 {
1231     kern_return_t kret = GetDBGState(true);
1232     if (kret != KERN_SUCCESS)
1233         return INVALID_NUB_ADDRESS;
1234     const uint32_t num = NumSupportedHardwareWatchpoints();
1235     if (hw_index >= num)
1236         return INVALID_NUB_ADDRESS;
1237     if (IsWatchpointEnabled (m_state.dbg, hw_index))
1238         return GetWatchAddress (m_state.dbg, hw_index);
1239     return INVALID_NUB_ADDRESS;
1240 }
1241 
1242 bool
1243 DNBArchMachARM::IsWatchpointEnabled(const DBG &debug_state, uint32_t hw_index)
1244 {
1245     // Watchpoint Control Registers, bitfield definitions
1246     // ...
1247     // Bits    Value    Description
1248     // [0]     0        Watchpoint disabled
1249     //         1        Watchpoint enabled.
1250     return (debug_state.__wcr[hw_index] & 1u);
1251 }
1252 
1253 nub_addr_t
1254 DNBArchMachARM::GetWatchAddress(const DBG &debug_state, uint32_t hw_index)
1255 {
1256     // Watchpoint Value Registers, bitfield definitions
1257     // Bits        Description
1258     // [31:2]      Watchpoint value (word address, i.e., 4-byte aligned)
1259     // [1:0]       RAZ/SBZP
1260     return bits(debug_state.__wvr[hw_index], 31, 0);
1261 }
1262 
1263 //----------------------------------------------------------------------
1264 // Register information definitions for 32 bit ARMV7.
1265 //----------------------------------------------------------------------
1266 enum gpr_regnums
1267 {
1268     gpr_r0 = 0,
1269     gpr_r1,
1270     gpr_r2,
1271     gpr_r3,
1272     gpr_r4,
1273     gpr_r5,
1274     gpr_r6,
1275     gpr_r7,
1276     gpr_r8,
1277     gpr_r9,
1278     gpr_r10,
1279     gpr_r11,
1280     gpr_r12,
1281     gpr_sp,
1282     gpr_lr,
1283     gpr_pc,
1284     gpr_cpsr
1285 };
1286 
1287 enum
1288 {
1289     vfp_s0 = 0,
1290     vfp_s1,
1291     vfp_s2,
1292     vfp_s3,
1293     vfp_s4,
1294     vfp_s5,
1295     vfp_s6,
1296     vfp_s7,
1297     vfp_s8,
1298     vfp_s9,
1299     vfp_s10,
1300     vfp_s11,
1301     vfp_s12,
1302     vfp_s13,
1303     vfp_s14,
1304     vfp_s15,
1305     vfp_s16,
1306     vfp_s17,
1307     vfp_s18,
1308     vfp_s19,
1309     vfp_s20,
1310     vfp_s21,
1311     vfp_s22,
1312     vfp_s23,
1313     vfp_s24,
1314     vfp_s25,
1315     vfp_s26,
1316     vfp_s27,
1317     vfp_s28,
1318     vfp_s29,
1319     vfp_s30,
1320     vfp_s31,
1321     vfp_d0,
1322     vfp_d1,
1323     vfp_d2,
1324     vfp_d3,
1325     vfp_d4,
1326     vfp_d5,
1327     vfp_d6,
1328     vfp_d7,
1329     vfp_d8,
1330     vfp_d9,
1331     vfp_d10,
1332     vfp_d11,
1333     vfp_d12,
1334     vfp_d13,
1335     vfp_d14,
1336     vfp_d15,
1337     vfp_d16,
1338     vfp_d17,
1339     vfp_d18,
1340     vfp_d19,
1341     vfp_d20,
1342     vfp_d21,
1343     vfp_d22,
1344     vfp_d23,
1345     vfp_d24,
1346     vfp_d25,
1347     vfp_d26,
1348     vfp_d27,
1349     vfp_d28,
1350     vfp_d29,
1351     vfp_d30,
1352     vfp_d31,
1353     vfp_q0,
1354     vfp_q1,
1355     vfp_q2,
1356     vfp_q3,
1357     vfp_q4,
1358     vfp_q5,
1359     vfp_q6,
1360     vfp_q7,
1361     vfp_q8,
1362     vfp_q9,
1363     vfp_q10,
1364     vfp_q11,
1365     vfp_q12,
1366     vfp_q13,
1367     vfp_q14,
1368     vfp_q15,
1369     vfp_fpscr
1370 };
1371 
1372 enum
1373 {
1374     exc_exception,
1375     exc_fsr,
1376     exc_far,
1377 };
1378 
1379 #define GPR_OFFSET_IDX(idx) (offsetof (DNBArchMachARM::GPR, __r[idx]))
1380 #define GPR_OFFSET_NAME(reg) (offsetof (DNBArchMachARM::GPR, __##reg))
1381 
1382 #define EXC_OFFSET(reg)      (offsetof (DNBArchMachARM::EXC, __##reg)  + offsetof (DNBArchMachARM::Context, exc))
1383 
1384 // These macros will auto define the register name, alt name, register size,
1385 // register offset, encoding, format and native register. This ensures that
1386 // the register state structures are defined correctly and have the correct
1387 // sizes and offsets.
1388 #define DEFINE_GPR_IDX(idx, reg, alt, gen) { e_regSetGPR, gpr_##reg, #reg, alt, Uint, Hex, 4, GPR_OFFSET_IDX(idx), gcc_##reg, dwarf_##reg, gen, INVALID_NUB_REGNUM, NULL, NULL}
1389 #define DEFINE_GPR_NAME(reg, alt, gen, inval) { e_regSetGPR, gpr_##reg, #reg, alt, Uint, Hex, 4, GPR_OFFSET_NAME(reg), gcc_##reg, dwarf_##reg, gen, INVALID_NUB_REGNUM, NULL, inval}
1390 
1391 // In case we are debugging to a debug target that the ability to
1392 // change into the protected modes with folded registers (ABT, IRQ,
1393 // FIQ, SYS, USR, etc..), we should invalidate r8-r14 if the CPSR
1394 // gets modified.
1395 
1396 const char * g_invalidate_cpsr[] = { "r8", "r9", "r10", "r11", "r12", "sp", "lr", NULL };
1397 
1398 // General purpose registers
1399 const DNBRegisterInfo
1400 DNBArchMachARM::g_gpr_registers[] =
1401 {
1402     DEFINE_GPR_IDX ( 0,  r0,"arg1", GENERIC_REGNUM_ARG1  ),
1403     DEFINE_GPR_IDX ( 1,  r1,"arg2", GENERIC_REGNUM_ARG2  ),
1404     DEFINE_GPR_IDX ( 2,  r2,"arg3", GENERIC_REGNUM_ARG3  ),
1405     DEFINE_GPR_IDX ( 3,  r3,"arg4", GENERIC_REGNUM_ARG4  ),
1406     DEFINE_GPR_IDX ( 4,  r4,  NULL, INVALID_NUB_REGNUM   ),
1407     DEFINE_GPR_IDX ( 5,  r5,  NULL, INVALID_NUB_REGNUM   ),
1408     DEFINE_GPR_IDX ( 6,  r6,  NULL, INVALID_NUB_REGNUM   ),
1409     DEFINE_GPR_IDX ( 7,  r7,  "fp", GENERIC_REGNUM_FP    ),
1410     DEFINE_GPR_IDX ( 8,  r8,  NULL, INVALID_NUB_REGNUM   ),
1411     DEFINE_GPR_IDX ( 9,  r9,  NULL, INVALID_NUB_REGNUM   ),
1412     DEFINE_GPR_IDX (10, r10,  NULL, INVALID_NUB_REGNUM   ),
1413     DEFINE_GPR_IDX (11, r11,  NULL, INVALID_NUB_REGNUM   ),
1414     DEFINE_GPR_IDX (12, r12,  NULL, INVALID_NUB_REGNUM   ),
1415     DEFINE_GPR_NAME (sp, "r13", GENERIC_REGNUM_SP, NULL),
1416     DEFINE_GPR_NAME (lr, "r14", GENERIC_REGNUM_RA, NULL),
1417     DEFINE_GPR_NAME (pc, "r15", GENERIC_REGNUM_PC, NULL),
1418     DEFINE_GPR_NAME (cpsr, "flags", GENERIC_REGNUM_FLAGS, g_invalidate_cpsr)
1419 };
1420 
1421 const char *g_contained_q0 [] { "q0", NULL };
1422 const char *g_contained_q1 [] { "q1", NULL };
1423 const char *g_contained_q2 [] { "q2", NULL };
1424 const char *g_contained_q3 [] { "q3", NULL };
1425 const char *g_contained_q4 [] { "q4", NULL };
1426 const char *g_contained_q5 [] { "q5", NULL };
1427 const char *g_contained_q6 [] { "q6", NULL };
1428 const char *g_contained_q7 [] { "q7", NULL };
1429 const char *g_contained_q8 [] { "q8", NULL };
1430 const char *g_contained_q9 [] { "q9", NULL };
1431 const char *g_contained_q10[] { "q10", NULL };
1432 const char *g_contained_q11[] { "q11", NULL };
1433 const char *g_contained_q12[] { "q12", NULL };
1434 const char *g_contained_q13[] { "q13", NULL };
1435 const char *g_contained_q14[] { "q14", NULL };
1436 const char *g_contained_q15[] { "q15", NULL };
1437 
1438 const char *g_invalidate_q0[]  { "q0",   "d0" , "d1" ,  "s0" , "s1" , "s2" , "s3" , NULL };
1439 const char *g_invalidate_q1[]  { "q1",   "d2" , "d3" ,  "s4" , "s5" , "s6" , "s7" , NULL };
1440 const char *g_invalidate_q2[]  { "q2",   "d4" , "d5" ,  "s8" , "s9" , "s10", "s11", NULL };
1441 const char *g_invalidate_q3[]  { "q3",   "d6" , "d7" ,  "s12", "s13", "s14", "s15", NULL };
1442 const char *g_invalidate_q4[]  { "q4",   "d8" , "d9" ,  "s16", "s17", "s18", "s19", NULL };
1443 const char *g_invalidate_q5[]  { "q5",   "d10", "d11",  "s20", "s21", "s22", "s23", NULL };
1444 const char *g_invalidate_q6[]  { "q6",   "d12", "d13",  "s24", "s25", "s26", "s27", NULL };
1445 const char *g_invalidate_q7[]  { "q7",   "d14", "d15",  "s28", "s29", "s30", "s31", NULL };
1446 const char *g_invalidate_q8[]  { "q8",   "d16", "d17",  NULL };
1447 const char *g_invalidate_q9[]  { "q9",   "d18", "d19",  NULL };
1448 const char *g_invalidate_q10[] { "q10",  "d20", "d21",  NULL };
1449 const char *g_invalidate_q11[] { "q11",  "d22", "d23",  NULL };
1450 const char *g_invalidate_q12[] { "q12",  "d24", "d25",  NULL };
1451 const char *g_invalidate_q13[] { "q13",  "d26", "d27",  NULL };
1452 const char *g_invalidate_q14[] { "q14",  "d28", "d29",  NULL };
1453 const char *g_invalidate_q15[] { "q15",  "d30", "d31",  NULL };
1454 
1455 #define VFP_S_OFFSET_IDX(idx) (((idx) % 4) * 4)  // offset into q reg: 0, 4, 8, 12
1456 #define VFP_D_OFFSET_IDX(idx) (((idx) % 2) * 8)  // offset into q reg: 0, 8
1457 #define VFP_Q_OFFSET_IDX(idx) (VFP_S_OFFSET_IDX ((idx) * 4))
1458 
1459 #define VFP_OFFSET_NAME(reg) (offsetof (DNBArchMachARM::FPU, __##reg) + offsetof (DNBArchMachARM::Context, vfp))
1460 
1461 #define FLOAT_FORMAT Float
1462 
1463 #define DEFINE_VFP_S_IDX(idx)  e_regSetVFP, vfp_s##idx, "s" #idx, NULL, IEEE754, FLOAT_FORMAT, 4, VFP_S_OFFSET_IDX(idx), INVALID_NUB_REGNUM, dwarf_s##idx, INVALID_NUB_REGNUM, INVALID_NUB_REGNUM
1464 #define DEFINE_VFP_D_IDX(idx)  e_regSetVFP, vfp_d##idx, "d" #idx, NULL, IEEE754, FLOAT_FORMAT, 8, VFP_D_OFFSET_IDX(idx), INVALID_NUB_REGNUM, dwarf_d##idx, INVALID_NUB_REGNUM, INVALID_NUB_REGNUM
1465 #define DEFINE_VFP_Q_IDX(idx)  e_regSetVFP, vfp_q##idx, "q" #idx, NULL, Vector, VectorOfUInt8, 16, VFP_Q_OFFSET_IDX(idx), INVALID_NUB_REGNUM, dwarf_q##idx, INVALID_NUB_REGNUM, INVALID_NUB_REGNUM
1466 
1467 // Floating point registers
1468 const DNBRegisterInfo
1469 DNBArchMachARM::g_vfp_registers[] =
1470 {
1471     { DEFINE_VFP_S_IDX ( 0), g_contained_q0, g_invalidate_q0 },
1472     { DEFINE_VFP_S_IDX ( 1), g_contained_q0, g_invalidate_q0 },
1473     { DEFINE_VFP_S_IDX ( 2), g_contained_q0, g_invalidate_q0 },
1474     { DEFINE_VFP_S_IDX ( 3), g_contained_q0, g_invalidate_q0 },
1475     { DEFINE_VFP_S_IDX ( 4), g_contained_q1, g_invalidate_q1 },
1476     { DEFINE_VFP_S_IDX ( 5), g_contained_q1, g_invalidate_q1 },
1477     { DEFINE_VFP_S_IDX ( 6), g_contained_q1, g_invalidate_q1 },
1478     { DEFINE_VFP_S_IDX ( 7), g_contained_q1, g_invalidate_q1 },
1479     { DEFINE_VFP_S_IDX ( 8), g_contained_q2, g_invalidate_q2 },
1480     { DEFINE_VFP_S_IDX ( 9), g_contained_q2, g_invalidate_q2 },
1481     { DEFINE_VFP_S_IDX (10), g_contained_q2, g_invalidate_q2 },
1482     { DEFINE_VFP_S_IDX (11), g_contained_q2, g_invalidate_q2 },
1483     { DEFINE_VFP_S_IDX (12), g_contained_q3, g_invalidate_q3 },
1484     { DEFINE_VFP_S_IDX (13), g_contained_q3, g_invalidate_q3 },
1485     { DEFINE_VFP_S_IDX (14), g_contained_q3, g_invalidate_q3 },
1486     { DEFINE_VFP_S_IDX (15), g_contained_q3, g_invalidate_q3 },
1487     { DEFINE_VFP_S_IDX (16), g_contained_q4, g_invalidate_q4 },
1488     { DEFINE_VFP_S_IDX (17), g_contained_q4, g_invalidate_q4 },
1489     { DEFINE_VFP_S_IDX (18), g_contained_q4, g_invalidate_q4 },
1490     { DEFINE_VFP_S_IDX (19), g_contained_q4, g_invalidate_q4 },
1491     { DEFINE_VFP_S_IDX (20), g_contained_q5, g_invalidate_q5 },
1492     { DEFINE_VFP_S_IDX (21), g_contained_q5, g_invalidate_q5 },
1493     { DEFINE_VFP_S_IDX (22), g_contained_q5, g_invalidate_q5 },
1494     { DEFINE_VFP_S_IDX (23), g_contained_q5, g_invalidate_q5 },
1495     { DEFINE_VFP_S_IDX (24), g_contained_q6, g_invalidate_q6 },
1496     { DEFINE_VFP_S_IDX (25), g_contained_q6, g_invalidate_q6 },
1497     { DEFINE_VFP_S_IDX (26), g_contained_q6, g_invalidate_q6 },
1498     { DEFINE_VFP_S_IDX (27), g_contained_q6, g_invalidate_q6 },
1499     { DEFINE_VFP_S_IDX (28), g_contained_q7, g_invalidate_q7 },
1500     { DEFINE_VFP_S_IDX (29), g_contained_q7, g_invalidate_q7 },
1501     { DEFINE_VFP_S_IDX (30), g_contained_q7, g_invalidate_q7 },
1502     { DEFINE_VFP_S_IDX (31), g_contained_q7, g_invalidate_q7 },
1503 
1504     { DEFINE_VFP_D_IDX (0),  g_contained_q0, g_invalidate_q0 },
1505     { DEFINE_VFP_D_IDX (1),  g_contained_q0, g_invalidate_q0 },
1506     { DEFINE_VFP_D_IDX (2),  g_contained_q1, g_invalidate_q1 },
1507     { DEFINE_VFP_D_IDX (3),  g_contained_q1, g_invalidate_q1 },
1508     { DEFINE_VFP_D_IDX (4),  g_contained_q2, g_invalidate_q2 },
1509     { DEFINE_VFP_D_IDX (5),  g_contained_q2, g_invalidate_q2 },
1510     { DEFINE_VFP_D_IDX (6),  g_contained_q3, g_invalidate_q3 },
1511     { DEFINE_VFP_D_IDX (7),  g_contained_q3, g_invalidate_q3 },
1512     { DEFINE_VFP_D_IDX (8),  g_contained_q4, g_invalidate_q4 },
1513     { DEFINE_VFP_D_IDX (9),  g_contained_q4, g_invalidate_q4 },
1514     { DEFINE_VFP_D_IDX (10), g_contained_q5, g_invalidate_q5 },
1515     { DEFINE_VFP_D_IDX (11), g_contained_q5, g_invalidate_q5 },
1516     { DEFINE_VFP_D_IDX (12), g_contained_q6, g_invalidate_q6 },
1517     { DEFINE_VFP_D_IDX (13), g_contained_q6, g_invalidate_q6 },
1518     { DEFINE_VFP_D_IDX (14), g_contained_q7, g_invalidate_q7 },
1519     { DEFINE_VFP_D_IDX (15), g_contained_q7, g_invalidate_q7 },
1520     { DEFINE_VFP_D_IDX (16), g_contained_q8, g_invalidate_q8 },
1521     { DEFINE_VFP_D_IDX (17), g_contained_q8, g_invalidate_q8 },
1522     { DEFINE_VFP_D_IDX (18), g_contained_q9, g_invalidate_q9 },
1523     { DEFINE_VFP_D_IDX (19), g_contained_q9, g_invalidate_q9 },
1524     { DEFINE_VFP_D_IDX (20), g_contained_q10, g_invalidate_q10 },
1525     { DEFINE_VFP_D_IDX (21), g_contained_q10, g_invalidate_q10 },
1526     { DEFINE_VFP_D_IDX (22), g_contained_q11, g_invalidate_q11 },
1527     { DEFINE_VFP_D_IDX (23), g_contained_q11, g_invalidate_q11 },
1528     { DEFINE_VFP_D_IDX (24), g_contained_q12, g_invalidate_q12 },
1529     { DEFINE_VFP_D_IDX (25), g_contained_q12, g_invalidate_q12 },
1530     { DEFINE_VFP_D_IDX (26), g_contained_q13, g_invalidate_q13 },
1531     { DEFINE_VFP_D_IDX (27), g_contained_q13, g_invalidate_q13 },
1532     { DEFINE_VFP_D_IDX (28), g_contained_q14, g_invalidate_q14 },
1533     { DEFINE_VFP_D_IDX (29), g_contained_q14, g_invalidate_q14 },
1534     { DEFINE_VFP_D_IDX (30), g_contained_q15, g_invalidate_q15 },
1535     { DEFINE_VFP_D_IDX (31), g_contained_q15, g_invalidate_q15 },
1536 
1537     { DEFINE_VFP_Q_IDX (0),  NULL,            g_invalidate_q0 },
1538     { DEFINE_VFP_Q_IDX (1),  NULL,            g_invalidate_q1 },
1539     { DEFINE_VFP_Q_IDX (2),  NULL,            g_invalidate_q2 },
1540     { DEFINE_VFP_Q_IDX (3),  NULL,            g_invalidate_q3 },
1541     { DEFINE_VFP_Q_IDX (4),  NULL,            g_invalidate_q4 },
1542     { DEFINE_VFP_Q_IDX (5),  NULL,            g_invalidate_q5 },
1543     { DEFINE_VFP_Q_IDX (6),  NULL,            g_invalidate_q6 },
1544     { DEFINE_VFP_Q_IDX (7),  NULL,            g_invalidate_q7 },
1545     { DEFINE_VFP_Q_IDX (8),  NULL,            g_invalidate_q8 },
1546     { DEFINE_VFP_Q_IDX (9),  NULL,            g_invalidate_q9 },
1547     { DEFINE_VFP_Q_IDX (10),  NULL,           g_invalidate_q10 },
1548     { DEFINE_VFP_Q_IDX (11),  NULL,           g_invalidate_q11 },
1549     { DEFINE_VFP_Q_IDX (12),  NULL,           g_invalidate_q12 },
1550     { DEFINE_VFP_Q_IDX (13),  NULL,           g_invalidate_q13 },
1551     { DEFINE_VFP_Q_IDX (14),  NULL,           g_invalidate_q14 },
1552     { DEFINE_VFP_Q_IDX (15),  NULL,           g_invalidate_q15 },
1553 
1554     { e_regSetVFP, vfp_fpscr, "fpscr", NULL, Uint, Hex, 4, VFP_OFFSET_NAME(fpscr), INVALID_NUB_REGNUM, INVALID_NUB_REGNUM, INVALID_NUB_REGNUM, INVALID_NUB_REGNUM, NULL, NULL }
1555 };
1556 
1557 // Exception registers
1558 
1559 const DNBRegisterInfo
1560 DNBArchMachARM::g_exc_registers[] =
1561 {
1562   { e_regSetVFP, exc_exception  , "exception"   , NULL, Uint, Hex, 4, EXC_OFFSET(exception) , INVALID_NUB_REGNUM, INVALID_NUB_REGNUM, INVALID_NUB_REGNUM, INVALID_NUB_REGNUM },
1563   { e_regSetVFP, exc_fsr        , "fsr"         , NULL, Uint, Hex, 4, EXC_OFFSET(fsr)       , INVALID_NUB_REGNUM, INVALID_NUB_REGNUM, INVALID_NUB_REGNUM, INVALID_NUB_REGNUM },
1564   { e_regSetVFP, exc_far        , "far"         , NULL, Uint, Hex, 4, EXC_OFFSET(far)       , INVALID_NUB_REGNUM, INVALID_NUB_REGNUM, INVALID_NUB_REGNUM, INVALID_NUB_REGNUM }
1565 };
1566 
1567 // Number of registers in each register set
1568 const size_t DNBArchMachARM::k_num_gpr_registers = sizeof(g_gpr_registers)/sizeof(DNBRegisterInfo);
1569 const size_t DNBArchMachARM::k_num_vfp_registers = sizeof(g_vfp_registers)/sizeof(DNBRegisterInfo);
1570 const size_t DNBArchMachARM::k_num_exc_registers = sizeof(g_exc_registers)/sizeof(DNBRegisterInfo);
1571 const size_t DNBArchMachARM::k_num_all_registers = k_num_gpr_registers + k_num_vfp_registers + k_num_exc_registers;
1572 
1573 //----------------------------------------------------------------------
1574 // Register set definitions. The first definitions at register set index
1575 // of zero is for all registers, followed by other registers sets. The
1576 // register information for the all register set need not be filled in.
1577 //----------------------------------------------------------------------
1578 const DNBRegisterSetInfo
1579 DNBArchMachARM::g_reg_sets[] =
1580 {
1581     { "ARM Registers",              NULL,               k_num_all_registers     },
1582     { "General Purpose Registers",  g_gpr_registers,    k_num_gpr_registers     },
1583     { "Floating Point Registers",   g_vfp_registers,    k_num_vfp_registers     },
1584     { "Exception State Registers",  g_exc_registers,    k_num_exc_registers     }
1585 };
1586 // Total number of register sets for this architecture
1587 const size_t DNBArchMachARM::k_num_register_sets = sizeof(g_reg_sets)/sizeof(DNBRegisterSetInfo);
1588 
1589 
1590 const DNBRegisterSetInfo *
1591 DNBArchMachARM::GetRegisterSetInfo(nub_size_t *num_reg_sets)
1592 {
1593     *num_reg_sets = k_num_register_sets;
1594     return g_reg_sets;
1595 }
1596 
1597 bool
1598 DNBArchMachARM::GetRegisterValue(int set, int reg, DNBRegisterValue *value)
1599 {
1600     if (set == REGISTER_SET_GENERIC)
1601     {
1602         switch (reg)
1603         {
1604         case GENERIC_REGNUM_PC:     // Program Counter
1605             set = e_regSetGPR;
1606             reg = gpr_pc;
1607             break;
1608 
1609         case GENERIC_REGNUM_SP:     // Stack Pointer
1610             set = e_regSetGPR;
1611             reg = gpr_sp;
1612             break;
1613 
1614         case GENERIC_REGNUM_FP:     // Frame Pointer
1615             set = e_regSetGPR;
1616             reg = gpr_r7;   // is this the right reg?
1617             break;
1618 
1619         case GENERIC_REGNUM_RA:     // Return Address
1620             set = e_regSetGPR;
1621             reg = gpr_lr;
1622             break;
1623 
1624         case GENERIC_REGNUM_FLAGS:  // Processor flags register
1625             set = e_regSetGPR;
1626             reg = gpr_cpsr;
1627             break;
1628 
1629         default:
1630             return false;
1631         }
1632     }
1633 
1634     if (GetRegisterState(set, false) != KERN_SUCCESS)
1635         return false;
1636 
1637     const DNBRegisterInfo *regInfo = m_thread->GetRegisterInfo(set, reg);
1638     if (regInfo)
1639     {
1640         value->info = *regInfo;
1641         switch (set)
1642         {
1643         case e_regSetGPR:
1644             if (reg < k_num_gpr_registers)
1645             {
1646                 value->value.uint32 = m_state.context.gpr.__r[reg];
1647                 return true;
1648             }
1649             break;
1650 
1651         case e_regSetVFP:
1652             // "reg" is an index into the floating point register set at this point.
1653             // We need to translate it up so entry 0 in the fp reg set is the same as vfp_s0
1654             // in the enumerated values for case statement below.
1655             if (reg >= vfp_s0 && reg <= vfp_s31)
1656             {
1657                 value->value.uint32 = m_state.context.vfp.__r[reg];
1658                 return true;
1659             }
1660             else if (reg >= vfp_d0 && reg <= vfp_d31)
1661             {
1662                 uint32_t d_reg_idx = reg - vfp_d0;
1663                 uint32_t s_reg_idx = d_reg_idx * 2;
1664                 value->value.v_sint32[0] = m_state.context.vfp.__r[s_reg_idx + 0];
1665                 value->value.v_sint32[1] = m_state.context.vfp.__r[s_reg_idx + 1];
1666                 return true;
1667             }
1668             else if (reg >= vfp_q0 && reg <= vfp_q15)
1669             {
1670                 uint32_t s_reg_idx = (reg - vfp_q0) * 4;
1671                 memcpy (&value->value.v_uint8, (uint8_t *) &m_state.context.vfp.__r[s_reg_idx], 16);
1672                 return true;
1673             }
1674             else if (reg == vfp_fpscr)
1675             {
1676                 value->value.uint32 = m_state.context.vfp.__fpscr;
1677                 return true;
1678             }
1679             break;
1680 
1681         case e_regSetEXC:
1682             if (reg < k_num_exc_registers)
1683             {
1684                 value->value.uint32 = (&m_state.context.exc.__exception)[reg];
1685                 return true;
1686             }
1687             break;
1688         }
1689     }
1690     return false;
1691 }
1692 
1693 bool
1694 DNBArchMachARM::SetRegisterValue(int set, int reg, const DNBRegisterValue *value)
1695 {
1696     if (set == REGISTER_SET_GENERIC)
1697     {
1698         switch (reg)
1699         {
1700         case GENERIC_REGNUM_PC:     // Program Counter
1701             set = e_regSetGPR;
1702             reg = gpr_pc;
1703             break;
1704 
1705         case GENERIC_REGNUM_SP:     // Stack Pointer
1706             set = e_regSetGPR;
1707             reg = gpr_sp;
1708             break;
1709 
1710         case GENERIC_REGNUM_FP:     // Frame Pointer
1711             set = e_regSetGPR;
1712             reg = gpr_r7;
1713             break;
1714 
1715         case GENERIC_REGNUM_RA:     // Return Address
1716             set = e_regSetGPR;
1717             reg = gpr_lr;
1718             break;
1719 
1720         case GENERIC_REGNUM_FLAGS:  // Processor flags register
1721             set = e_regSetGPR;
1722             reg = gpr_cpsr;
1723             break;
1724 
1725         default:
1726             return false;
1727         }
1728     }
1729 
1730     if (GetRegisterState(set, false) != KERN_SUCCESS)
1731         return false;
1732 
1733     bool success = false;
1734     const DNBRegisterInfo *regInfo = m_thread->GetRegisterInfo(set, reg);
1735     if (regInfo)
1736     {
1737         switch (set)
1738         {
1739         case e_regSetGPR:
1740             if (reg < k_num_gpr_registers)
1741             {
1742                 m_state.context.gpr.__r[reg] = value->value.uint32;
1743                 success = true;
1744             }
1745             break;
1746 
1747         case e_regSetVFP:
1748             // "reg" is an index into the floating point register set at this point.
1749             // We need to translate it up so entry 0 in the fp reg set is the same as vfp_s0
1750             // in the enumerated values for case statement below.
1751             if (reg >= vfp_s0 && reg <= vfp_s31)
1752             {
1753                 m_state.context.vfp.__r[reg] = value->value.uint32;
1754                 success = true;
1755             }
1756             else if (reg >= vfp_d0 && reg <= vfp_d31)
1757             {
1758                 uint32_t d_reg_idx = reg - vfp_d0;
1759                 uint32_t s_reg_idx = d_reg_idx * 2;
1760                 m_state.context.vfp.__r[s_reg_idx + 0] = value->value.v_sint32[0];
1761                 m_state.context.vfp.__r[s_reg_idx + 1] = value->value.v_sint32[1];
1762                 success = true;
1763             }
1764             else if (reg >= vfp_q0 && reg <= vfp_q15)
1765             {
1766                 uint32_t s_reg_idx = (reg - vfp_q0) * 4;
1767                 memcpy ((uint8_t *) &m_state.context.vfp.__r[s_reg_idx], &value->value.v_uint8, 16);
1768                 return true;
1769             }
1770             else if (reg == vfp_fpscr)
1771             {
1772                 m_state.context.vfp.__fpscr = value->value.uint32;
1773                 success = true;
1774             }
1775             break;
1776 
1777         case e_regSetEXC:
1778             if (reg < k_num_exc_registers)
1779             {
1780                 (&m_state.context.exc.__exception)[reg] = value->value.uint32;
1781                 success = true;
1782             }
1783             break;
1784         }
1785 
1786     }
1787     if (success)
1788         return SetRegisterState(set) == KERN_SUCCESS;
1789     return false;
1790 }
1791 
1792 kern_return_t
1793 DNBArchMachARM::GetRegisterState(int set, bool force)
1794 {
1795     switch (set)
1796     {
1797     case e_regSetALL:   return GetGPRState(force) |
1798                                GetVFPState(force) |
1799                                GetEXCState(force) |
1800                                GetDBGState(force);
1801     case e_regSetGPR:   return GetGPRState(force);
1802     case e_regSetVFP:   return GetVFPState(force);
1803     case e_regSetEXC:   return GetEXCState(force);
1804     case e_regSetDBG:   return GetDBGState(force);
1805     default: break;
1806     }
1807     return KERN_INVALID_ARGUMENT;
1808 }
1809 
1810 kern_return_t
1811 DNBArchMachARM::SetRegisterState(int set)
1812 {
1813     // Make sure we have a valid context to set.
1814     kern_return_t err = GetRegisterState(set, false);
1815     if (err != KERN_SUCCESS)
1816         return err;
1817 
1818     switch (set)
1819     {
1820     case e_regSetALL:   return SetGPRState() |
1821                                SetVFPState() |
1822                                SetEXCState() |
1823                                SetDBGState(false);
1824     case e_regSetGPR:   return SetGPRState();
1825     case e_regSetVFP:   return SetVFPState();
1826     case e_regSetEXC:   return SetEXCState();
1827     case e_regSetDBG:   return SetDBGState(false);
1828     default: break;
1829     }
1830     return KERN_INVALID_ARGUMENT;
1831 }
1832 
1833 bool
1834 DNBArchMachARM::RegisterSetStateIsValid (int set) const
1835 {
1836     return m_state.RegsAreValid(set);
1837 }
1838 
1839 
1840 nub_size_t
1841 DNBArchMachARM::GetRegisterContext (void *buf, nub_size_t buf_len)
1842 {
1843     nub_size_t size = sizeof (m_state.context.gpr) +
1844                       sizeof (m_state.context.vfp) +
1845                       sizeof (m_state.context.exc);
1846 
1847     if (buf && buf_len)
1848     {
1849         if (size > buf_len)
1850             size = buf_len;
1851 
1852         bool force = false;
1853         if (GetGPRState(force) | GetVFPState(force) | GetEXCState(force))
1854             return 0;
1855 
1856         // Copy each struct individually to avoid any padding that might be between the structs in m_state.context
1857         uint8_t *p = (uint8_t *)buf;
1858         ::memcpy (p, &m_state.context.gpr, sizeof(m_state.context.gpr));
1859         p += sizeof(m_state.context.gpr);
1860         ::memcpy (p, &m_state.context.vfp, sizeof(m_state.context.vfp));
1861         p += sizeof(m_state.context.vfp);
1862         ::memcpy (p, &m_state.context.exc, sizeof(m_state.context.exc));
1863         p += sizeof(m_state.context.exc);
1864 
1865         size_t bytes_written = p - (uint8_t *)buf;
1866         assert (bytes_written == size);
1867 
1868     }
1869     DNBLogThreadedIf (LOG_THREAD, "DNBArchMachARM::GetRegisterContext (buf = %p, len = %llu) => %llu", buf, (uint64_t)buf_len, (uint64_t)size);
1870     // Return the size of the register context even if NULL was passed in
1871     return size;
1872 }
1873 
1874 nub_size_t
1875 DNBArchMachARM::SetRegisterContext (const void *buf, nub_size_t buf_len)
1876 {
1877     nub_size_t size = sizeof (m_state.context.gpr) +
1878                       sizeof (m_state.context.vfp) +
1879                       sizeof (m_state.context.exc);
1880 
1881     if (buf == NULL || buf_len == 0)
1882         size = 0;
1883 
1884     if (size)
1885     {
1886         if (size > buf_len)
1887             size = buf_len;
1888 
1889         // Copy each struct individually to avoid any padding that might be between the structs in m_state.context
1890         uint8_t *p = (uint8_t *)buf;
1891         ::memcpy (&m_state.context.gpr, p, sizeof(m_state.context.gpr));
1892         p += sizeof(m_state.context.gpr);
1893         ::memcpy (&m_state.context.vfp, p, sizeof(m_state.context.vfp));
1894         p += sizeof(m_state.context.vfp);
1895         ::memcpy (&m_state.context.exc, p, sizeof(m_state.context.exc));
1896         p += sizeof(m_state.context.exc);
1897 
1898         size_t bytes_written = p - (uint8_t *)buf;
1899         assert (bytes_written == size);
1900 
1901         if (SetGPRState() | SetVFPState() | SetEXCState())
1902             return 0;
1903     }
1904     DNBLogThreadedIf (LOG_THREAD, "DNBArchMachARM::SetRegisterContext (buf = %p, len = %llu) => %llu", buf, (uint64_t)buf_len, (uint64_t)size);
1905     return size;
1906 }
1907 
1908 
1909 uint32_t
1910 DNBArchMachARM::SaveRegisterState ()
1911 {
1912     kern_return_t kret = ::thread_abort_safely(m_thread->MachPortNumber());
1913     DNBLogThreadedIf (LOG_THREAD, "thread = 0x%4.4x calling thread_abort_safely (tid) => %u (SetGPRState() for stop_count = %u)", m_thread->MachPortNumber(), kret, m_thread->Process()->StopCount());
1914 
1915     // Always re-read the registers because above we call thread_abort_safely();
1916     bool force = true;
1917 
1918     if ((kret = GetGPRState(force)) != KERN_SUCCESS)
1919     {
1920         DNBLogThreadedIf (LOG_THREAD, "DNBArchMachARM::SaveRegisterState () error: GPR regs failed to read: %u ", kret);
1921     }
1922     else if ((kret = GetVFPState(force)) != KERN_SUCCESS)
1923     {
1924         DNBLogThreadedIf (LOG_THREAD, "DNBArchMachARM::SaveRegisterState () error: %s regs failed to read: %u", "VFP", kret);
1925     }
1926     else
1927     {
1928         const uint32_t save_id = GetNextRegisterStateSaveID ();
1929         m_saved_register_states[save_id] = m_state.context;
1930         return save_id;
1931     }
1932     return UINT32_MAX;
1933 }
1934 
1935 bool
1936 DNBArchMachARM::RestoreRegisterState (uint32_t save_id)
1937 {
1938     SaveRegisterStates::iterator pos = m_saved_register_states.find(save_id);
1939     if (pos != m_saved_register_states.end())
1940     {
1941         m_state.context.gpr = pos->second.gpr;
1942         m_state.context.vfp = pos->second.vfp;
1943         kern_return_t kret;
1944         bool success = true;
1945         if ((kret = SetGPRState()) != KERN_SUCCESS)
1946         {
1947             DNBLogThreadedIf (LOG_THREAD, "DNBArchMachARM::RestoreRegisterState (save_id = %u) error: GPR regs failed to write: %u", save_id, kret);
1948             success = false;
1949         }
1950         else if ((kret = SetVFPState()) != KERN_SUCCESS)
1951         {
1952             DNBLogThreadedIf (LOG_THREAD, "DNBArchMachARM::RestoreRegisterState (save_id = %u) error: %s regs failed to write: %u", save_id, "VFP", kret);
1953             success = false;
1954         }
1955         m_saved_register_states.erase(pos);
1956         return success;
1957     }
1958     return false;
1959 }
1960 
1961 
1962 #endif    // #if defined (__arm__)
1963 
1964