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