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