Handle thumb IT instructions correctly all the time.

The issue with Thumb IT (if/then) instructions is the IT instruction preceeds up to four instructions that are made conditional. If a breakpoint is placed on one of the conditional instructions, the instruction either needs to match the thumb opcode size (2 or 4 bytes) or a BKPT instruction needs to be used as these are always unconditional (even in a IT instruction). If BKPT instructions are used, then we might end up stopping on an instruction that won't get executed. So if we do stop at a BKPT instruction, we need to continue if the condition is not true.

When using the BKPT isntructions are easy in that you don't need to detect the size of the breakpoint that needs to be used when setting a breakpoint even in a thumb IT instruction. The bad part is you will now always stop at the opcode location and let LLDB determine if it should auto-continue. If the BKPT instruction is used, the BKPT that is used for ARM code should be something that also triggers the BKPT instruction in Thumb in case you set a breakpoint in the middle of code and the code is actually Thumb code. A value of 0xE120BE70 will work since the lower 16 bits being 0xBE70 happens to be a Thumb BKPT instruction. 

The alternative is to use trap or illegal instructions that the kernel will translate into breakpoint hits. On Mac this was 0xE7FFDEFE for ARM and 0xDEFE for Thumb. The darwin kernel currently doesn't recognize any 32 bit Thumb instruction as a instruction that will get turned into a breakpoint exception (EXC_BREAKPOINT), so we had to use the BKPT instruction on Mac. The linux kernel recognizes a 16 and a 32 bit instruction as valid thumb breakpoint opcodes. The benefit of using 16 or 32 bit instructions is you don't stop on opcodes in a IT block when the condition doesn't match. 

To further complicate things, single stepping on ARM is often implemented by modifying the BCR/BVR registers and setting the processor to stop when the PC is not equal to the current value. This means single stepping is another way the ARM target can stop on instructions that won't get executed.

This patch does the following:
1 - Fix the internal debugserver for Apple to use the BKPT instruction for ARM and Thumb
2 - Fix LLDB to catch when we stop in the middle of a Thumb IT instruction and continue if we stop at an instruction that won't execute
3 - Fixes this in a way that will work for any target on any platform as long as it is ARM/Thumb
4 - Adds a patch for ignoring conditions that don't match when in ARM mode (see below)

This patch also provides the code that implements the same thing for ARM instructions, though it is disabled for now. The ARM patch will check the condition of the instruction in ARM mode and continue if the condition isn't true (and therefore the instruction would not be executed). Again, this is not enable, but the code for it has been added.

<rdar://problem/19145455> 

llvm-svn: 223851
diff --git a/lldb/source/Core/ArchSpec.cpp b/lldb/source/Core/ArchSpec.cpp
index 70f53d9..e7a5e48 100644
--- a/lldb/source/Core/ArchSpec.cpp
+++ b/lldb/source/Core/ArchSpec.cpp
@@ -24,6 +24,11 @@
 #include "lldb/Host/Endian.h"
 #include "lldb/Host/HostInfo.h"
 #include "lldb/Target/Platform.h"
+#include "lldb/Target/Process.h"
+#include "lldb/Target/RegisterContext.h"
+#include "lldb/Target/Thread.h"
+#include "Plugins/Process/Utility/ARMDefines.h"
+#include "Plugins/Process/Utility/InstructionUtils.h"
 
 using namespace lldb;
 using namespace lldb_private;
@@ -1081,3 +1086,108 @@
     const ArchSpec::Core rhs_core = rhs.GetCore ();
     return lhs_core < rhs_core;
 }
