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