Coverage Report

Created: 2022-01-18 06:27

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