+
+static void
+StopInfoOverrideCallbackTypeARM(lldb_private::Thread &thread)
+{
+    // We need to check if we are stopped in Thumb mode in a IT instruction
+    // and detect if the condition doesn't pass. If this is the case it means
+    // we won't actually execute this instruction. If this happens we need to
+    // clear the stop reason to no thread plans think we are stopped for a
+    // reason and the plans should keep going.
+    //
+    // We do this because when single stepping many ARM processes, debuggers
+    // often use the BVR/BCR registers that says "stop when the PC is not
+    // equal to its current value". This method of stepping means we can end
+    // up stopping on instructions inside an if/then block that wouldn't get
+    // executed. By fixing this we can stop the debugger from seeming like
+    // you stepped through both the "if" _and_ the "else" clause when source
+    // level stepping because the debugger stops regardless due to the BVR/BCR
+    // triggering a stop.
+    //
+    // It also means we can set breakpoints on instructions inside an an
+    // if/then block and correctly skip them if we use the BKPT instruction.
+    // The ARM and Thumb BKPT instructions are unconditional even when executed
+    // in a Thumb IT block.
+    //
+    // If your debugger inserts software traps in ARM/Thumb code, it will
+    // need to use 16 and 32 bit instruction for 16 and 32 bit thumb
+    // instructions respectively. If your debugger inserts a 16 bit thumb
+    // trap on top of a 32 bit thumb instruction for an opcode that is inside
+    // an if/then, it will change the it/then to conditionally execute your
+    // 16 bit trap and then cause your program to crash if it executes the
+    // trailing 16 bits (the second half of the 32 bit thumb instruction you
+    // partially overwrote).
+
+    RegisterContextSP reg_ctx_sp (thread.GetRegisterContext());
+    if (reg_ctx_sp)
+    {
+        const uint32_t cpsr = reg_ctx_sp->GetFlags(0);
+        if (cpsr != 0)
+        {
+            // Read the J and T bits to get the ISETSTATE
+            const uint32_t J = Bit32(cpsr, 24);
+            const uint32_t T = Bit32(cpsr, 5);
+            const uint32_t ISETSTATE = J << 1 | T;
+            if (ISETSTATE == 0)
+            {
+                // NOTE: I am pretty sure we want to enable the code below
+                // that detects when we stop on an instruction in ARM mode
+                // that is conditional and the condition doesn't pass. This
+                // can happen if you set a breakpoint on an instruction that
+                // is conditional. We currently will _always_ stop on the
+                // instruction which is bad. You can also run into this while
+                // single stepping and you could appear to run code in the "if"
+                // and in the "else" clause because it would stop at all of the
+                // conditional instructions in both.
+                // In such cases, we really don't want to stop at this location.
+                // I will check with the lldb-dev list first before I enable this.
+#if 0
+                // ARM mode: check for condition on intsruction
+                const addr_t pc = reg_ctx_sp->GetPC();
+                Error error;
+                // If we fail to read the opcode we will get UINT64_MAX as the
+                // result in "opcode" which we can use to detect if we read a
+                // valid opcode.
+                const uint64_t opcode = thread.GetProcess()->ReadUnsignedIntegerFromMemory(pc, 4, UINT64_MAX, error);
+                if (opcode <= UINT32_MAX)
+                {
+                    const uint32_t condition = Bits32((uint32_t)opcode, 31, 28);
+                    if (ARMConditionPassed(condition, cpsr) == false)
+                    {
+                        // We ARE stopped on an ARM instruction whose condition doesn't
+                        // pass so this instruction won't get executed.
+                        // Regardless of why it stopped, we need to clear the stop info
+                        thread.SetStopInfo (StopInfoSP());
+                    }
+                }
+#endif
+            }
+            else if (ISETSTATE == 1)
+            {
+                // Thumb mode
+                const uint32_t ITSTATE = Bits32 (cpsr, 15, 10) << 2 | Bits32 (cpsr, 26, 25);
+                if (ITSTATE != 0)
+                {
+                    const uint32_t condition = Bits32(ITSTATE, 7, 4);
+                    if (ARMConditionPassed(condition, cpsr) == false)
+                    {
+                        // We ARE stopped in a Thumb IT instruction on an instruction whose
+                        // condition doesn't pass so this instruction won't get executed.
+                        // Regardless of why it stopped, we need to clear the stop info
+                        thread.SetStopInfo (StopInfoSP());
+                    }
+                }
+            }
+        }
+    }
+}
+
+ArchSpec::StopInfoOverrideCallbackType
+ArchSpec::GetStopInfoOverrideCallback () const
+{
+    const llvm::Triple::ArchType machine = GetMachine();
+    if (machine == llvm::Triple::arm)
+        return StopInfoOverrideCallbackTypeARM;
+    return NULL;
+}
diff --git a/lldb/source/Plugins/Process/Utility/ARMDefines.h b/lldb/source/Plugins/Process/Utility/ARMDefines.h
index 2c8ad35..cfb33be 100644
--- a/lldb/source/Plugins/Process/Utility/ARMDefines.h
+++ b/lldb/source/Plugins/Process/Utility/ARMDefines.h
@@ -45,7 +45,8 @@
 #define COND_AL     0xE    // Always (unconditional)    Always (unconditional)        Any
 #define COND_UNCOND 0xF
 
