Coverage Report

Created: 2022-07-16 07:03

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