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/Debugger.h" 21 #include "lldb/Core/Module.h" 22 #include "lldb/Core/PluginManager.h" 23 #include "lldb/Core/RegisterValue.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/Thread.h" 33 #include "lldb/Target/ThreadList.h" 34 #include "lldb/Utility/DataBufferHeap.h" 35 #include "lldb/Utility/StreamString.h" 36 #include "lldb/Utility/StructuredData.h" 37 38 using namespace lldb; 39 using namespace lldb_private; 40 41 void OperatingSystemPython::Initialize() { 42 PluginManager::RegisterPlugin(GetPluginNameStatic(), 43 GetPluginDescriptionStatic(), CreateInstance, 44 nullptr); 45 } 46 47 void OperatingSystemPython::Terminate() { 48 PluginManager::UnregisterPlugin(CreateInstance); 49 } 50 51 OperatingSystem *OperatingSystemPython::CreateInstance(Process *process, 52 bool force) { 53 // Python OperatingSystem plug-ins must be requested by name, so force must be 54 // true 55 FileSpec python_os_plugin_spec(process->GetPythonOSPluginPath()); 56 if (python_os_plugin_spec && python_os_plugin_spec.Exists()) { 57 std::unique_ptr<OperatingSystemPython> os_ap( 58 new OperatingSystemPython(process, python_os_plugin_spec)); 59 if (os_ap.get() && os_ap->IsValid()) 60 return os_ap.release(); 61 } 62 return NULL; 63 } 64 65 ConstString OperatingSystemPython::GetPluginNameStatic() { 66 static ConstString g_name("python"); 67 return g_name; 68 } 69 70 const char *OperatingSystemPython::GetPluginDescriptionStatic() { 71 return "Operating system plug-in that gathers OS information from a python " 72 "class that implements the necessary OperatingSystem functionality."; 73 } 74 75 OperatingSystemPython::OperatingSystemPython(lldb_private::Process *process, 76 const FileSpec &python_module_path) 77 : OperatingSystem(process), m_thread_list_valobj_sp(), m_register_info_ap(), 78 m_interpreter(NULL), m_python_object_sp() { 79 if (!process) 80 return; 81 TargetSP target_sp = process->CalculateTarget(); 82 if (!target_sp) 83 return; 84 m_interpreter = 85 target_sp->GetDebugger().GetCommandInterpreter().GetScriptInterpreter(); 86 if (m_interpreter) { 87 88 std::string os_plugin_class_name( 89 python_module_path.GetFilename().AsCString("")); 90 if (!os_plugin_class_name.empty()) { 91 const bool init_session = false; 92 const bool allow_reload = true; 93 char python_module_path_cstr[PATH_MAX]; 94 python_module_path.GetPath(python_module_path_cstr, 95 sizeof(python_module_path_cstr)); 96 Status error; 97 if (m_interpreter->LoadScriptingModule( 98 python_module_path_cstr, allow_reload, init_session, error)) { 99 // Strip the ".py" extension if there is one 100 size_t py_extension_pos = os_plugin_class_name.rfind(".py"); 101 if (py_extension_pos != std::string::npos) 102 os_plugin_class_name.erase(py_extension_pos); 103 // Add ".OperatingSystemPlugIn" to the module name to get a string like 104 // "modulename.OperatingSystemPlugIn" 105 os_plugin_class_name += ".OperatingSystemPlugIn"; 106 StructuredData::ObjectSP object_sp = 107 m_interpreter->OSPlugin_CreatePluginObject( 108 os_plugin_class_name.c_str(), process->CalculateProcess()); 109 if (object_sp && object_sp->IsValid()) 110 m_python_object_sp = object_sp; 111 } 112 } 113 } 114 } 115 116 OperatingSystemPython::~OperatingSystemPython() {} 117 118 DynamicRegisterInfo *OperatingSystemPython::GetDynamicRegisterInfo() { 119 if (m_register_info_ap.get() == NULL) { 120 if (!m_interpreter || !m_python_object_sp) 121 return NULL; 122 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OS)); 123 124 if (log) 125 log->Printf("OperatingSystemPython::GetDynamicRegisterInfo() fetching " 126 "thread register definitions from python for pid %" PRIu64, 127 m_process->GetID()); 128 129 StructuredData::DictionarySP dictionary = 130 m_interpreter->OSPlugin_RegisterInfo(m_python_object_sp); 131 if (!dictionary) 132 return NULL; 133 134 m_register_info_ap.reset(new DynamicRegisterInfo( 135 *dictionary, m_process->GetTarget().GetArchitecture())); 136 assert(m_register_info_ap->GetNumRegisters() > 0); 137 assert(m_register_info_ap->GetNumRegisterSets() > 0); 138 } 139 return m_register_info_ap.get(); 140 } 141 142 //------------------------------------------------------------------ 143 // PluginInterface protocol 144 //------------------------------------------------------------------ 145 ConstString OperatingSystemPython::GetPluginName() { 146 return GetPluginNameStatic(); 147 } 148 149 uint32_t OperatingSystemPython::GetPluginVersion() { return 1; } 150 151 bool OperatingSystemPython::UpdateThreadList(ThreadList &old_thread_list, 152 ThreadList &core_thread_list, 153 ThreadList &new_thread_list) { 154 if (!m_interpreter || !m_python_object_sp) 155 return false; 156 157 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OS)); 158 159 // First thing we have to do is to try to get the API lock, and the 160 // interpreter lock. We're going to change the thread content of the process, 161 // and we're going to use python, which requires the API lock to do it. We 162 // need the interpreter lock to make sure thread_info_dict stays alive. 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> api_lock(target.GetAPIMutex(), 171 std::defer_lock); 172 api_lock.try_lock(); 173 auto interpreter_lock = m_interpreter->AcquireInterpreterLock(); 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 lldb_private::Process subclass, no memory threads will be in this 182 // list. 183 StructuredData::ArraySP threads_list = 184 m_interpreter->OSPlugin_ThreadsInfo(m_python_object_sp); 185 186 const uint32_t num_cores = core_thread_list.GetSize(false); 187 188 // Make a map so we can keep track of which cores were used from the 189 // core_thread list. Any real threads/cores that weren't used should 190 // later be put back into the "new_thread_list". 191 std::vector<bool> core_used_map(num_cores, false); 192 if (threads_list) { 193 if (log) { 194 StreamString strm; 195 threads_list->Dump(strm); 196 log->Printf("threads_list = %s", strm.GetData()); 197 } 198 199 const uint32_t num_threads = threads_list->GetSize(); 200 for (uint32_t i = 0; i < num_threads; ++i) { 201 StructuredData::ObjectSP thread_dict_obj = 202 threads_list->GetItemAtIndex(i); 203 if (auto thread_dict = thread_dict_obj->GetAsDictionary()) { 204 ThreadSP thread_sp( 205 CreateThreadFromThreadInfo(*thread_dict, core_thread_list, 206 old_thread_list, core_used_map, NULL)); 207 if (thread_sp) 208 new_thread_list.AddThread(thread_sp); 209 } 210 } 211 } 212 213 // Any real core threads that didn't end up backing a memory thread should 214 // still be in the main thread list, and they should be inserted at the 215 // beginning 216 // of the list 217 uint32_t insert_idx = 0; 218 for (uint32_t core_idx = 0; core_idx < num_cores; ++core_idx) { 219 if (core_used_map[core_idx] == false) { 220 new_thread_list.InsertThread( 221 core_thread_list.GetThreadAtIndex(core_idx, false), insert_idx); 222 ++insert_idx; 223 } 224 } 225 226 return new_thread_list.GetSize(false) > 0; 227 } 228 229 ThreadSP OperatingSystemPython::CreateThreadFromThreadInfo( 230 StructuredData::Dictionary &thread_dict, ThreadList &core_thread_list, 231 ThreadList &old_thread_list, std::vector<bool> &core_used_map, 232 bool *did_create_ptr) { 233 ThreadSP thread_sp; 234 tid_t tid = LLDB_INVALID_THREAD_ID; 235 if (!thread_dict.GetValueForKeyAsInteger("tid", tid)) 236 return ThreadSP(); 237 238 uint32_t core_number; 239 addr_t reg_data_addr; 240 llvm::StringRef name; 241 llvm::StringRef queue; 242 243 thread_dict.GetValueForKeyAsInteger("core", core_number, UINT32_MAX); 244 thread_dict.GetValueForKeyAsInteger("register_data_addr", reg_data_addr, 245 LLDB_INVALID_ADDRESS); 246 thread_dict.GetValueForKeyAsString("name", name); 247 thread_dict.GetValueForKeyAsString("queue", queue); 248 249 // See if a thread already exists for "tid" 250 thread_sp = old_thread_list.FindThreadByID(tid, false); 251 if (thread_sp) { 252 // A thread already does exist for "tid", make sure it was an operating 253 // system 254 // plug-in generated thread. 255 if (!IsOperatingSystemPluginThread(thread_sp)) { 256 // We have thread ID overlap between the protocol threads and the 257 // operating system threads, clear the thread so we create an 258 // operating system thread for this. 259 thread_sp.reset(); 260 } 261 } 262 263 if (!thread_sp) { 264 if (did_create_ptr) 265 *did_create_ptr = true; 266 thread_sp.reset( 267 new ThreadMemory(*m_process, tid, name, queue, reg_data_addr)); 268 } 269 270 if (core_number < core_thread_list.GetSize(false)) { 271 ThreadSP core_thread_sp( 272 core_thread_list.GetThreadAtIndex(core_number, false)); 273 if (core_thread_sp) { 274 // Keep track of which cores were set as the backing thread for memory 275 // threads... 276 if (core_number < core_used_map.size()) 277 core_used_map[core_number] = true; 278 279 ThreadSP backing_core_thread_sp(core_thread_sp->GetBackingThread()); 280 if (backing_core_thread_sp) { 281 thread_sp->SetBackingThread(backing_core_thread_sp); 282 } else { 283 thread_sp->SetBackingThread(core_thread_sp); 284 } 285 } 286 } 287 return thread_sp; 288 } 289 290 void OperatingSystemPython::ThreadWasSelected(Thread *thread) {} 291 292 RegisterContextSP 293 OperatingSystemPython::CreateRegisterContextForThread(Thread *thread, 294 addr_t reg_data_addr) { 295 RegisterContextSP reg_ctx_sp; 296 if (!m_interpreter || !m_python_object_sp || !thread) 297 return reg_ctx_sp; 298 299 if (!IsOperatingSystemPluginThread(thread->shared_from_this())) 300 return reg_ctx_sp; 301 302 // First thing we have to do is to try to get the API lock, and the 303 // interpreter lock. We're going to change the thread content of the process, 304 // and we're going to use python, which requires the API lock to do it. We 305 // need the interpreter lock to make sure thread_info_dict stays alive. 306 // 307 // If someone already has the API lock, that is ok, we just want to avoid 308 // external code from making new API calls while this call is happening. 309 // 310 // This is a recursive lock so we can grant it to any Python code called on 311 // the stack below us. 312 Target &target = m_process->GetTarget(); 313 std::unique_lock<std::recursive_mutex> api_lock(target.GetAPIMutex(), 314 std::defer_lock); 315 api_lock.try_lock(); 316 auto interpreter_lock = m_interpreter->AcquireInterpreterLock(); 317 318 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_THREAD)); 319 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 to try to get the API lock, and the 389 // interpreter lock. We're going to change the thread content of the 390 // process, and we're going to use python, which requires the API lock to 391 // do it. We need the interpreter lock to make sure thread_info_dict stays 392 // alive. 393 // 394 // If someone already has the API lock, that is ok, we just want to avoid 395 // external code from making new API calls while this call is happening. 396 // 397 // This is a recursive lock so we can grant it to any Python code called on 398 // the stack below us. 399 Target &target = m_process->GetTarget(); 400 std::unique_lock<std::recursive_mutex> api_lock(target.GetAPIMutex(), 401 std::defer_lock); 402 api_lock.try_lock(); 403 auto interpreter_lock = m_interpreter->AcquireInterpreterLock(); 404 405 StructuredData::DictionarySP thread_info_dict = 406 m_interpreter->OSPlugin_CreateThread(m_python_object_sp, tid, context); 407 std::vector<bool> core_used_map; 408 if (thread_info_dict) { 409 ThreadList core_threads(m_process); 410 ThreadList &thread_list = m_process->GetThreadList(); 411 bool did_create = false; 412 ThreadSP thread_sp( 413 CreateThreadFromThreadInfo(*thread_info_dict, core_threads, 414 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 #endif // #ifndef LLDB_DISABLE_PYTHON 424