-static inline const char *ARMCondCodeToString(uint32_t CC)
+static inline const char *
+ARMCondCodeToString(uint32_t CC)
 {
     switch (CC) {
     default: assert(0 && "Unknown condition code");
@@ -67,6 +68,37 @@
     }
 }
 
+static inline bool
+ARMConditionPassed(const uint32_t condition, const uint32_t cpsr)
+{
+    const uint32_t cpsr_n = (cpsr >> 31) & 1u; // Negative condition code flag
+    const uint32_t cpsr_z = (cpsr >> 30) & 1u; // Zero condition code flag
+    const uint32_t cpsr_c = (cpsr >> 29) & 1u; // Carry condition code flag
+    const uint32_t cpsr_v = (cpsr >> 28) & 1u; // Overflow condition code flag
+
+    switch (condition) {
+        case COND_EQ: return (cpsr_z == 1);
+        case COND_NE: return (cpsr_z == 0);
+        case COND_CS: return (cpsr_c == 1);
+        case COND_CC: return (cpsr_c == 0);
+        case COND_MI: return (cpsr_n == 1);
+        case COND_PL: return (cpsr_n == 0);
+        case COND_VS: return (cpsr_v == 1);
+        case COND_VC: return (cpsr_v == 0);
+        case COND_HI: return ((cpsr_c == 1) && (cpsr_z == 0));
+        case COND_LS: return ((cpsr_c == 0) || (cpsr_z == 1));
+        case COND_GE: return (cpsr_n == cpsr_v);
+        case COND_LT: return (cpsr_n != cpsr_v);
+        case COND_GT: return ((cpsr_z == 0) && (cpsr_n == cpsr_v));
+        case COND_LE: return ((cpsr_z == 1) || (cpsr_n != cpsr_v));
+        case COND_AL:
+        case COND_UNCOND:
+        default:
+            return true;
+    }
+    return false;
+}
+
 // Bit positions for CPSR
 #define CPSR_T_POS  5
 #define CPSR_F_POS  6
diff --git a/lldb/source/Plugins/Process/Utility/StopInfoMachException.cpp b/lldb/source/Plugins/Process/Utility/StopInfoMachException.cpp
index 0e3e559..a69b38b 100644
--- a/lldb/source/Plugins/Process/Utility/StopInfoMachException.cpp
+++ b/lldb/source/Plugins/Process/Utility/StopInfoMachException.cpp
@@ -423,9 +423,11 @@
                                 wp_sp->SetHardwareIndex((uint32_t)exc_sub_sub_code);
                             return StopInfo::CreateStopReasonWithWatchpointID(thread, wp_sp->GetID());
                         }
-                        // EXC_ARM_DA_DEBUG seems to be reused for EXC_BREAKPOINT as well as EXC_BAD_ACCESS
-                        if (thread.GetTemporaryResumeState() == eStateStepping)
-                            return StopInfo::CreateStopReasonToTrace(thread);
+                        else
+                        {
+                            is_actual_breakpoint = true;
+                            is_trace_if_actual_breakpoint_missing = true;
+                        }
                     }
                     else if (exc_code == 1) // EXC_ARM_BREAKPOINT
                     {
diff --git a/lldb/source/Target/Process.cpp b/lldb/source/Target/Process.cpp
index 3b50799..ab82db3 100644
--- a/lldb/source/Target/Process.cpp
+++ b/lldb/source/Target/Process.cpp
@@ -719,6 +719,7 @@
     m_public_run_lock (),
     m_private_run_lock (),
     m_currently_handling_event(false),
+    m_stop_info_override_callback (NULL),
     m_finalize_called(false),
     m_clear_thread_plans_on_stop (false),
     m_force_next_event_delivery(false),
@@ -846,6 +847,7 @@
     m_language_runtimes.clear();
     m_instrumentation_runtimes.clear();
     m_next_event_action_ap.reset();
+    m_stop_info_override_callback = NULL;
 //#ifdef LLDB_CONFIGURATION_DEBUG
 //    StreamFile s(stdout, false);
 //    EventSP event_sp;
@@ -3002,6 +3004,7 @@
     m_system_runtime_ap.reset();
     m_os_ap.reset();
     m_process_input_reader.reset();
+    m_stop_info_override_callback = NULL;
 
     Module *exe_module = m_target.GetExecutableModulePointer();
     if (exe_module)
@@ -3093,6 +3096,8 @@
                             ResumePrivateStateThread ();
                         else
                             StartPrivateStateThread ();
+
+                        m_stop_info_override_callback = GetTarget().GetArchitecture().GetStopInfoOverrideCallback();
                     }
                     else if (state == eStateExited)
                     {
@@ -3270,6 +3275,7 @@
     m_jit_loaders_ap.reset();
     m_system_runtime_ap.reset();
     m_os_ap.reset();
+    m_stop_info_override_callback = NULL;
     
     lldb::pid_t attach_pid = attach_info.GetProcessID();
     Error error;
@@ -3527,6 +3533,8 @@
                          exe_module_sp ? exe_module_sp->GetFileSpec().GetPath().c_str () : "<none>");
         }
     }
