[Lldb-commits] [lldb] 59d8dd7 - [lldb/Plugins] Add support for ScriptedThread in ScriptedProcess

Med Ismail Bennani via lldb-commits lldb-commits at lists.llvm.org
Fri Oct 8 05:55:03 PDT 2021


Author: Med Ismail Bennani
Date: 2021-10-08T14:54:07+02:00
New Revision: 59d8dd79e1f9dead2dc2756e139073083e487228

URL: https://github.com/llvm/llvm-project/commit/59d8dd79e1f9dead2dc2756e139073083e487228
DIFF: https://github.com/llvm/llvm-project/commit/59d8dd79e1f9dead2dc2756e139073083e487228.diff

LOG: [lldb/Plugins] Add support for ScriptedThread in ScriptedProcess

This patch introduces the `ScriptedThread` class with its python
interface.

When used with `ScriptedProcess`, `ScriptedThreaad` can provide various
information such as the thread state, stop reason or even its register
context.

This can be used to reconstruct the program stack frames using lldb's unwinder.

rdar://74503836

Differential Revision: https://reviews.llvm.org/D107585

Signed-off-by: Med Ismail Bennani <medismail.bennani at gmail.com>

Added: 
    lldb/source/Plugins/Process/scripted/ScriptedThread.cpp
    lldb/source/Plugins/Process/scripted/ScriptedThread.h
    lldb/source/Plugins/ScriptInterpreter/Python/ScriptedThreadPythonInterface.cpp
    lldb/source/Plugins/ScriptInterpreter/Python/ScriptedThreadPythonInterface.h

Modified: 
    lldb/bindings/python/python-wrapper.swig
    lldb/examples/python/scripted_process/my_scripted_process.py
    lldb/examples/python/scripted_process/scripted_process.py
    lldb/include/lldb/Interpreter/ScriptedInterface.h
    lldb/include/lldb/Interpreter/ScriptedProcessInterface.h
    lldb/include/lldb/lldb-forward.h
    lldb/source/Plugins/Process/scripted/CMakeLists.txt
    lldb/source/Plugins/Process/scripted/ScriptedProcess.cpp
    lldb/source/Plugins/Process/scripted/ScriptedProcess.h
    lldb/source/Plugins/ScriptInterpreter/Python/CMakeLists.txt
    lldb/source/Plugins/ScriptInterpreter/Python/SWIGPythonBridge.h
    lldb/source/Plugins/ScriptInterpreter/Python/ScriptedProcessPythonInterface.cpp
    lldb/source/Plugins/ScriptInterpreter/Python/ScriptedProcessPythonInterface.h
    lldb/source/Plugins/ScriptInterpreter/Python/ScriptedPythonInterface.cpp
    lldb/source/Plugins/ScriptInterpreter/Python/ScriptedPythonInterface.h
    lldb/test/API/functionalities/scripted_process/TestScriptedProcess.py
    lldb/unittests/ScriptInterpreter/Python/PythonTestSuite.cpp

Removed: 
    


################################################################################
diff  --git a/lldb/bindings/python/python-wrapper.swig b/lldb/bindings/python/python-wrapper.swig
index a148ec3544ab8..feb4e54240bc1 100644
--- a/lldb/bindings/python/python-wrapper.swig
+++ b/lldb/bindings/python/python-wrapper.swig
@@ -340,6 +340,63 @@ LLDBSwigPythonCreateScriptedProcess
     Py_RETURN_NONE;
 }
 
