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