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