xref: /llvm-project/lldb/source/Plugins/Process/scripted/ScriptedThread.cpp (revision 59d8dd79e1f9dead2dc2756e139073083e487228)
1 //===-- ScriptedThread.cpp ------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "ScriptedThread.h"
10 
11 #include "Plugins/Process/Utility/RegisterContextThreadMemory.h"
12 #include "lldb/Target/OperatingSystem.h"
13 #include "lldb/Target/Process.h"
14 #include "lldb/Target/RegisterContext.h"
15 #include "lldb/Target/StopInfo.h"
16 #include "lldb/Target/Unwind.h"
17 #include "lldb/Utility/DataBufferHeap.h"
18 #include "lldb/Utility/Log.h"
19 #include "lldb/Utility/Logging.h"
20 
21 #include <memory>
22 
23 using namespace lldb;
24 using namespace lldb_private;
25 
26 void ScriptedThread::CheckInterpreterAndScriptObject() const {
27   lldbassert(m_script_object_sp && "Invalid Script Object.");
28   lldbassert(GetInterface() && "Invalid Scripted Thread Interface.");
29 }
30 
31 ScriptedThread::ScriptedThread(ScriptedProcess &process, Status &error)
32     : Thread(process, LLDB_INVALID_THREAD_ID), m_scripted_process(process) {
33   if (!process.IsValid()) {
34     error.SetErrorString("Invalid scripted process");
35     return;
36   }
37 
38   process.CheckInterpreterAndScriptObject();
39 
40   auto scripted_thread_interface = GetInterface();
41   if (!scripted_thread_interface) {
42     error.SetErrorString("Failed to get scripted thread interface.");
43     return;
44   }
45 
46   llvm::Optional<std::string> class_name =
47       process.GetInterface().GetScriptedThreadPluginName();
48   if (!class_name || class_name->empty()) {
49     error.SetErrorString("Failed to get scripted thread class name.");
50     return;
51   }
52 
53   ExecutionContext exe_ctx(process);
54 
55   StructuredData::GenericSP object_sp =
56       scripted_thread_interface->CreatePluginObject(
57           class_name->c_str(), exe_ctx,
58           process.m_scripted_process_info.GetDictionarySP());
59   if (!object_sp || !object_sp->IsValid()) {
60     error.SetErrorString("Failed to create valid script object");
61     return;
62   }
63 
64   m_script_object_sp = object_sp;
65 
66   SetID(scripted_thread_interface->GetThreadID());
67 
68   llvm::Optional<std::string> reg_data =
69       scripted_thread_interface->GetRegisterContext();
70   if (!reg_data) {
71     error.SetErrorString("Failed to get scripted thread registers data.");
72     return;
73   }
74 
75   DataBufferSP data_sp(
76       std::make_shared<DataBufferHeap>(reg_data->c_str(), reg_data->size()));
77 
78   if (!data_sp->GetByteSize()) {
79     error.SetErrorString("Failed to copy raw registers data.");
80     return;
81   }
82 
83   std::shared_ptr<RegisterContextMemory> reg_ctx_memory =
84       std::make_shared<RegisterContextMemory>(
85           *this, 0, *GetDynamicRegisterInfo(), LLDB_INVALID_ADDRESS);
86   if (!reg_ctx_memory) {
87     error.SetErrorString("Failed to create a register context.");
88     return;
89   }
90 
91   reg_ctx_memory->SetAllRegisterData(data_sp);
92   m_reg_context_sp = reg_ctx_memory;
93 }
94 
95 ScriptedThread::~ScriptedThread() { DestroyThread(); }
96 
97 const char *ScriptedThread::GetName() {
98   CheckInterpreterAndScriptObject();
99   llvm::Optional<std::string> thread_name = GetInterface()->GetName();
100   if (!thread_name)
101     return nullptr;
102   return ConstString(thread_name->c_str()).AsCString();
103 }
104 
105 const char *ScriptedThread::GetQueueName() {
106   CheckInterpreterAndScriptObject();
107   llvm::Optional<std::string> queue_name = GetInterface()->GetQueue();
108   if (!queue_name)
109     return nullptr;
110   return ConstString(queue_name->c_str()).AsCString();
111 }
112 
113 void ScriptedThread::WillResume(StateType resume_state) {}
114 
115 void ScriptedThread::ClearStackFrames() { Thread::ClearStackFrames(); }
116 
117 RegisterContextSP ScriptedThread::GetRegisterContext() {
118   if (!m_reg_context_sp) {
119     m_reg_context_sp = std::make_shared<RegisterContextThreadMemory>(
120         *this, LLDB_INVALID_ADDRESS);
121     GetInterface()->GetRegisterContext();
122   }
123   return m_reg_context_sp;
124 }
125 
126 RegisterContextSP
127 ScriptedThread::CreateRegisterContextForFrame(StackFrame *frame) {
128   uint32_t concrete_frame_idx = frame ? frame->GetConcreteFrameIndex() : 0;
129 
130   if (concrete_frame_idx == 0)
131     return GetRegisterContext();
132   return GetUnwinder().CreateRegisterContextForFrame(frame);
133 }
134 
135 bool ScriptedThread::CalculateStopInfo() {
136   StructuredData::DictionarySP dict_sp = GetInterface()->GetStopReason();
137 
138   Status error;
139   lldb::StopInfoSP stop_info_sp;
140   lldb::StopReason stop_reason_type;
141 
142   if (!dict_sp->GetValueForKeyAsInteger("type", stop_reason_type))
143     return GetInterface()->ErrorWithMessage<bool>(
144         __PRETTY_FUNCTION__,
145         "Couldn't find value for key 'type' in stop reason dictionary.", error);
146 
147   StructuredData::Dictionary *data_dict;
148   if (!dict_sp->GetValueForKeyAsDictionary("data", data_dict))
149     return GetInterface()->ErrorWithMessage<bool>(
150         __PRETTY_FUNCTION__,
151         "Couldn't find value for key 'type' in stop reason dictionary.", error);
152 
153   switch (stop_reason_type) {
154   case lldb::eStopReasonNone:
155     break;
156   case lldb::eStopReasonBreakpoint: {
157     lldb::break_id_t break_id;
158     data_dict->GetValueForKeyAsInteger("break_id", break_id,
159                                        LLDB_INVALID_BREAK_ID);
160     stop_info_sp =
161         StopInfo::CreateStopReasonWithBreakpointSiteID(*this, break_id);
162   } break;
163   case lldb::eStopReasonSignal: {
164     int signal;
165     llvm::StringRef description;
166     data_dict->GetValueForKeyAsInteger("signal", signal,
167                                        LLDB_INVALID_SIGNAL_NUMBER);
168     data_dict->GetValueForKeyAsString("desc", description);
169     stop_info_sp =
170         StopInfo::CreateStopReasonWithSignal(*this, signal, description.data());
171   } break;
172   default:
173     return GetInterface()->ErrorWithMessage<bool>(
174         __PRETTY_FUNCTION__,
175         llvm::Twine("Unsupported stop reason type (" +
176                     llvm::Twine(stop_reason_type) + llvm::Twine(")."))
177             .str(),
178         error);
179   }
180 
181   SetStopInfo(stop_info_sp);
182   return true;
183 }
184 
185 void ScriptedThread::RefreshStateAfterStop() {
186   // TODO: Implement
187   if (m_reg_context_sp)
188     m_reg_context_sp->InvalidateAllRegisters();
189 }
190 
191 lldb::ScriptedThreadInterfaceSP ScriptedThread::GetInterface() const {
192   return m_scripted_process.GetInterface().GetScriptedThreadInterface();
193 }
194 
195 std::shared_ptr<DynamicRegisterInfo> ScriptedThread::GetDynamicRegisterInfo() {
196   CheckInterpreterAndScriptObject();
197 
198   if (!m_register_info_sp) {
199     StructuredData::DictionarySP reg_info = GetInterface()->GetRegisterInfo();
200     if (!reg_info)
201       return nullptr;
202 
203     m_register_info_sp = std::make_shared<DynamicRegisterInfo>(
204         *reg_info, m_scripted_process.GetTarget().GetArchitecture());
205     assert(m_register_info_sp->GetNumRegisters() > 0);
206     assert(m_register_info_sp->GetNumRegisterSets() > 0);
207   }
208 
209   return m_register_info_sp;
210 }
211