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