[Lldb-commits] [lldb] r208732 - Add a new SBThread::SafeToCallFunctions API; this calls over to

Jason Molenda jmolenda at apple.com
Tue May 13 15:02:48 PDT 2014


Author: jmolenda
Date: Tue May 13 17:02:48 2014
New Revision: 208732

URL: http://llvm.org/viewvc/llvm-project?rev=208732&view=rev
Log:
Add a new SBThread::SafeToCallFunctions API; this calls over to
the SystemRuntime to check if a thread will have any problems 
performing an inferior function call so the driver can skip
making that function call on that thread.  Often the function
call can be executed on another thread instead.
<rdar://problem/16777874> 

Added:
    lldb/trunk/test/macosx/safe-to-func-call/
    lldb/trunk/test/macosx/safe-to-func-call/Makefile
    lldb/trunk/test/macosx/safe-to-func-call/TestSafeFuncCalls.py
    lldb/trunk/test/macosx/safe-to-func-call/main.c
Modified:
    lldb/trunk/include/lldb/API/SBThread.h
    lldb/trunk/include/lldb/Target/SystemRuntime.h
    lldb/trunk/include/lldb/Target/Thread.h
    lldb/trunk/scripts/Python/interface/SBThread.i
    lldb/trunk/source/API/SBThread.cpp
    lldb/trunk/source/Plugins/SystemRuntime/MacOSX/AppleGetItemInfoHandler.cpp
    lldb/trunk/source/Plugins/SystemRuntime/MacOSX/AppleGetPendingItemsHandler.cpp
    lldb/trunk/source/Plugins/SystemRuntime/MacOSX/AppleGetQueuesHandler.cpp
    lldb/trunk/source/Plugins/SystemRuntime/MacOSX/AppleGetThreadItemInfoHandler.cpp
    lldb/trunk/source/Plugins/SystemRuntime/MacOSX/SystemRuntimeMacOSX.cpp
    lldb/trunk/source/Plugins/SystemRuntime/MacOSX/SystemRuntimeMacOSX.h
    lldb/trunk/source/Target/Thread.cpp

Modified: lldb/trunk/include/lldb/API/SBThread.h
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/API/SBThread.h?rev=208732&r1=208731&r2=208732&view=diff
==============================================================================
--- lldb/trunk/include/lldb/API/SBThread.h (original)
+++ lldb/trunk/include/lldb/API/SBThread.h Tue May 13 17:02:48 2014
@@ -210,6 +210,9 @@ public:
     uint32_t
     GetExtendedBacktraceOriginatingIndexID ();
 
+    bool
+    SafeToCallFunctions ();
+
 protected:
     friend class SBBreakpoint;
     friend class SBBreakpointLocation;

Modified: lldb/trunk/include/lldb/Target/SystemRuntime.h
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/Target/SystemRuntime.h?rev=208732&r1=208731&r2=208732&view=diff
==============================================================================
--- lldb/trunk/include/lldb/Target/SystemRuntime.h (original)
+++ lldb/trunk/include/lldb/Target/SystemRuntime.h Tue May 13 17:02:48 2014
@@ -309,6 +309,27 @@ public:
     {
     }
 
+    //------------------------------------------------------------------
+    /// Determine whether it is safe to run an expression on a given thread
+    ///
+    /// If a system must not run functions on a thread in some particular state,
+    /// this method gives a way for it to flag that the expression should not be
+    /// run.
+    ///
+    /// @param [in] thread_sp
+    ///     The thread we want to run the expression on.
+    ///
+    /// @return
+    ///     True will be returned if there are no known problems with running an
+    ///     expression on this thread.  False means that the inferior function
+    ///     call should not be made on this thread.
+    //------------------------------------------------------------------
+    virtual bool
+    SafeToCallFunctionsOnThisThread (lldb::ThreadSP thread_sp)
+    {
+        return true;
+    }
+
 protected:
     //------------------------------------------------------------------
     // Member variables.

Modified: lldb/trunk/include/lldb/Target/Thread.h
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/include/lldb/Target/Thread.h?rev=208732&r1=208731&r2=208732&view=diff
==============================================================================
--- lldb/trunk/include/lldb/Target/Thread.h (original)
+++ lldb/trunk/include/lldb/Target/Thread.h Tue May 13 17:02:48 2014
@@ -592,6 +592,19 @@ public:
     virtual lldb::addr_t
     GetThreadLocalData (const lldb::ModuleSP module);
 
