1 //===-- OperatingSystemPython.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 "lldb/Host/Config.h" 10 11 #if LLDB_ENABLE_PYTHON 12 13 #include "OperatingSystemPython.h" 14 15 #include "Plugins/Process/Utility/RegisterContextDummy.h" 16 #include "Plugins/Process/Utility/RegisterContextMemory.h" 17 #include "Plugins/Process/Utility/ThreadMemory.h" 18 #include "lldb/Core/Debugger.h" 19 #include "lldb/Core/Module.h" 20 #include "lldb/Core/PluginManager.h" 21 #include "lldb/Core/ValueObjectVariable.h" 22 #include "lldb/Interpreter/CommandInterpreter.h" 23 #include "lldb/Interpreter/ScriptInterpreter.h" 24 #include "lldb/Symbol/ObjectFile.h" 25 #include "lldb/Symbol/VariableList.h" 26 #include "lldb/Target/Process.h" 27 #include "lldb/Target/StopInfo.h" 28 #include "lldb/Target/Target.h" 29 #include "lldb/Target/Thread.h" 30 #include "lldb/Target/ThreadList.h" 31 #include "lldb/Utility/DataBufferHeap.h" 32 #include "lldb/Utility/RegisterValue.h" 33 #include "lldb/Utility/StreamString.h" 34 #include "lldb/Utility/StructuredData.h" 35 36 #include <memory> 37 38 using namespace lldb; 39 using namespace lldb_private; 40 41 LLDB_PLUGIN_DEFINE(OperatingSystemPython) 42 43 void OperatingSystemPython::Initialize() { 44 PluginManager::RegisterPlugin(GetPluginNameStatic(), 45 GetPluginDescriptionStatic(), CreateInstance, 46 nullptr); 47 } 48 49 void OperatingSystemPython::Terminate() { 50 PluginManager::UnregisterPlugin(CreateInstance); 51 } 52 53 OperatingSystem *OperatingSystemPython::CreateInstance(Process *process, 54 bool force) { 55 // Python OperatingSystem plug-ins must be requested by name, so force must 56 // be true 57 FileSpec python_os_plugin_spec(process->GetPythonOSPluginPath()); 58 if (python_os_plugin_spec && 59 FileSystem::Instance().Exists(python_os_plugin_spec)) { 60 std::unique_ptr<OperatingSystemPython> os_up( 61 new OperatingSystemPython(process, python_os_plugin_spec)); 62 if (os_up.get() && os_up->IsValid()) 63 return os_up.release(); 64 } 65 return nullptr; 66 } 67 68 ConstString OperatingSystemPython::GetPluginNameStatic() { 69 static ConstString g_name("python"); 70 return g_name; 71 } 72 73 const char *OperatingSystemPython::GetPluginDescriptionStatic() { 74 return "Operating system plug-in that gathers OS information from a python " 75 "class that implements the necessary OperatingSystem functionality."; 76 } 77 78 OperatingSystemPython::OperatingSystemPython(lldb_private::Process *process, 79 const FileSpec &python_module_path) 80 : OperatingSystem(process), m_thread_list_valobj_sp(), m_register_info_up(), 81 m_interpreter(nullptr), m_python_object_sp() { 82 if (!process) 83 return; 84 TargetSP target_sp = process->CalculateTarget(); 85 if (!target_sp) 86 return; 87 m_interpreter = target_sp->GetDebugger().GetScriptInterpreter(); 88 if (m_interpreter) { 89 90 std::string os_plugin_class_name( 91 python_module_path.GetFilename().AsCString("")); 92 if (!os_plugin_class_name.empty()) { 93 LoadScriptOptions options; 94 char python_module_path_cstr[PATH_MAX]; 95 python_module_path.GetPath(python_module_path_cstr, 96 sizeof(python_module_path_cstr)); 97 Status error; 98 if (m_interpreter->LoadScriptingModule(python_module_path_cstr, options, 99 error)) { 100 // Strip the ".py" extension if there is one 101 size_t py_extension_pos = os_plugin_class_name.rfind(".py"); 102 if (py_extension_pos != std::string::npos) 103 os_plugin_class_name.erase(py_extension_pos); 104 // Add ".OperatingSystemPlugIn" to the module name to get a string like 105 // "modulename.OperatingSystemPlugIn" 106 os_plugin_class_name += ".OperatingSystemPlugIn"; 107 StructuredData::ObjectSP object_sp = 108 m_interpreter->OSPlugin_CreatePluginObject( 109 os_plugin_class_name.c_str(), process->CalculateProcess()); 110 if (object_sp && object_sp->IsValid()) 111 m_python_object_sp = object_sp; 112 } 113 } 114 } 115 } 116 117 OperatingSystemPython::~OperatingSystemPython() = default; 118 119 DynamicRegisterInfo *OperatingSystemPython::GetDynamicRegisterInfo() { 120 if (m_register_info_up == nullptr) { 121 if (!m_interpreter || !m_python_object_sp) 122 return nullptr; 123 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OS)); 124 125 LLDB_LOGF(log, 126 "OperatingSystemPython::GetDynamicRegisterInfo() fetching " 127 "thread register definitions from python for pid %" PRIu64, 128 m_process->GetID()); 129 130 StructuredData::DictionarySP dictionary = 131 m_interpreter->OSPlugin_RegisterInfo(m_python_object_sp); 132 if (!dictionary) 133 return nullptr; 134 135 m_register_info_up = std::make_unique<DynamicRegisterInfo>( 136 *dictionary, m_process->GetTarget().GetArchitecture()); 137 assert(m_register_info_up->GetNumRegisters() > 0); 138 assert(m_register_info_up->GetNumRegisterSets() > 0); 139 } 140 return m_register_info_up.get(); 141 } 142 143 // PluginInterface protocol 144 ConstString OperatingSystemPython::GetPluginName() { 145 return GetPluginNameStatic(); 146 } 147 148 bool OperatingSystemPython::UpdateThreadList(ThreadList &old_thread_list, 149 ThreadList &core_thread_list, 150 ThreadList &new_thread_list) { 151 if (!m_interpreter || !m_python_object_sp) 152 return false; 153 154 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OS)); 155 156 // First thing we have to do is to try to get the API lock, and the 157 // interpreter lock. We're going to change the thread content of the process, 158 // and we're going to use python, which requires the API lock to do it. We 159 // need the interpreter lock to make sure thread_info_dict stays alive. 160 // 161 // If someone already has the API lock, that is ok, we just want to avoid 162 // external code from making new API calls while this call is happening. 163 // 164 // This is a recursive lock so we can grant it to any Python code called on 165 // the stack below us. 166 Target &target = m_process->GetTarget(); 167 std::unique_lock<std::recursive_mutex> api_lock(target.GetAPIMutex(), 168 std::defer_lock); 169 (void)api_lock.try_lock(); // See above. 170 auto interpreter_lock = m_interpreter->AcquireInterpreterLock(); 171 172 LLDB_LOGF(log, 173 "OperatingSystemPython::UpdateThreadList() fetching thread " 174 "data from python for pid %" PRIu64, 175 m_process->GetID()); 176 177 // The threads that are in "core_thread_list" upon entry are the threads from 178 // the lldb_private::Process subclass, no memory threads will be in this 179 // list. 180 StructuredData::ArraySP threads_list = 181 m_interpreter->OSPlugin_ThreadsInfo(m_python_object_sp); 182 183 const uint32_t num_cores = core_thread_list.GetSize(false); 184 185 // Make a map so we can keep track of which cores were used from the 186 // core_thread list. Any real threads/cores that weren't used should later be 187 // put back into the "new_thread_list". 188 std::vector<bool> core_used_map(num_cores, false); 189 if (threads_list) { 190 if (log) { 191 StreamString strm; 192 threads_list->Dump(strm); 193 LLDB_LOGF(log, "threads_list = %s", strm.GetData()); 194 } 195 196 const uint32_t num_threads = threads_list->GetSize(); 197 for (uint32_t i = 0; i < num_threads; ++i) { 198 StructuredData::ObjectSP thread_dict_obj = 199 threads_list->GetItemAtIndex(i); 200 if (auto thread_dict = thread_dict_obj->GetAsDictionary()) { 201 ThreadSP thread_sp(CreateThreadFromThreadInfo( 202 *thread_dict, core_thread_list, old_thread_list, core_used_map, 203 nullptr)); 204 if (thread_sp) 205 new_thread_list.AddThread(thread_sp); 206 } 207 } 208 } 209 210 // Any real core threads that didn't end up backing a memory thread should 211 // still be in the main thread list, and they should be inserted at the 212 // beginning of the list 213 uint32_t insert_idx = 0; 214 for (uint32_t core_idx = 0; core_idx < num_cores; ++core_idx) { 215 if (!core_used_map[core_idx]) { 216 new_thread_list.InsertThread( 217 core_thread_list.GetThreadAtIndex(core_idx, false), insert_idx); 218 ++insert_idx; 219 } 220 } 221 222 return new_thread_list.GetSize(false) > 0; 223 } 224 225 ThreadSP OperatingSystemPython::CreateThreadFromThreadInfo( 226 StructuredData::Dictionary &thread_dict, ThreadList &core_thread_list, 227 ThreadList &old_thread_list, std::vector<bool> &core_used_map, 228 bool *did_create_ptr) { 229 ThreadSP thread_sp; 230 tid_t tid = LLDB_INVALID_THREAD_ID; 231 if (!thread_dict.GetValueForKeyAsInteger("tid", tid)) 232 return ThreadSP(); 233 234 uint32_t core_number; 235 addr_t reg_data_addr; 236 llvm::StringRef name; 237 llvm::StringRef queue; 238 239 thread_dict.GetValueForKeyAsInteger("core", core_number, UINT32_MAX); 240 thread_dict.GetValueForKeyAsInteger("register_data_addr", reg_data_addr, 241 LLDB_INVALID_ADDRESS); 242 thread_dict.GetValueForKeyAsString("name", name); 243 thread_dict.GetValueForKeyAsString("queue", queue); 244 245 // See if a thread already exists for "tid" 246 thread_sp = old_thread_list.FindThreadByID(tid, false); 247 if (thread_sp) { 248 // A thread already does exist for "tid", make sure it was an operating 249 // system 250 // plug-in generated thread. 251 if (!IsOperatingSystemPluginThread(thread_sp)) { 252 // We have thread ID overlap between the protocol threads and the 253 // operating system threads, clear the thread so we create an operating 254 // system thread for this. 255 thread_sp.reset(); 256 } 257 } 258 259 if (!thread_sp) { 260 if (did_create_ptr) 261 *did_create_ptr = true; 262 thread_sp = std::make_shared<ThreadMemory>(*m_process, tid, name, queue, 263 reg_data_addr); 264 } 265 266 if (core_number < core_thread_list.GetSize(false)) { 267 ThreadSP core_thread_sp( 268 core_thread_list.GetThreadAtIndex(core_number, false)); 269 if (core_thread_sp) { 270 // Keep track of which cores were set as the backing thread for memory 271 // threads... 272 if (core_number < core_used_map.size()) 273 core_used_map[core_number] = true; 274 275 ThreadSP backing_core_thread_sp(core_thread_sp->GetBackingThread()); 276 if (backing_core_thread_sp) { 277 thread_sp->SetBackingThread(backing_core_thread_sp); 278 } else { 279 thread_sp->SetBackingThread(core_thread_sp); 280 } 281 } 282 } 283 return thread_sp; 284 } 285 286 void OperatingSystemPython::ThreadWasSelected(Thread *thread) {} 287 288 RegisterContextSP 289 OperatingSystemPython::CreateRegisterContextForThread(Thread *thread, 290 addr_t reg_data_addr) { 291 RegisterContextSP reg_ctx_sp; 292 if (!m_interpreter || !m_python_object_sp || !thread) 293 return reg_ctx_sp; 294 295 if (!IsOperatingSystemPluginThread(thread->shared_from_this())) 296 return reg_ctx_sp; 297 298 // First thing we have to do is to try to get the API lock, and the 299 // interpreter lock. We're going to change the thread content of the process, 300 // and we're going to use python, which requires the API lock to do it. We 301 // need the interpreter lock to make sure thread_info_dict stays alive. 302 // 303 // If someone already has the API lock, that is ok, we just want to avoid 304 // external code from making new API calls while this call is happening. 305 // 306 // This is a recursive lock so we can grant it to any Python code called on 307 // the stack below us. 308 Target &target = m_process->GetTarget(); 309 std::unique_lock<std::recursive_mutex> api_lock(target.GetAPIMutex(), 310 std::defer_lock); 311 (void)api_lock.try_lock(); // See above. 312 auto interpreter_lock = m_interpreter->AcquireInterpreterLock(); 313 314 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_THREAD)); 315 316 if (reg_data_addr != LLDB_INVALID_ADDRESS) { 317 // The registers data is in contiguous memory, just create the register 318 // context using the address provided 319 LLDB_LOGF(log, 320 "OperatingSystemPython::CreateRegisterContextForThread (tid " 321 "= 0x%" PRIx64 ", 0x%" PRIx64 ", reg_data_addr = 0x%" PRIx64 322 ") creating memory register context", 323 thread->GetID(), thread->GetProtocolID(), reg_data_addr); 324 reg_ctx_sp = std::make_shared<RegisterContextMemory>( 325 *thread, 0, *GetDynamicRegisterInfo(), reg_data_addr); 326 } else { 327 // No register data address is provided, query the python plug-in to let it 328 // make up the data as it sees fit 329 LLDB_LOGF(log, 330 "OperatingSystemPython::CreateRegisterContextForThread (tid " 331 "= 0x%" PRIx64 ", 0x%" PRIx64 332 ") fetching register data from python", 333 thread->GetID(), thread->GetProtocolID()); 334 335 StructuredData::StringSP reg_context_data = 336 m_interpreter->OSPlugin_RegisterContextData(m_python_object_sp, 337 thread->GetID()); 338 if (reg_context_data) { 339 std::string value = std::string(reg_context_data->GetValue()); 340 DataBufferSP data_sp(new DataBufferHeap(value.c_str(), value.length())); 341 if (data_sp->GetByteSize()) { 342 RegisterContextMemory *reg_ctx_memory = new RegisterContextMemory( 343 *thread, 0, *GetDynamicRegisterInfo(), LLDB_INVALID_ADDRESS); 344 if (reg_ctx_memory) { 345 reg_ctx_sp.reset(reg_ctx_memory); 346 reg_ctx_memory->SetAllRegisterData(data_sp); 347 } 348 } 349 } 350 } 351 // if we still have no register data, fallback on a dummy context to avoid 352 // crashing 353 if (!reg_ctx_sp) { 354 LLDB_LOGF(log, 355 "OperatingSystemPython::CreateRegisterContextForThread (tid " 356 "= 0x%" PRIx64 ") forcing a dummy register context", 357 thread->GetID()); 358 reg_ctx_sp = std::make_shared<RegisterContextDummy>( 359 *thread, 0, target.GetArchitecture().GetAddressByteSize()); 360 } 361 return reg_ctx_sp; 362 } 363 364 StopInfoSP 365 OperatingSystemPython::CreateThreadStopReason(lldb_private::Thread *thread) { 366 // We should have gotten the thread stop info from the dictionary of data for 367 // the thread in the initial call to get_thread_info(), this should have been 368 // cached so we can return it here 369 StopInfoSP 370 stop_info_sp; //(StopInfo::CreateStopReasonWithSignal (*thread, SIGSTOP)); 371 return stop_info_sp; 372 } 373 374 lldb::ThreadSP OperatingSystemPython::CreateThread(lldb::tid_t tid, 375 addr_t context) { 376 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_THREAD)); 377 378 LLDB_LOGF(log, 379 "OperatingSystemPython::CreateThread (tid = 0x%" PRIx64 380 ", context = 0x%" PRIx64 ") fetching register data from python", 381 tid, context); 382 383 if (m_interpreter && m_python_object_sp) { 384 // First thing we have to do is to try to get the API lock, and the 385 // interpreter lock. We're going to change the thread content of the 386 // process, and we're going to use python, which requires the API lock to 387 // do it. We need the interpreter lock to make sure thread_info_dict stays 388 // alive. 389 // 390 // If someone already has the API lock, that is ok, we just want to avoid 391 // external code from making new API calls while this call is happening. 392 // 393 // This is a recursive lock so we can grant it to any Python code called on 394 // the stack below us. 395 Target &target = m_process->GetTarget(); 396 std::unique_lock<std::recursive_mutex> api_lock(target.GetAPIMutex(), 397 std::defer_lock); 398 (void)api_lock.try_lock(); // See above. 399 auto interpreter_lock = m_interpreter->AcquireInterpreterLock(); 400 401 StructuredData::DictionarySP thread_info_dict = 402 m_interpreter->OSPlugin_CreateThread(m_python_object_sp, tid, context); 403 std::vector<bool> core_used_map; 404 if (thread_info_dict) { 405 ThreadList core_threads(m_process); 406 ThreadList &thread_list = m_process->GetThreadList(); 407 bool did_create = false; 408 ThreadSP thread_sp( 409 CreateThreadFromThreadInfo(*thread_info_dict, core_threads, 410 thread_list, core_used_map, &did_create)); 411 if (did_create) 412 thread_list.AddThread(thread_sp); 413 return thread_sp; 414 } 415 } 416 return ThreadSP(); 417 } 418 419 #endif // #if LLDB_ENABLE_PYTHON 420