+
+    m_stop_info_override_callback = process_arch.GetStopInfoOverrideCallback();
 }
 
 Error
@@ -6239,6 +6247,7 @@
     m_instrumentation_runtimes.clear();
     m_thread_list.DiscardThreadPlans();
     m_memory_cache.Clear(true);
+    m_stop_info_override_callback = NULL;
     DoDidExec();
     CompleteAttach ();
     // Flush the process (threads and all stack frames) after running CompleteAttach()
diff --git a/lldb/source/Target/Thread.cpp b/lldb/source/Target/Thread.cpp
index 2381677..b532d8d 100644
--- a/lldb/source/Target/Thread.cpp
+++ b/lldb/source/Target/Thread.cpp
@@ -279,6 +279,7 @@
     m_process_wp (process.shared_from_this()),
     m_stop_info_sp (),
     m_stop_info_stop_id (0),
+    m_stop_info_override_stop_id (0),
     m_index_id (use_invalid_index_id ? LLDB_INVALID_INDEX32 : process.GetNextThreadIndexID(tid)),
     m_reg_context_sp (),
     m_state (eStateUnloaded),
@@ -466,6 +467,24 @@
                     SetStopInfo (StopInfoSP());
             }
         }
+
+        // The stop info can be manually set by calling Thread::SetStopInfo()
+        // prior to this function ever getting called, so we can't rely on
+        // "m_stop_info_stop_id != process_stop_id" as the condition for
+        // the if statement below, we must also check the stop info to see
+        // if we need to override it. See the header documentation in
+        // Process::GetStopInfoOverrideCallback() for more information on
+        // the stop info override callback.
+        if (m_stop_info_override_stop_id != process_stop_id)
+        {
+            m_stop_info_override_stop_id = process_stop_id;
+            if (m_stop_info_sp)
+            {
+                ArchSpec::StopInfoOverrideCallbackType callback = GetProcess()->GetStopInfoOverrideCallback();
+                if (callback)
+                    callback(*this);
+            }
+        }
     }
     return m_stop_info_sp;
 }
@@ -643,7 +662,8 @@
         lldb::RegisterContextSP reg_ctx_sp (GetRegisterContext());
         if (reg_ctx_sp)
         {
-            BreakpointSiteSP bp_site_sp = GetProcess()->GetBreakpointSiteList().FindByAddress(reg_ctx_sp->GetPC());
+            const addr_t thread_pc = reg_ctx_sp->GetPC();
+            BreakpointSiteSP bp_site_sp = GetProcess()->GetBreakpointSiteList().FindByAddress(thread_pc);
             if (bp_site_sp)
             {
                 // Note, don't assume there's a ThreadPlanStepOverBreakpoint, the target may not require anything
@@ -651,7 +671,17 @@
                     
                 ThreadPlan *cur_plan = GetCurrentPlan();
 
-                if (cur_plan->GetKind() != ThreadPlan::eKindStepOverBreakpoint)
+                bool push_step_over_bp_plan = false;
+                if (cur_plan->GetKind() == ThreadPlan::eKindStepOverBreakpoint)
+                {
+                    ThreadPlanStepOverBreakpoint *bp_plan = (ThreadPlanStepOverBreakpoint *)cur_plan;
+                    if (bp_plan->GetBreakpointLoadAddress() != thread_pc)
+                        push_step_over_bp_plan = true;
+                }
+                else
+                    push_step_over_bp_plan = true;
+
+                if (push_step_over_bp_plan)
                 {
                     ThreadPlanSP step_bp_plan_sp (new ThreadPlanStepOverBreakpoint (*this));
                     if (step_bp_plan_sp)