+    //------------------------------------------------------------------
+    /// Check whether this thread is safe to run functions
+    ///
+    /// The SystemRuntime may know of certain thread states (functions in 
+    /// process of execution, for instance) which can make it unsafe for 
+    /// functions to be called.
+    ///
+    /// @return
+    ///     True if it is safe to call functions on this thread.
+    ///     False if function calls should be avoided on this thread.
+    //------------------------------------------------------------------
+    virtual bool
+    SafeToCallFunctions ();
 
     //------------------------------------------------------------------
     // Thread Plan Providers:

Modified: lldb/trunk/scripts/Python/interface/SBThread.i
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/scripts/Python/interface/SBThread.i?rev=208732&r1=208731&r2=208732&view=diff
==============================================================================
--- lldb/trunk/scripts/Python/interface/SBThread.i (original)
+++ lldb/trunk/scripts/Python/interface/SBThread.i Tue May 13 17:02:48 2014
@@ -297,6 +297,16 @@ public:
     uint32_t
     GetExtendedBacktraceOriginatingIndexID();
 
+    %feature("autodoc","
+    Takes no arguments, returns a bool.
+    lldb may be able to detect that function calls should not be executed
+    on a given thread at a particular point in time.  It is recommended that
+    this is checked before performing an inferior function call on a given
+    thread.
+    ") SafeToCallFunctions;
+    bool
+    SafeToCallFunctions ();
+
     %pythoncode %{
         class frames_access(object):
             '''A helper object that will lazily hand out frames for a thread when supplied an index.'''

Modified: lldb/trunk/source/API/SBThread.cpp
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/API/SBThread.cpp?rev=208732&r1=208731&r2=208732&view=diff
==============================================================================
--- lldb/trunk/source/API/SBThread.cpp (original)
+++ lldb/trunk/source/API/SBThread.cpp Tue May 13 17:02:48 2014
@@ -1437,3 +1437,12 @@ SBThread::GetExtendedBacktraceOriginatin
         return thread_sp->GetExtendedBacktraceOriginatingIndexID();
     return LLDB_INVALID_INDEX32;
 }
+
+bool
+SBThread::SafeToCallFunctions ()
+{
+    ThreadSP thread_sp(m_opaque_sp->GetThreadSP());
+    if (thread_sp)
+        return thread_sp->SafeToCallFunctions();
+    return true;
+}

Modified: lldb/trunk/source/Plugins/SystemRuntime/MacOSX/AppleGetItemInfoHandler.cpp
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Plugins/SystemRuntime/MacOSX/AppleGetItemInfoHandler.cpp?rev=208732&r1=208731&r2=208732&view=diff
==============================================================================
--- lldb/trunk/source/Plugins/SystemRuntime/MacOSX/AppleGetItemInfoHandler.cpp (original)
+++ lldb/trunk/source/Plugins/SystemRuntime/MacOSX/AppleGetItemInfoHandler.cpp Tue May 13 17:02:48 2014
@@ -269,6 +269,14 @@ AppleGetItemInfoHandler::GetItemInfo (Th
 
     error.Clear();
 
+    if (thread.SafeToCallFunctions() == false)
+    {
+        if (log)
+            log->Printf ("Not safe to call functions on thread 0x%" PRIx64, thread.GetID());
+        error.SetErrorString ("Not safe to call functions on this thread.");
+        return return_value;
+    }
+
     // Set up the arguments for a call to
 
     // struct get_item_info_return_values

Modified: lldb/trunk/source/Plugins/SystemRuntime/MacOSX/AppleGetPendingItemsHandler.cpp
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Plugins/SystemRuntime/MacOSX/AppleGetPendingItemsHandler.cpp?rev=208732&r1=208731&r2=208732&view=diff
==============================================================================
--- lldb/trunk/source/Plugins/SystemRuntime/MacOSX/AppleGetPendingItemsHandler.cpp (original)
+++ lldb/trunk/source/Plugins/SystemRuntime/MacOSX/AppleGetPendingItemsHandler.cpp Tue May 13 17:02:48 2014
@@ -274,6 +274,14 @@ AppleGetPendingItemsHandler::GetPendingI
 
     error.Clear();
 
+    if (thread.SafeToCallFunctions() == false)
+    {
+        if (log)
+            log->Printf ("Not safe to call functions on thread 0x%" PRIx64, thread.GetID());
+        error.SetErrorString ("Not safe to call functions on this thread.");
+        return return_value;
+    }
+
     // Set up the arguments for a call to
 
     // struct get_pending_items_return_values

Modified: lldb/trunk/source/Plugins/SystemRuntime/MacOSX/AppleGetQueuesHandler.cpp
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Plugins/SystemRuntime/MacOSX/AppleGetQueuesHandler.cpp?rev=208732&r1=208731&r2=208732&view=diff
==============================================================================
--- lldb/trunk/source/Plugins/SystemRuntime/MacOSX/AppleGetQueuesHandler.cpp (original)
+++ lldb/trunk/source/Plugins/SystemRuntime/MacOSX/AppleGetQueuesHandler.cpp Tue May 13 17:02:48 2014
@@ -282,6 +282,14 @@ AppleGetQueuesHandler::GetCurrentQueues
 
     error.Clear();
 
+    if (thread.SafeToCallFunctions() == false)
+    {
+        if (log)
+            log->Printf ("Not safe to call functions on thread 0x%" PRIx64, thread.GetID());
+        error.SetErrorString ("Not safe to call functions on this thread.");
+        return return_value;
+    }
+
     // Set up the arguments for a call to
 
     // struct get_current_queues_return_values

Modified: lldb/trunk/source/Plugins/SystemRuntime/MacOSX/AppleGetThreadItemInfoHandler.cpp
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Plugins/SystemRuntime/MacOSX/AppleGetThreadItemInfoHandler.cpp?rev=208732&r1=208731&r2=208732&view=diff
==============================================================================
--- lldb/trunk/source/Plugins/SystemRuntime/MacOSX/AppleGetThreadItemInfoHandler.cpp (original)
+++ lldb/trunk/source/Plugins/SystemRuntime/MacOSX/AppleGetThreadItemInfoHandler.cpp Tue May 13 17:02:48 2014
@@ -273,6 +273,14 @@ AppleGetThreadItemInfoHandler::GetThread
 
     error.Clear();
 
+    if (thread.SafeToCallFunctions() == false)
+    {
+        if (log)
+            log->Printf ("Not safe to call functions on thread 0x%" PRIx64, thread.GetID());
+        error.SetErrorString ("Not safe to call functions on this thread.");
+        return return_value;
+    }
+
     // Set up the arguments for a call to
 
     // struct get_thread_item_info_return_values

Modified: lldb/trunk/source/Plugins/SystemRuntime/MacOSX/SystemRuntimeMacOSX.cpp
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Plugins/SystemRuntime/MacOSX/SystemRuntimeMacOSX.cpp?rev=208732&r1=208731&r2=208732&view=diff
==============================================================================
--- lldb/trunk/source/Plugins/SystemRuntime/MacOSX/SystemRuntimeMacOSX.cpp (original)
+++ lldb/trunk/source/Plugins/SystemRuntime/MacOSX/SystemRuntimeMacOSX.cpp Tue May 13 17:02:48 2014
@@ -214,6 +214,21 @@ SystemRuntimeMacOSX::GetQueueKind (addr_
     return kind;
 }
 
+bool
+SystemRuntimeMacOSX::SafeToCallFunctionsOnThisThread (ThreadSP thread_sp)
+{
+    if (thread_sp && thread_sp->GetStackFrameCount() > 0 && thread_sp->GetFrameWithConcreteFrameIndex(0))
+    {
+        const SymbolContext sym_ctx (thread_sp->GetFrameWithConcreteFrameIndex(0)->GetSymbolContext (eSymbolContextSymbol));
+        static ConstString g_select_symbol ("__select");
+        if (sym_ctx.GetFunctionName() == g_select_symbol)
+        {
+            return false;
+        }
+    }
+    return true;
+}
+
 lldb::queue_id_t
 SystemRuntimeMacOSX::GetQueueIDFromThreadQAddress (lldb::addr_t dispatch_qaddr)
 {

Modified: lldb/trunk/source/Plugins/SystemRuntime/MacOSX/SystemRuntimeMacOSX.h
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Plugins/SystemRuntime/MacOSX/SystemRuntimeMacOSX.h?rev=208732&r1=208731&r2=208732&view=diff
==============================================================================
--- lldb/trunk/source/Plugins/SystemRuntime/MacOSX/SystemRuntimeMacOSX.h (original)
+++ lldb/trunk/source/Plugins/SystemRuntime/MacOSX/SystemRuntimeMacOSX.h Tue May 13 17:02:48 2014
@@ -108,6 +108,9 @@ public:
     virtual lldb::QueueKind
     GetQueueKind (lldb::addr_t dispatch_queue_addr);
 
+    virtual bool
+    SafeToCallFunctionsOnThisThread (lldb::ThreadSP thread_sp);
+
     //------------------------------------------------------------------
     // PluginInterface protocol
     //------------------------------------------------------------------

Modified: lldb/trunk/source/Target/Thread.cpp
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/source/Target/Thread.cpp?rev=208732&r1=208731&r2=208732&view=diff
==============================================================================
--- lldb/trunk/source/Target/Thread.cpp (original)
+++ lldb/trunk/source/Target/Thread.cpp Tue May 13 17:02:48 2014
@@ -26,6 +26,7 @@
 #include "lldb/Target/Process.h"
 #include "lldb/Target/RegisterContext.h"
 #include "lldb/Target/StopInfo.h"
+#include "lldb/Target/SystemRuntime.h"
 #include "lldb/Target/Target.h"
 #include "lldb/Target/Thread.h"
 #include "lldb/Target/ThreadPlan.h"
@@ -1953,6 +1954,21 @@ Thread::GetThreadLocalData (const Module
         return LLDB_INVALID_ADDRESS;
 }
 
+bool
+Thread::SafeToCallFunctions ()
+{
+    Process *process = GetProcess().get();
+    if (process)
+    {
+        SystemRuntime *runtime = process->GetSystemRuntime ();
+        if (runtime)
+        {
+            return runtime->SafeToCallFunctionsOnThisThread (shared_from_this());
+        }
+    }
+    return true;
+}
+
 lldb::StackFrameSP
 Thread::GetStackFrameSPForStackFramePtr (StackFrame *stack_frame_ptr)
 {

Added: lldb/trunk/test/macosx/safe-to-func-call/Makefile
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/macosx/safe-to-func-call/Makefile?rev=208732&view=auto
==============================================================================
--- lldb/trunk/test/macosx/safe-to-func-call/Makefile (added)
+++ lldb/trunk/test/macosx/safe-to-func-call/Makefile Tue May 13 17:02:48 2014
@@ -0,0 +1,28 @@
+CC ?= clang
+ifeq "$(ARCH)" ""
+	ARCH = x86_64
+endif
+
+ifeq "$(OS)" ""
+	OS = $(shell uname -s)
+endif
+
+CFLAGS ?= -g -O0
+CWD := $(shell pwd)
+
+LIB_PREFIX := lib
+
+ifeq "$(OS)" "Darwin"
+	CFLAGS += -arch $(ARCH)
+endif
+
+all: a.out
+
+a.out: main.o
+	$(CC) $(CFLAGS) -o a.out main.o
+
+main.o: main.c
+	$(CC) $(CFLAGS) -c main.c
+
+clean:
+	rm -rf *.o *~ *.dylib *.so a.out *.dSYM

Added: lldb/trunk/test/macosx/safe-to-func-call/TestSafeFuncCalls.py
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/macosx/safe-to-func-call/TestSafeFuncCalls.py?rev=208732&view=auto
==============================================================================
--- lldb/trunk/test/macosx/safe-to-func-call/TestSafeFuncCalls.py (added)
+++ lldb/trunk/test/macosx/safe-to-func-call/TestSafeFuncCalls.py Tue May 13 17:02:48 2014
@@ -0,0 +1,81 @@
+"""Test function call thread safety."""
+
+import os, time
+import unittest2
+import lldb
+import lldbutil
+from lldbtest import *
+
+class TestSafeFuncCalls(TestBase):
+
+    mydir = TestBase.compute_mydir(__file__)
+
+    @unittest2.skipUnless(sys.platform.startswith("darwin"), "requires Darwin")
+    @python_api_test
+    @dsym_test
+    def test_with_dsym_and_python_api(self):
+        """Test function call thread safety."""
+        self.buildDsym()
+        self.function_call_safety_check()
+
+    @unittest2.skipUnless(sys.platform.startswith("darwin"), "requires Darwin")
+    @python_api_test
+    @dwarf_test
+    def test_with_dwarf_and_python_api(self):
+        """Test function call thread safety."""
+        self.buildDwarf()
+        self.function_call_safety_check()
+
+    def setUp(self):
+        # Call super's setUp().
+        TestBase.setUp(self)
+        # Find the line numbers that we will step to in main:
+        self.main_source = "main.c"
+
+
+
+    def check_number_of_threads(self, process):
+        self.assertTrue(process.GetNumThreads() == 2, "Check that the process has two threads when sitting at the stopper() breakpoint")
+
+    def safe_to_call_func_on_main_thread (self, main_thread):
+        self.assertTrue(main_thread.SafeToCallFunctions() == True, "It is safe to call functions on the main thread")
+
+    def safe_to_call_func_on_select_thread (self, select_thread):
+        self.assertTrue(select_thread.SafeToCallFunctions() == False, "It is not safe to call functions on the select thread")
+
+    def function_call_safety_check(self):
+        """Test function call safety checks"""
+        exe = os.path.join(os.getcwd(), "a.out")
+
+        target = self.dbg.CreateTarget(exe)
+        self.assertTrue(target, VALID_TARGET)
+        self.main_source_spec = lldb.SBFileSpec (self.main_source)
+        break1 = target.BreakpointCreateByName ("stopper", 'a.out')
+        self.assertTrue(break1, VALID_BREAKPOINT)
+        process = target.LaunchSimple (None, None, self.get_process_working_directory())
+        self.assertTrue(process, PROCESS_IS_VALID)
+        threads = lldbutil.get_threads_stopped_at_breakpoint (process, break1)
+        if len(threads) != 1:
+            self.fail ("Failed to stop at breakpoint 1.")
+
+        self.check_number_of_threads(process)
+
+        main_thread = lldb.SBThread()
+        select_thread = lldb.SBThread()
+        for idx in range (0, process.GetNumThreads()):
+            t = process.GetThreadAtIndex (idx)
+            if t.GetName() == "main thread":
+                main_thread = t
+            if t.GetName() == "select thread":
+                select_thread = t
+
+        self.assertTrue(main_thread.IsValid() and select_thread.IsValid(), "Got both expected threads")
+
+        self.safe_to_call_func_on_main_thread (main_thread)
+        self.safe_to_call_func_on_select_thread (select_thread)
+
+if __name__ == '__main__':
+    import atexit
+    lldb.SBDebugger.Initialize()
+    atexit.register(lambda: lldb.SBDebugger.Terminate())
+    unittest2.main()

Added: lldb/trunk/test/macosx/safe-to-func-call/main.c
URL: http://llvm.org/viewvc/llvm-project/lldb/trunk/test/macosx/safe-to-func-call/main.c?rev=208732&view=auto
==============================================================================
--- lldb/trunk/test/macosx/safe-to-func-call/main.c (added)
+++ lldb/trunk/test/macosx/safe-to-func-call/main.c Tue May 13 17:02:48 2014
@@ -0,0 +1,30 @@
+#include <sys/select.h>
+#include <stdio.h>
+#include <pthread.h>
+#include <unistd.h>
+
+void *
+select_thread (void *in)
+{
+    pthread_setname_np ("select thread");
+    fd_set fdset;
+    FD_SET (STDIN_FILENO, &fdset);
+    while (1)
+        select (2, &fdset, NULL, NULL, NULL);
+    return NULL;
+}
+
+void stopper ()
+{
+    while (1)
+        sleep(1); // break here
+}
+
+int main ()
+{
+    pthread_setname_np ("main thread");
+    pthread_t other_thread;
+    pthread_create (&other_thread, NULL, select_thread, NULL);
+    sleep (1);
+    stopper();
+}





More information about the lldb-commits mailing list