+SWIGEXPORT void*
+LLDBSwigPythonCreateScriptedThread
+(
+    const char *python_class_name,
+    const char *session_dictionary_name,
+    const lldb::TargetSP& target_sp,
+    std::string &error_string
+)
+{
+    if (python_class_name == NULL || python_class_name[0] == '\0' || !session_dictionary_name)
+        Py_RETURN_NONE;
+
+    PyErr_Cleaner py_err_cleaner(true);
+
+    auto dict = PythonModule::MainModule().ResolveName<PythonDictionary>(session_dictionary_name);
+    auto pfunc = PythonObject::ResolveNameWithDictionary<PythonCallable>(python_class_name, dict);
+
+    if (!pfunc.IsAllocated()) {
+        error_string.append("could not find script class: ");
+        error_string.append(python_class_name);
+        return nullptr;
+    }
+
+    // I do not want the SBTarget to be deallocated when going out of scope
+    // because python has ownership of it and will manage memory for this
+    // object by itself
+    PythonObject target_arg(PyRefType::Owned, SBTypeToSWIGWrapper(new lldb::SBTarget(target_sp)));
+
+    if (!target_arg.IsAllocated())
+        Py_RETURN_NONE;
+
+    llvm::Expected<PythonCallable::ArgInfo> arg_info = pfunc.GetArgInfo();
+    if (!arg_info) {
+        llvm::handleAllErrors(
+            arg_info.takeError(),
+            [&](PythonException &E) {
+                error_string.append(E.ReadBacktrace());
+            },
+            [&](const llvm::ErrorInfoBase &E) {
+                error_string.append(E.message());
+            });
+        Py_RETURN_NONE;
+    }
+
+    PythonObject result = {};
+    if (arg_info.get().max_positional_args == 1) {
+        result = pfunc(target_arg);
+    } else {
+        error_string.assign("wrong number of arguments in __init__, should be 2 or 3 (not including self)");
+        Py_RETURN_NONE;
+    }
+
+    if (result.IsAllocated())
+        return result.release();
+    Py_RETURN_NONE;
+}
+
 SWIGEXPORT void*
 LLDBSwigPythonCreateScriptedThreadPlan
 (

diff  --git a/lldb/examples/python/scripted_process/my_scripted_process.py b/lldb/examples/python/scripted_process/my_scripted_process.py
index 429531e80e1e0..9257cd9c85126 100644
--- a/lldb/examples/python/scripted_process/my_scripted_process.py
+++ b/lldb/examples/python/scripted_process/my_scripted_process.py
@@ -1,7 +1,10 @@
-import os
+import os,struct,signal
+
+from typing import Any, Dict
 
 import lldb
 from lldb.plugins.scripted_process import ScriptedProcess
+from lldb.plugins.scripted_process import ScriptedThread
 
 class MyScriptedProcess(ScriptedProcess):
     def __init__(self, target: lldb.SBTarget, args : lldb.SBStructuredData):
@@ -35,6 +38,45 @@ def should_stop(self) -> bool:
     def is_alive(self) -> bool:
         return True
 
+    def get_scripted_thread_plugin(self):
+        return MyScriptedThread.__module__ + "." + MyScriptedThread.__name__
+
+
+class MyScriptedThread(ScriptedThread):
+    def __init__(self, target):
+        super().__init__(target)
+
+    def get_thread_id(self) -> int:
+        return 0x19
+
+    def get_name(self) -> str:
+        return MyScriptedThread.__name__ + ".thread-1"
+
+    def get_stop_reason(self) -> Dict[str, Any]:
+        return { "type": lldb.eStopReasonSignal, "data": {
+            "signal": signal.SIGINT
+        } }
+
+    def get_stackframes(self):
+        class ScriptedStackFrame:
+            def __init__(idx, cfa, pc, symbol_ctx):
+                self.idx = idx
+                self.cfa = cfa
+                self.pc = pc
+                self.symbol_ctx = symbol_ctx
+
+
+        symbol_ctx = lldb.SBSymbolContext()
+        frame_zero = ScriptedStackFrame(0, 0x42424242, 0x5000000, symbol_ctx)
+        self.frames.append(frame_zero)
+
+        return self.frame_zero[0:0]
+
+    def get_register_context(self) -> str:
+        return struct.pack(
+                '21Q', 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21)
+
+
 def __lldb_init_module(debugger, dict):
     if not 'SKIP_SCRIPTED_PROCESS_LAUNCH' in os.environ:
         debugger.HandleCommand(

diff  --git a/lldb/examples/python/scripted_process/scripted_process.py b/lldb/examples/python/scripted_process/scripted_process.py
index 72dce5c1e3bb0..d3474fbcf0a08 100644
--- a/lldb/examples/python/scripted_process/scripted_process.py
+++ b/lldb/examples/python/scripted_process/scripted_process.py
@@ -163,3 +163,163 @@ def is_alive(self):
             bool: True if scripted process is alive. False otherwise.
         """
         pass
+
+    @abstractmethod
+    def get_scripted_thread_plugin(self):
+        """ Get scripted thread plugin name.
+
+        Returns:
+            str: Name of the scripted thread plugin.
+        """
+        return None
+
+ at six.add_metaclass(ABCMeta)
+class ScriptedThread:
+
+    """
+    The base class for a scripted thread.
+
+    Most of the base class methods are `@abstractmethod` that need to be
+    overwritten by the inheriting class.
+
+    DISCLAIMER: THIS INTERFACE IS STILL UNDER DEVELOPMENT AND NOT STABLE.
+                THE METHODS EXPOSED MIGHT CHANGE IN THE FUTURE.
+    """
+
+    @abstractmethod
+    def __init__(self, target):
+        """ Construct a scripted thread.
+
+        Args:
+            target (lldb.SBTarget): The target launching the scripted process.
+            args (lldb.SBStructuredData): A Dictionary holding arbitrary
+                key/value pairs used by the scripted process.
+        """
+        self.target = None
+        self.args = None
+        if isinstance(target, lldb.SBTarget) and target.IsValid():
+            self.target = target
+
+        self.id = None
+        self.name = None
+        self.queue = None
+        self.state = None
+        self.stop_reason = None
+        self.register_info = None
+        self.register_ctx = []
+        self.frames = []
+
+    @abstractmethod
+    def get_thread_id(self):
+        """ Get the scripted thread identifier.
+
+        Returns:
+            int: The identifier of the scripted thread.
+        """
+        pass
+
+    @abstractmethod
+    def get_name(self):
+        """ Get the scripted thread name.
+
+        Returns:
+            str: The name of the scripted thread.
+        """
+        pass
+
+    def get_state(self):
+        """ Get the scripted thread state type.
+
+            eStateStopped,   ///< Process or thread is stopped and can be examined.
+            eStateRunning,   ///< Process or thread is running and can't be examined.
+            eStateStepping,  ///< Process or thread is in the process of stepping and can
+                             /// not be examined.
+
+        Returns:
+            int: The state type of the scripted thread.
+                 Returns lldb.eStateStopped by default.
+        """
+        return lldb.eStateStopped
+
+    def get_queue(self):
+        """ Get the scripted thread associated queue name.
+            This method is optional.
+
+        Returns:
+            str: The queue name associated with the scripted thread.
+        """
+        pass
+
+    @abstractmethod
+    def get_stop_reason(self):
+        """ Get the dictionary describing the stop reason type with some data.
+            This method is optional.
+
+        Returns:
+            Dict: The dictionary holding the stop reason type and the possibly
+            the stop reason data.
+        """
+        pass
+
+    def get_stackframes(self):
+        """ Get the list of stack frames for the scripted thread.
+
+        ```
+        class ScriptedStackFrame:
+            def __init__(idx, cfa, pc, symbol_ctx):
+                self.idx = idx
+                self.cfa = cfa
+                self.pc = pc
+                self.symbol_ctx = symbol_ctx
+        ```
+
+        Returns:
+            List[ScriptedFrame]: A list of `ScriptedStackFrame`
+                containing for each entry, the frame index, the canonical
+                frame address, the program counter value for that frame
+                and a symbol context.
+                None if the list is empty.
+        """
+        return 0
+
+    def get_register_info(self):
+        if self.register_info is None:
+            self.register_info = dict()
+            triple = self.target.triple
+            if triple:
+                arch = triple.split('-')[0]
+                if arch == 'x86_64':
+                    self.register_info['sets'] = ['GPR', 'FPU', 'EXC']
+                    self.register_info['registers'] = [
+                        {'name': 'rax', 'bitsize': 64, 'offset': 0, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 0, 'dwarf': 0},
+                        {'name': 'rbx', 'bitsize': 64, 'offset': 8, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 3, 'dwarf': 3},
+                        {'name': 'rcx', 'bitsize': 64, 'offset': 16, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 2, 'dwarf': 2, 'generic': 'arg4', 'alt-name': 'arg4', },
+                        {'name': 'rdx', 'bitsize': 64, 'offset': 24, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 1, 'dwarf': 1, 'generic': 'arg3', 'alt-name': 'arg3', },
+                        {'name': 'rdi', 'bitsize': 64, 'offset': 32, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 5, 'dwarf': 5, 'generic': 'arg1', 'alt-name': 'arg1', },
+                        {'name': 'rsi', 'bitsize': 64, 'offset': 40, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 4, 'dwarf': 4, 'generic': 'arg2', 'alt-name': 'arg2', },
+                        {'name': 'rbp', 'bitsize': 64, 'offset': 48, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 6, 'dwarf': 6, 'generic': 'fp', 'alt-name': 'fp', },
+                        {'name': 'rsp', 'bitsize': 64, 'offset': 56, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 7, 'dwarf': 7, 'generic': 'sp', 'alt-name': 'sp', },
+                        {'name': 'r8', 'bitsize': 64, 'offset': 64, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 8, 'dwarf': 8, 'generic': 'arg5', 'alt-name': 'arg5', },
+                        {'name': 'r9', 'bitsize': 64, 'offset': 72, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 9, 'dwarf': 9, 'generic': 'arg6', 'alt-name': 'arg6', },
+                        {'name': 'r10', 'bitsize': 64, 'offset': 80, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 10, 'dwarf': 10},
+                        {'name': 'r11', 'bitsize': 64, 'offset': 88, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 11, 'dwarf': 11},
+                        {'name': 'r12', 'bitsize': 64, 'offset': 96, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 12, 'dwarf': 12},
+                        {'name': 'r13', 'bitsize': 64, 'offset': 104, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 13, 'dwarf': 13},
+                        {'name': 'r14', 'bitsize': 64, 'offset': 112, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 14, 'dwarf': 14},
+                        {'name': 'r15', 'bitsize': 64, 'offset': 120, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 15, 'dwarf': 15},
+                        {'name': 'rip', 'bitsize': 64, 'offset': 128, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'gcc': 16, 'dwarf': 16, 'generic': 'pc', 'alt-name': 'pc'},
+                        {'name': 'rflags', 'bitsize': 64, 'offset': 136, 'encoding': 'uint', 'format': 'hex', 'set': 0, 'generic': 'flags', 'alt-name': 'flags'},
+                        {'name': 'cs', 'bitsize': 64, 'offset': 144, 'encoding': 'uint', 'format': 'hex', 'set': 0},
+                        {'name': 'fs', 'bitsize': 64, 'offset': 152, 'encoding': 'uint', 'format': 'hex', 'set': 0},
+                        {'name': 'gs', 'bitsize': 64, 'offset': 160, 'encoding': 'uint', 'format': 'hex', 'set': 0},
+                    ]
+        return self.register_info
+
+    @abstractmethod
+    def get_register_context(self):
+        """ Get the scripted thread register context
+
+        Returns:
+            str: A byte representing all register's value.
+        """
+        pass

diff  --git a/lldb/include/lldb/Interpreter/ScriptedInterface.h b/lldb/include/lldb/Interpreter/ScriptedInterface.h
index 7cd0c6a1a7772..38164739bab57 100644
--- a/lldb/include/lldb/Interpreter/ScriptedInterface.h
+++ b/lldb/include/lldb/Interpreter/ScriptedInterface.h
@@ -11,6 +11,8 @@
 
 #include "lldb/Core/StructuredDataImpl.h"
 #include "lldb/Target/ExecutionContext.h"
+#include "lldb/Utility/Log.h"
+#include "lldb/Utility/Logging.h"
 #include "lldb/lldb-private.h"
 
 #include <string>
@@ -25,6 +27,44 @@ class ScriptedInterface {
   CreatePluginObject(llvm::StringRef class_name, ExecutionContext &exe_ctx,
                      StructuredData::DictionarySP args_sp) = 0;
 
+  template <typename Ret>
+  Ret ErrorWithMessage(llvm::StringRef caller_name, llvm::StringRef error_msg,
+                       Status &error,
+                       uint32_t log_caterogy = LIBLLDB_LOG_PROCESS) {
+    LLDB_LOGF(GetLogIfAllCategoriesSet(log_caterogy), "%s ERROR = %s",
+              caller_name.data(), error_msg.data());
+    error.SetErrorString(llvm::Twine(caller_name + llvm::Twine(" ERROR = ") +
+                                     llvm::Twine(error_msg))
+                             .str());
+    return {};
+  }
+
+  template <typename T = StructuredData::ObjectSP>
+  bool CheckStructuredDataObject(llvm::StringRef caller, T obj, Status &error) {
+    if (!obj) {
+      return ErrorWithMessage<bool>(caller,
+                                    llvm::Twine("Null StructuredData object (" +
+                                                llvm::Twine(error.AsCString()) +
+                                                llvm::Twine(")."))
+                                        .str(),
+                                    error);
+    }
+
+    if (!obj->IsValid()) {
+      return ErrorWithMessage<bool>(
+          caller,
+          llvm::Twine("Invalid StructuredData object (" +
+                      llvm::Twine(error.AsCString()) + llvm::Twine(")."))
+              .str(),
+          error);
+    }
+
+    if (error.Fail())
+      return ErrorWithMessage<bool>(caller, error.AsCString(), error);
+
+    return true;
+  }
+
 protected:
   StructuredData::GenericSP m_object_instance_sp;
 };

diff  --git a/lldb/include/lldb/Interpreter/ScriptedProcessInterface.h b/lldb/include/lldb/Interpreter/ScriptedProcessInterface.h
index 9682ba76383b7..31d6e1476a6ed 100644
--- a/lldb/include/lldb/Interpreter/ScriptedProcessInterface.h
+++ b/lldb/include/lldb/Interpreter/ScriptedProcessInterface.h
@@ -57,6 +57,45 @@ class ScriptedProcessInterface : virtual public ScriptedInterface {
   virtual lldb::pid_t GetProcessID() { return LLDB_INVALID_PROCESS_ID; }
 
   virtual bool IsAlive() { return true; }
+
+  virtual llvm::Optional<std::string> GetScriptedThreadPluginName() {
+    return llvm::None;
+  }
+
+protected:
+  friend class ScriptedThread;
+  virtual lldb::ScriptedThreadInterfaceSP GetScriptedThreadInterface() {
+    return nullptr;
+  }
+
+  lldb::ScriptedThreadInterfaceSP m_scripted_thread_interface_sp = nullptr;
+};
+
+class ScriptedThreadInterface : virtual public ScriptedInterface {
+public:
+  StructuredData::GenericSP
+  CreatePluginObject(llvm::StringRef class_name, ExecutionContext &exe_ctx,
+                     StructuredData::DictionarySP args_sp) override {
+    return nullptr;
+  }
+
+  virtual lldb::tid_t GetThreadID() { return LLDB_INVALID_THREAD_ID; }
+
+  virtual llvm::Optional<std::string> GetName() { return llvm::None; }
+
+  virtual lldb::StateType GetState() { return lldb::eStateInvalid; }
+
+  virtual llvm::Optional<std::string> GetQueue() { return llvm::None; }
+
+  virtual StructuredData::DictionarySP GetStopReason() { return nullptr; }
+
+  virtual StructuredData::ArraySP GetStackFrames() { return nullptr; }
+
+  virtual StructuredData::DictionarySP GetRegisterInfo() { return nullptr; }
+
+  virtual llvm::Optional<std::string> GetRegisterContext() {
+    return llvm::None;
+  }
 };
 } // namespace lldb_private
 

diff  --git a/lldb/include/lldb/lldb-forward.h b/lldb/include/lldb/lldb-forward.h
index b68e9048ce3b4..482da17bfacb8 100644
--- a/lldb/include/lldb/lldb-forward.h
+++ b/lldb/include/lldb/lldb-forward.h
@@ -175,6 +175,7 @@ class Scalar;
 class ScriptInterpreter;
 class ScriptInterpreterLocker;
 class ScriptedProcessInterface;
+class ScriptedThreadInterface;
 class ScriptedSyntheticChildren;
 class SearchFilter;
 class Section;
@@ -367,6 +368,8 @@ typedef std::shared_ptr<lldb_private::ScriptSummaryFormat>
 typedef std::shared_ptr<lldb_private::ScriptInterpreter> ScriptInterpreterSP;
 typedef std::unique_ptr<lldb_private::ScriptedProcessInterface>
     ScriptedProcessInterfaceUP;
+typedef std::shared_ptr<lldb_private::ScriptedThreadInterface>
+    ScriptedThreadInterfaceSP;
 typedef std::shared_ptr<lldb_private::Section> SectionSP;
 typedef std::unique_ptr<lldb_private::SectionList> SectionListUP;
 typedef std::weak_ptr<lldb_private::Section> SectionWP;

diff  --git a/lldb/source/Plugins/Process/scripted/CMakeLists.txt b/lldb/source/Plugins/Process/scripted/CMakeLists.txt
index e2cfd058e2783..600ef31d032eb 100644
--- a/lldb/source/Plugins/Process/scripted/CMakeLists.txt
+++ b/lldb/source/Plugins/Process/scripted/CMakeLists.txt
@@ -1,5 +1,6 @@
 add_lldb_library(lldbPluginScriptedProcess PLUGIN
   ScriptedProcess.cpp
+  ScriptedThread.cpp
 
   LINK_LIBS
     lldbCore

diff  --git a/lldb/source/Plugins/Process/scripted/ScriptedProcess.cpp b/lldb/source/Plugins/Process/scripted/ScriptedProcess.cpp
index 23522b129fe87..4af107b00a968 100644
--- a/lldb/source/Plugins/Process/scripted/ScriptedProcess.cpp
+++ b/lldb/source/Plugins/Process/scripted/ScriptedProcess.cpp
@@ -21,8 +21,6 @@
 #include "lldb/Target/MemoryRegionInfo.h"
 #include "lldb/Target/RegisterContext.h"
 
-#include "lldb/Utility/Log.h"
-#include "lldb/Utility/Logging.h"
 #include "lldb/Utility/State.h"
 
 #include <mutex>
@@ -234,14 +232,9 @@ bool ScriptedProcess::IsAlive() {
 
 size_t ScriptedProcess::DoReadMemory(lldb::addr_t addr, void *buf, size_t size,
                                      Status &error) {
-
-  auto error_with_message = [&error](llvm::StringRef message) {
-    error.SetErrorString(message);
-    return 0;
-  };
-
   if (!m_interpreter)
-    return error_with_message("No interpreter.");
+    return GetInterface().ErrorWithMessage<size_t>(__PRETTY_FUNCTION__,
+                                                   "No interpreter.", error);
 
   lldb::DataExtractorSP data_extractor_sp =
       GetInterface().ReadMemoryAtAddress(addr, size, error);
@@ -253,7 +246,8 @@ size_t ScriptedProcess::DoReadMemory(lldb::addr_t addr, void *buf, size_t size,
       0, data_extractor_sp->GetByteSize(), buf, size, GetByteOrder());
 
   if (!bytes_copied || bytes_copied == LLDB_INVALID_OFFSET)
-    return error_with_message("Failed to copy read memory to buffer.");
+    return GetInterface().ErrorWithMessage<size_t>(
+        __PRETTY_FUNCTION__, "Failed to copy read memory to buffer.", error);
 
   return size;
 }
@@ -292,6 +286,30 @@ bool ScriptedProcess::DoUpdateThreadList(ThreadList &old_thread_list,
   // This is supposed to get the current set of threads, if any of them are in
   // old_thread_list then they get copied to new_thread_list, and then any
   // actually new threads will get added to new_thread_list.
+
+  CheckInterpreterAndScriptObject();
+
+  Status error;
+  ScriptLanguage language = m_interpreter->GetLanguage();
+
+  if (language != eScriptLanguagePython)
+    return GetInterface().ErrorWithMessage<bool>(
+        __PRETTY_FUNCTION__,
+        llvm::Twine("ScriptInterpreter language (" +
+                    llvm::Twine(m_interpreter->LanguageToString(language)) +
+                    llvm::Twine(") not supported."))
+            .str(),
+        error);
+
+  lldb::ThreadSP thread_sp;
+  thread_sp = std::make_shared<ScriptedThread>(*this, error);
+
+  if (!thread_sp || error.Fail())
+    return GetInterface().ErrorWithMessage<bool>(__PRETTY_FUNCTION__,
+                                                 error.AsCString(), error);
+
+  new_thread_list.AddThread(thread_sp);
+
   return new_thread_list.GetSize(false) > 0;
 }
 

diff  --git a/lldb/source/Plugins/Process/scripted/ScriptedProcess.h b/lldb/source/Plugins/Process/scripted/ScriptedProcess.h
index bdc18494b01ec..e7a5147cb858f 100644
--- a/lldb/source/Plugins/Process/scripted/ScriptedProcess.h
+++ b/lldb/source/Plugins/Process/scripted/ScriptedProcess.h
@@ -13,6 +13,8 @@
 #include "lldb/Utility/ConstString.h"
 #include "lldb/Utility/Status.h"
 
+#include "ScriptedThread.h"
+
 #include <mutex>
 
 namespace lldb_private {
@@ -101,6 +103,8 @@ class ScriptedProcess : public Process {
                           ThreadList &new_thread_list) override;
 
 private:
+  friend class ScriptedThread;
+
   void CheckInterpreterAndScriptObject() const;
   ScriptedProcessInterface &GetInterface() const;
   static bool IsScriptLanguageSupported(lldb::ScriptLanguage language);

diff  --git a/lldb/source/Plugins/Process/scripted/ScriptedThread.cpp b/lldb/source/Plugins/Process/scripted/ScriptedThread.cpp
new file mode 100644
index 0000000000000..11db89bfc3977
--- /dev/null
+++ b/lldb/source/Plugins/Process/scripted/ScriptedThread.cpp
@@ -0,0 +1,210 @@
+//===-- ScriptedThread.cpp ------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "ScriptedThread.h"
+
+#include "Plugins/Process/Utility/RegisterContextThreadMemory.h"
+#include "lldb/Target/OperatingSystem.h"
+#include "lldb/Target/Process.h"
+#include "lldb/Target/RegisterContext.h"
+#include "lldb/Target/StopInfo.h"
+#include "lldb/Target/Unwind.h"
+#include "lldb/Utility/DataBufferHeap.h"
+#include "lldb/Utility/Log.h"
+#include "lldb/Utility/Logging.h"
+
+#include <memory>
+
+using namespace lldb;
+using namespace lldb_private;
+
+void ScriptedThread::CheckInterpreterAndScriptObject() const {
+  lldbassert(m_script_object_sp && "Invalid Script Object.");
+  lldbassert(GetInterface() && "Invalid Scripted Thread Interface.");
+}
+
+ScriptedThread::ScriptedThread(ScriptedProcess &process, Status &error)
+    : Thread(process, LLDB_INVALID_THREAD_ID), m_scripted_process(process) {
+  if (!process.IsValid()) {
+    error.SetErrorString("Invalid scripted process");
+    return;
+  }
+
+  process.CheckInterpreterAndScriptObject();
+
+  auto scripted_thread_interface = GetInterface();
+  if (!scripted_thread_interface) {
+    error.SetErrorString("Failed to get scripted thread interface.");
+    return;
+  }
+
+  llvm::Optional<std::string> class_name =
+      process.GetInterface().GetScriptedThreadPluginName();
+  if (!class_name || class_name->empty()) {
+    error.SetErrorString("Failed to get scripted thread class name.");
+    return;
+  }
+
+  ExecutionContext exe_ctx(process);
+
+  StructuredData::GenericSP object_sp =
+      scripted_thread_interface->CreatePluginObject(
+          class_name->c_str(), exe_ctx,
+          process.m_scripted_process_info.GetDictionarySP());
+  if (!object_sp || !object_sp->IsValid()) {
+    error.SetErrorString("Failed to create valid script object");
+    return;
+  }
+
+  m_script_object_sp = object_sp;
+
+  SetID(scripted_thread_interface->GetThreadID());
+
+  llvm::Optional<std::string> reg_data =
+      scripted_thread_interface->GetRegisterContext();
+  if (!reg_data) {
+    error.SetErrorString("Failed to get scripted thread registers data.");
+    return;
+  }
+
+  DataBufferSP data_sp(
+      std::make_shared<DataBufferHeap>(reg_data->c_str(), reg_data->size()));
+
+  if (!data_sp->GetByteSize()) {
+    error.SetErrorString("Failed to copy raw registers data.");
+    return;
+  }
+
+  std::shared_ptr<RegisterContextMemory> reg_ctx_memory =
+      std::make_shared<RegisterContextMemory>(
+          *this, 0, *GetDynamicRegisterInfo(), LLDB_INVALID_ADDRESS);
+  if (!reg_ctx_memory) {
+    error.SetErrorString("Failed to create a register context.");
+    return;
+  }
+
+  reg_ctx_memory->SetAllRegisterData(data_sp);
+  m_reg_context_sp = reg_ctx_memory;
+}
+
+ScriptedThread::~ScriptedThread() { DestroyThread(); }
+
+const char *ScriptedThread::GetName() {
+  CheckInterpreterAndScriptObject();
+  llvm::Optional<std::string> thread_name = GetInterface()->GetName();
+  if (!thread_name)
+    return nullptr;
+  return ConstString(thread_name->c_str()).AsCString();
+}
+
+const char *ScriptedThread::GetQueueName() {
+  CheckInterpreterAndScriptObject();
+  llvm::Optional<std::string> queue_name = GetInterface()->GetQueue();
+  if (!queue_name)
+    return nullptr;
+  return ConstString(queue_name->c_str()).AsCString();
+}
+
+void ScriptedThread::WillResume(StateType resume_state) {}
+
+void ScriptedThread::ClearStackFrames() { Thread::ClearStackFrames(); }
+
+RegisterContextSP ScriptedThread::GetRegisterContext() {
+  if (!m_reg_context_sp) {
+    m_reg_context_sp = std::make_shared<RegisterContextThreadMemory>(
+        *this, LLDB_INVALID_ADDRESS);
+    GetInterface()->GetRegisterContext();
+  }
+  return m_reg_context_sp;
+}
+
+RegisterContextSP
+ScriptedThread::CreateRegisterContextForFrame(StackFrame *frame) {
+  uint32_t concrete_frame_idx = frame ? frame->GetConcreteFrameIndex() : 0;
+
+  if (concrete_frame_idx == 0)
+    return GetRegisterContext();
+  return GetUnwinder().CreateRegisterContextForFrame(frame);
+}
+
+bool ScriptedThread::CalculateStopInfo() {
+  StructuredData::DictionarySP dict_sp = GetInterface()->GetStopReason();
+
+  Status error;
+  lldb::StopInfoSP stop_info_sp;
+  lldb::StopReason stop_reason_type;
+
+  if (!dict_sp->GetValueForKeyAsInteger("type", stop_reason_type))
+    return GetInterface()->ErrorWithMessage<bool>(
+        __PRETTY_FUNCTION__,
+        "Couldn't find value for key 'type' in stop reason dictionary.", error);
+
+  StructuredData::Dictionary *data_dict;
+  if (!dict_sp->GetValueForKeyAsDictionary("data", data_dict))
+    return GetInterface()->ErrorWithMessage<bool>(
+        __PRETTY_FUNCTION__,
+        "Couldn't find value for key 'type' in stop reason dictionary.", error);
+
+  switch (stop_reason_type) {
+  case lldb::eStopReasonNone:
+    break;
+  case lldb::eStopReasonBreakpoint: {
+    lldb::break_id_t break_id;
+    data_dict->GetValueForKeyAsInteger("break_id", break_id,
+                                       LLDB_INVALID_BREAK_ID);
+    stop_info_sp =
+        StopInfo::CreateStopReasonWithBreakpointSiteID(*this, break_id);
+  } break;
+  case lldb::eStopReasonSignal: {
+    int signal;
+    llvm::StringRef description;
+    data_dict->GetValueForKeyAsInteger("signal", signal,
+                                       LLDB_INVALID_SIGNAL_NUMBER);
+    data_dict->GetValueForKeyAsString("desc", description);
+    stop_info_sp =
+        StopInfo::CreateStopReasonWithSignal(*this, signal, description.data());
+  } break;
+  default:
+    return GetInterface()->ErrorWithMessage<bool>(
+        __PRETTY_FUNCTION__,
+        llvm::Twine("Unsupported stop reason type (" +
+                    llvm::Twine(stop_reason_type) + llvm::Twine(")."))
+            .str(),
+        error);
+  }
+
+  SetStopInfo(stop_info_sp);
+  return true;
+}
+
+void ScriptedThread::RefreshStateAfterStop() {
+  // TODO: Implement
+  if (m_reg_context_sp)
+    m_reg_context_sp->InvalidateAllRegisters();
+}
+
+lldb::ScriptedThreadInterfaceSP ScriptedThread::GetInterface() const {
+  return m_scripted_process.GetInterface().GetScriptedThreadInterface();
+}
+
+std::shared_ptr<DynamicRegisterInfo> ScriptedThread::GetDynamicRegisterInfo() {
+  CheckInterpreterAndScriptObject();
+
+  if (!m_register_info_sp) {
+    StructuredData::DictionarySP reg_info = GetInterface()->GetRegisterInfo();
+    if (!reg_info)
+      return nullptr;
+
+    m_register_info_sp = std::make_shared<DynamicRegisterInfo>(
+        *reg_info, m_scripted_process.GetTarget().GetArchitecture());
+    assert(m_register_info_sp->GetNumRegisters() > 0);
+    assert(m_register_info_sp->GetNumRegisterSets() > 0);
+  }
+
+  return m_register_info_sp;
+}

diff  --git a/lldb/source/Plugins/Process/scripted/ScriptedThread.h b/lldb/source/Plugins/Process/scripted/ScriptedThread.h
new file mode 100644
index 0000000000000..cdcd543702a48
--- /dev/null
+++ b/lldb/source/Plugins/Process/scripted/ScriptedThread.h
@@ -0,0 +1,68 @@
+//===-- ScriptedThread.h ----------------------------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLDB_SOURCE_PLUGINS_SCRIPTED_THREAD_H
+#define LLDB_SOURCE_PLUGINS_SCRIPTED_THREAD_H
+
+#include <string>
+
+#include "ScriptedProcess.h"
+
+#include "Plugins/Process/Utility/RegisterContextMemory.h"
+#include "lldb/Interpreter/ScriptInterpreter.h"
+#include "lldb/Target//DynamicRegisterInfo.h"
+#include "lldb/Target/Thread.h"
+
+namespace lldb_private {
+class ScriptedProcess;
+}
+
+namespace lldb_private {
+
+class ScriptedThread : public lldb_private::Thread {
+public:
+  ScriptedThread(ScriptedProcess &process, Status &error);
+
+  ~ScriptedThread() override;
+
+  lldb::RegisterContextSP GetRegisterContext() override;
+
+  lldb::RegisterContextSP
+  CreateRegisterContextForFrame(lldb_private::StackFrame *frame) override;
+
+  bool CalculateStopInfo() override;
+
+  const char *GetInfo() override { return nullptr; }
+
+  const char *GetName() override;
+
+  const char *GetQueueName() override;
+
+  void WillResume(lldb::StateType resume_state) override;
+
+  void RefreshStateAfterStop() override;
+
+  void ClearStackFrames() override;
+
+private:
+  void CheckInterpreterAndScriptObject() const;
+  lldb::ScriptedThreadInterfaceSP GetInterface() const;
+
+  ScriptedThread(const ScriptedThread &) = delete;
+  const ScriptedThread &operator=(const ScriptedThread &) = delete;
+
+  std::shared_ptr<DynamicRegisterInfo> GetDynamicRegisterInfo();
+
+  const ScriptedProcess &m_scripted_process;
+  std::shared_ptr<DynamicRegisterInfo> m_register_info_sp = nullptr;
+  lldb_private::StructuredData::ObjectSP m_script_object_sp = nullptr;
+};
+
+} // namespace lldb_private
+
+#endif // LLDB_SOURCE_PLUGINS_SCRIPTED_THREAD_H

diff  --git a/lldb/source/Plugins/ScriptInterpreter/Python/CMakeLists.txt b/lldb/source/Plugins/ScriptInterpreter/Python/CMakeLists.txt
index 98dc552ba6489..f3c20a741c1f4 100644
--- a/lldb/source/Plugins/ScriptInterpreter/Python/CMakeLists.txt
+++ b/lldb/source/Plugins/ScriptInterpreter/Python/CMakeLists.txt
@@ -13,6 +13,7 @@ add_lldb_library(lldbPluginScriptInterpreterPython PLUGIN
   ScriptInterpreterPython.cpp
   ScriptedPythonInterface.cpp
   ScriptedProcessPythonInterface.cpp
+  ScriptedThreadPythonInterface.cpp
   SWIGPythonBridge.cpp
 
   LINK_LIBS

diff  --git a/lldb/source/Plugins/ScriptInterpreter/Python/SWIGPythonBridge.h b/lldb/source/Plugins/ScriptInterpreter/Python/SWIGPythonBridge.h
index 1ef792bcf303b..8d6e7dc4ee789 100644
--- a/lldb/source/Plugins/ScriptInterpreter/Python/SWIGPythonBridge.h
+++ b/lldb/source/Plugins/ScriptInterpreter/Python/SWIGPythonBridge.h
@@ -46,6 +46,10 @@ extern "C" void *LLDBSwigPythonCreateScriptedProcess(
     const lldb::TargetSP &target_sp, StructuredDataImpl *args_impl,
     std::string &error_string);
 
+extern "C" void *LLDBSwigPythonCreateScriptedThread(
+    const char *python_class_name, const char *session_dictionary_name,
+    const lldb::TargetSP &target_sp, std::string &error_string);
+
 extern "C" void *LLDBSWIGPython_CastPyObjectToSBData(void *data);
 extern "C" void *LLDBSWIGPython_CastPyObjectToSBError(void *data);
 extern "C" void *LLDBSWIGPython_CastPyObjectToSBValue(void *data);

diff  --git a/lldb/source/Plugins/ScriptInterpreter/Python/ScriptedProcessPythonInterface.cpp b/lldb/source/Plugins/ScriptInterpreter/Python/ScriptedProcessPythonInterface.cpp
index 7cc74803bd613..32be169f0d1de 100644
--- a/lldb/source/Plugins/ScriptInterpreter/Python/ScriptedProcessPythonInterface.cpp
+++ b/lldb/source/Plugins/ScriptInterpreter/Python/ScriptedProcessPythonInterface.cpp
@@ -19,6 +19,7 @@
 #include "SWIGPythonBridge.h"
 #include "ScriptInterpreterPythonImpl.h"
 #include "ScriptedProcessPythonInterface.h"
+#include "ScriptedThreadPythonInterface.h"
 
 using namespace lldb;
 using namespace lldb_private;
@@ -71,18 +72,8 @@ bool ScriptedProcessPythonInterface::ShouldStop() {
   Status error;
   StructuredData::ObjectSP obj = Dispatch("is_alive", error);
 
-  auto error_with_message = [](llvm::StringRef message) {
-    LLDB_LOGF(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS),
-              "ScriptedProcess::%s ERROR = %s", __FUNCTION__, message.data());
-    return false;
-  };
-
-  if (!obj || !obj->IsValid() || error.Fail()) {
-    return error_with_message(llvm::Twine("Null or invalid object (" +
-                                          llvm::Twine(error.AsCString()) +
-                                          llvm::Twine(")."))
-                                  .str());
-  }
+  if (!CheckStructuredDataObject(__PRETTY_FUNCTION__, obj, error))
+    return {};
 
   return obj->GetBooleanValue();
 }
@@ -100,24 +91,11 @@ ScriptedProcessPythonInterface::GetMemoryRegionContainingAddress(
 
 StructuredData::DictionarySP
 ScriptedProcessPythonInterface::GetThreadWithID(lldb::tid_t tid) {
-  Locker py_lock(&m_interpreter, Locker::AcquireLock | Locker::NoSTDIN,
-                 Locker::FreeLock);
-
-  auto error_with_message = [](llvm::StringRef message) {
-    LLDB_LOGF(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS),
-              "ScriptedProcess::%s ERROR = %s", __FUNCTION__, message.data());
-    return StructuredData::DictionarySP();
-  };
-
   Status error;
   StructuredData::ObjectSP obj = Dispatch("get_thread_with_id", error, tid);
 
-  if (!obj || !obj->IsValid() || error.Fail()) {
-    return error_with_message(llvm::Twine("Null or invalid object (" +
-                                          llvm::Twine(error.AsCString()) +
-                                          llvm::Twine(")."))
-                                  .str());
-  }
+  if (!CheckStructuredDataObject(__PRETTY_FUNCTION__, obj, error))
+    return {};
 
   StructuredData::DictionarySP dict{obj->GetAsDictionary()};
 
@@ -145,18 +123,8 @@ lldb::pid_t ScriptedProcessPythonInterface::GetProcessID() {
   Status error;
   StructuredData::ObjectSP obj = Dispatch("get_process_id", error);
 
-  auto error_with_message = [](llvm::StringRef message) {
-    LLDB_LOGF(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS),
-              "ScriptedProcess::%s ERROR = %s", __FUNCTION__, message.data());
+  if (!CheckStructuredDataObject(__PRETTY_FUNCTION__, obj, error))
     return LLDB_INVALID_PROCESS_ID;
-  };
-
-  if (!obj || !obj->IsValid() || error.Fail()) {
-    return error_with_message(llvm::Twine("Null or invalid object (" +
-                                          llvm::Twine(error.AsCString()) +
-                                          llvm::Twine(")."))
-                                  .str());
-  }
 
   return obj->GetIntegerValue(LLDB_INVALID_PROCESS_ID);
 }
@@ -165,20 +133,30 @@ bool ScriptedProcessPythonInterface::IsAlive() {
   Status error;
   StructuredData::ObjectSP obj = Dispatch("is_alive", error);
 
-  auto error_with_message = [](llvm::StringRef message) {
-    LLDB_LOGF(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS),
-              "ScriptedProcess::%s ERROR = %s", __FUNCTION__, message.data());
-    return false;
-  };
-
-  if (!obj || !obj->IsValid() || error.Fail()) {
-    return error_with_message(llvm::Twine("Null or invalid object (" +
-                                          llvm::Twine(error.AsCString()) +
-                                          llvm::Twine(")."))
-                                  .str());
-  }
+  if (!CheckStructuredDataObject(__PRETTY_FUNCTION__, obj, error))
+    return {};
 
   return obj->GetBooleanValue();
 }
 
+llvm::Optional<std::string>
+ScriptedProcessPythonInterface::GetScriptedThreadPluginName() {
+  Status error;
+  StructuredData::ObjectSP obj = Dispatch("get_scripted_thread_plugin", error);
+
+  if (!CheckStructuredDataObject(__PRETTY_FUNCTION__, obj, error))
+    return {};
+
+  return obj->GetStringValue().str();
+}
+
+lldb::ScriptedThreadInterfaceSP
+ScriptedProcessPythonInterface::GetScriptedThreadInterface() {
+  if (!m_scripted_thread_interface_sp)
+    m_scripted_thread_interface_sp =
+        std::make_shared<ScriptedThreadPythonInterface>(m_interpreter);
+
+  return m_scripted_thread_interface_sp;
+}
+
 #endif

diff  --git a/lldb/source/Plugins/ScriptInterpreter/Python/ScriptedProcessPythonInterface.h b/lldb/source/Plugins/ScriptInterpreter/Python/ScriptedProcessPythonInterface.h
index 3ad1cdf6e18a8..eb3d2f3424436 100644
--- a/lldb/source/Plugins/ScriptInterpreter/Python/ScriptedProcessPythonInterface.h
+++ b/lldb/source/Plugins/ScriptInterpreter/Python/ScriptedProcessPythonInterface.h
@@ -50,6 +50,11 @@ class ScriptedProcessPythonInterface : public ScriptedProcessInterface,
   lldb::pid_t GetProcessID() override;
 
   bool IsAlive() override;
+
+  llvm::Optional<std::string> GetScriptedThreadPluginName() override;
+
+private:
+  lldb::ScriptedThreadInterfaceSP GetScriptedThreadInterface() override;
 };
 } // namespace lldb_private
 

diff  --git a/lldb/source/Plugins/ScriptInterpreter/Python/ScriptedPythonInterface.cpp b/lldb/source/Plugins/ScriptInterpreter/Python/ScriptedPythonInterface.cpp
index a38cb104c0c63..e8fb38e6492f1 100644
--- a/lldb/source/Plugins/ScriptInterpreter/Python/ScriptedPythonInterface.cpp
+++ b/lldb/source/Plugins/ScriptInterpreter/Python/ScriptedPythonInterface.cpp
@@ -35,6 +35,14 @@ ScriptedPythonInterface::GetStatusFromMethod(llvm::StringRef method_name) {
   return error;
 }
 
+template <>
+StructuredData::DictionarySP
+ScriptedPythonInterface::ExtractValueFromPythonObject<
+    StructuredData::DictionarySP>(python::PythonObject &p, Status &error) {
+  python::PythonDictionary result_dict(python::PyRefType::Borrowed, p.get());
+  return result_dict.CreateStructuredDictionary();
+}
+
 template <>
 Status ScriptedPythonInterface::ExtractValueFromPythonObject<Status>(
     python::PythonObject &p, Status &error) {

diff  --git a/lldb/source/Plugins/ScriptInterpreter/Python/ScriptedPythonInterface.h b/lldb/source/Plugins/ScriptInterpreter/Python/ScriptedPythonInterface.h
index bac4efbe76d8d..9f76ed8fba687 100644
--- a/lldb/source/Plugins/ScriptInterpreter/Python/ScriptedPythonInterface.h
+++ b/lldb/source/Plugins/ScriptInterpreter/Python/ScriptedPythonInterface.h
@@ -38,15 +38,13 @@ class ScriptedPythonInterface : virtual public ScriptedInterface {
     using namespace python;
     using Locker = ScriptInterpreterPythonImpl::Locker;
 
-    auto error_with_message = [&method_name, &error](llvm::StringRef message) {
-      error.SetErrorStringWithFormatv(
-          "ScriptedPythonInterface::{0} ({1}) ERROR = {2}", __FUNCTION__,
-          method_name, message);
-      return T();
-    };
-
+    std::string caller_signature =
+        llvm::Twine(__PRETTY_FUNCTION__ + llvm::Twine(" (") +
+                    llvm::Twine(method_name) + llvm::Twine(")"))
+            .str();
     if (!m_object_instance_sp)
-      return error_with_message("Python object ill-formed");
+      return ErrorWithMessage<T>(caller_signature, "Python object ill-formed",
+                                 error);
 
     Locker py_lock(&m_interpreter, Locker::AcquireLock | Locker::NoSTDIN,
                    Locker::FreeLock);
@@ -55,7 +53,8 @@ class ScriptedPythonInterface : virtual public ScriptedInterface {
                              (PyObject *)m_object_instance_sp->GetValue());
 
     if (!implementor.IsAllocated())
-      return error_with_message("Python implementor not allocated.");
+      return ErrorWithMessage<T>(caller_signature,
+                                 "Python implementor not allocated.", error);
 
     PythonObject pmeth(
         PyRefType::Owned,
@@ -65,12 +64,14 @@ class ScriptedPythonInterface : virtual public ScriptedInterface {
       PyErr_Clear();
 
     if (!pmeth.IsAllocated())
-      return error_with_message("Python method not allocated.");
+      return ErrorWithMessage<T>(caller_signature,
+                                 "Python method not allocated.", error);
 
     if (PyCallable_Check(pmeth.get()) == 0) {
       if (PyErr_Occurred())
         PyErr_Clear();
-      return error_with_message("Python method not callable.");
+      return ErrorWithMessage<T>(caller_signature,
+                                 "Python method not callable.", error);
     }
 
     if (PyErr_Occurred())
@@ -96,11 +97,13 @@ class ScriptedPythonInterface : virtual public ScriptedInterface {
     if (PyErr_Occurred()) {
       PyErr_Print();
       PyErr_Clear();
-      return error_with_message("Python method could not be called.");
+      return ErrorWithMessage<T>(caller_signature,
+                                 "Python method could not be called.", error);
     }
 
     if (!py_return.IsAllocated())
-      return error_with_message("Returned object is null.");
+      return ErrorWithMessage<T>(caller_signature, "Returned object is null.",
+                                 error);
 
     return ExtractValueFromPythonObject<T>(py_return, error);
   }
@@ -123,6 +126,11 @@ class ScriptedPythonInterface : virtual public ScriptedInterface {
   ScriptInterpreterPythonImpl &m_interpreter;
 };
 
+template <>
+StructuredData::DictionarySP
+ScriptedPythonInterface::ExtractValueFromPythonObject<
+    StructuredData::DictionarySP>(python::PythonObject &p, Status &error);
+
 template <>
 Status ScriptedPythonInterface::ExtractValueFromPythonObject<Status>(
     python::PythonObject &p, Status &error);

diff  --git a/lldb/source/Plugins/ScriptInterpreter/Python/ScriptedThreadPythonInterface.cpp b/lldb/source/Plugins/ScriptInterpreter/Python/ScriptedThreadPythonInterface.cpp
new file mode 100644
index 0000000000000..c2aa4381a1cee
--- /dev/null
+++ b/lldb/source/Plugins/ScriptInterpreter/Python/ScriptedThreadPythonInterface.cpp
@@ -0,0 +1,136 @@
+//===-- ScriptedThreadPythonInterface.cpp ---------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "lldb/Host/Config.h"
+#include "lldb/Utility/Log.h"
+#include "lldb/Utility/Logging.h"
+#include "lldb/lldb-enumerations.h"
+
+#if LLDB_ENABLE_PYTHON
+
+// LLDB Python header must be included first
+#include "lldb-python.h"
+
+#include "SWIGPythonBridge.h"
+#include "ScriptInterpreterPythonImpl.h"
+#include "ScriptedThreadPythonInterface.h"
+
+using namespace lldb;
+using namespace lldb_private;
+using namespace lldb_private::python;
+using Locker = ScriptInterpreterPythonImpl::Locker;
+
+ScriptedThreadPythonInterface::ScriptedThreadPythonInterface(
+    ScriptInterpreterPythonImpl &interpreter)
+    : ScriptedThreadInterface(), ScriptedPythonInterface(interpreter) {}
+
+StructuredData::GenericSP ScriptedThreadPythonInterface::CreatePluginObject(
+    const llvm::StringRef class_name, ExecutionContext &exe_ctx,
+    StructuredData::DictionarySP args_sp) {
+
+  if (class_name.empty())
+    return {};
+
+  Locker py_lock(&m_interpreter, Locker::AcquireLock | Locker::NoSTDIN,
+                 Locker::FreeLock);
+
+  std::string error_string;
+
+  TargetSP target_sp = exe_ctx.GetTargetSP();
+
+  void *ret_val = LLDBSwigPythonCreateScriptedThread(
+      class_name.str().c_str(), m_interpreter.GetDictionaryName(), target_sp,
+      error_string);
+
+  if (!ret_val)
+    return {};
+
+  m_object_instance_sp =
+      StructuredData::GenericSP(new StructuredPythonObject(ret_val));
+
+  return m_object_instance_sp;
+}
+
+lldb::tid_t ScriptedThreadPythonInterface::GetThreadID() {
+  Status error;
+  StructuredData::ObjectSP obj = Dispatch("get_thread_id", error);
+
+  if (!CheckStructuredDataObject(__PRETTY_FUNCTION__, obj, error))
+    return LLDB_INVALID_THREAD_ID;
+
+  return obj->GetIntegerValue(LLDB_INVALID_THREAD_ID);
+}
+
+llvm::Optional<std::string> ScriptedThreadPythonInterface::GetName() {
+  Status error;
+  StructuredData::ObjectSP obj = Dispatch("get_name", error);
+
+  if (!CheckStructuredDataObject(__PRETTY_FUNCTION__, obj, error))
+    return {};
+
+  return obj->GetStringValue().str();
+}
+
+lldb::StateType ScriptedThreadPythonInterface::GetState() {
+  Status error;
+  StructuredData::ObjectSP obj = Dispatch("get_state", error);
+
+  if (!CheckStructuredDataObject(__PRETTY_FUNCTION__, obj, error))
+    return eStateInvalid;
+
+  return static_cast<StateType>(obj->GetIntegerValue(eStateInvalid));
+}
+
+llvm::Optional<std::string> ScriptedThreadPythonInterface::GetQueue() {
+  Status error;
+  StructuredData::ObjectSP obj = Dispatch("get_queue", error);
+
+  if (!CheckStructuredDataObject(__PRETTY_FUNCTION__, obj, error))
+    return {};
+
+  return obj->GetStringValue().str();
+}
+
+StructuredData::DictionarySP ScriptedThreadPythonInterface::GetStopReason() {
+  Status error;
+  StructuredData::DictionarySP dict =
+      Dispatch<StructuredData::DictionarySP>("get_stop_reason", error);
+
+  if (!CheckStructuredDataObject(__PRETTY_FUNCTION__, dict, error))
+    return {};
+
+  return dict;
+}
+
+StructuredData::ArraySP ScriptedThreadPythonInterface::GetStackFrames() {
+  return nullptr;
+}
+
+StructuredData::DictionarySP ScriptedThreadPythonInterface::GetRegisterInfo() {
+  Status error;
+  StructuredData::DictionarySP dict =
+      Dispatch<StructuredData::DictionarySP>("get_register_info", error);
+
+  if (!CheckStructuredDataObject(__PRETTY_FUNCTION__, dict, error))
+    return {};
+
+  return dict;
+}
+
+llvm::Optional<std::string>
+ScriptedThreadPythonInterface::GetRegisterContext() {
+  Status error;
+  StructuredData::ObjectSP obj = Dispatch("get_register_context", error);
+
+  if (!CheckStructuredDataObject(__PRETTY_FUNCTION__, obj, error))
+    return {};
+
+  return obj->GetAsString()->GetValue().str();
+}
+
+#endif

diff  --git a/lldb/source/Plugins/ScriptInterpreter/Python/ScriptedThreadPythonInterface.h b/lldb/source/Plugins/ScriptInterpreter/Python/ScriptedThreadPythonInterface.h
new file mode 100644
index 0000000000000..996b8d43136bb
--- /dev/null
+++ b/lldb/source/Plugins/ScriptInterpreter/Python/ScriptedThreadPythonInterface.h
@@ -0,0 +1,48 @@
+//===-- ScriptedThreadPythonInterface.h ------------------------*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLDB_PLUGINS_SCRIPTINTERPRETER_PYTHON_SCRIPTEDTHREADPYTHONINTERFACE_H
+#define LLDB_PLUGINS_SCRIPTINTERPRETER_PYTHON_SCRIPTEDTHREADPYTHONINTERFACE_H
+
+#include "lldb/Host/Config.h"
+
+#if LLDB_ENABLE_PYTHON
+
+#include "ScriptedPythonInterface.h"
+#include "lldb/Interpreter/ScriptedProcessInterface.h"
+
+namespace lldb_private {
+class ScriptedThreadPythonInterface : public ScriptedThreadInterface,
+                                      public ScriptedPythonInterface {
+public:
+  ScriptedThreadPythonInterface(ScriptInterpreterPythonImpl &interpreter);
+
+  StructuredData::GenericSP
+  CreatePluginObject(llvm::StringRef class_name, ExecutionContext &exe_ctx,
+                     StructuredData::DictionarySP args_sp) override;
+
+  lldb::tid_t GetThreadID() override;
+
+  llvm::Optional<std::string> GetName() override;
+
+  lldb::StateType GetState() override;
+
+  llvm::Optional<std::string> GetQueue() override;
+
+  StructuredData::DictionarySP GetStopReason() override;
+
+  StructuredData::ArraySP GetStackFrames() override;
+
+  StructuredData::DictionarySP GetRegisterInfo() override;
+
+  llvm::Optional<std::string> GetRegisterContext() override;
+};
+} // namespace lldb_private
+
+#endif // LLDB_ENABLE_PYTHON
+#endif // LLDB_PLUGINS_SCRIPTINTERPRETER_PYTHON_SCRIPTEDPROCESSTHREADINTERFACE_H

diff  --git a/lldb/test/API/functionalities/scripted_process/TestScriptedProcess.py b/lldb/test/API/functionalities/scripted_process/TestScriptedProcess.py
index 5cf49ab37791b..70ee1a4d6592b 100644
--- a/lldb/test/API/functionalities/scripted_process/TestScriptedProcess.py
+++ b/lldb/test/API/functionalities/scripted_process/TestScriptedProcess.py
@@ -72,6 +72,28 @@ def test_launch_scripted_process_sbapi(self):
         self.assertTrue(error.Success(), "Failed to read memory from scripted process.")
         self.assertEqual(hello_world, memory_read)
 
+        self.assertEqual(process.GetNumThreads(), 1)
+
+        thread = process.GetSelectedThread()
+        self.assertTrue(thread, "Invalid thread.")
+        self.assertEqual(thread.GetThreadID(), 0x19)
+        self.assertEqual(thread.GetName(), "MyScriptedThread.thread-1")
+        self.assertEqual(thread.GetStopReason(), lldb.eStopReasonSignal)
+
+        self.assertGreater(thread.GetNumFrames(), 0)
+
+        frame = thread.GetFrameAtIndex(0)
+        register_set = frame.registers # Returns an SBValueList.
+        for regs in register_set:
+            if 'GPR' in regs.name:
+                registers  = regs
+                break
+
+        self.assertTrue(registers, "Invalid General Purpose Registers Set")
+        self.assertEqual(registers.GetNumChildren(), 21)
+        for idx, reg in enumerate(registers, start=1):
+            self.assertEqual(idx, int(reg.value, 16))
+
     def test_launch_scripted_process_cli(self):
         """Test that we can launch an lldb scripted process from the command
         line, check its process ID and read string from memory."""

diff  --git a/lldb/unittests/ScriptInterpreter/Python/PythonTestSuite.cpp b/lldb/unittests/ScriptInterpreter/Python/PythonTestSuite.cpp
index eb02ce2243eca..e636b8cf597ee 100644
--- a/lldb/unittests/ScriptInterpreter/Python/PythonTestSuite.cpp
+++ b/lldb/unittests/ScriptInterpreter/Python/PythonTestSuite.cpp
@@ -223,6 +223,12 @@ extern "C" void *LLDBSwigPythonCreateScriptedProcess(
   return nullptr;
 }
 
+extern "C" void *LLDBSwigPythonCreateScriptedThread(
+    const char *python_class_name, const char *session_dictionary_name,
+    const lldb::TargetSP &target_sp, std::string &error_string) {
+  return nullptr;
+}
+
 extern "C" void *
 LLDBSWIGPython_CreateFrameRecognizer(const char *python_class_name,
                                      const char *session_dictionary_name) {


        


More information about the lldb-commits mailing list