Coverage Report

Created: 2022-01-18 06:27

/Users/buildslave/jenkins/workspace/coverage/llvm-project/lldb/source/Plugins/ScriptInterpreter/Python/ScriptInterpreterPython.cpp
Line
Count
Source (jump to first uncovered line)
1
//===-- ScriptInterpreterPython.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
#include "lldb/lldb-enumerations.h"
11
12
#if LLDB_ENABLE_PYTHON
13
14
// LLDB Python header must be included first
15
#include "lldb-python.h"
16
17
#include "PythonDataObjects.h"
18
#include "PythonReadline.h"
19
#include "SWIGPythonBridge.h"
20
#include "ScriptInterpreterPythonImpl.h"
21
#include "ScriptedProcessPythonInterface.h"
22
23
#include "lldb/API/SBError.h"
24
#include "lldb/API/SBFrame.h"
25
#include "lldb/API/SBValue.h"
26
#include "lldb/Breakpoint/StoppointCallbackContext.h"
27
#include "lldb/Breakpoint/WatchpointOptions.h"
28
#include "lldb/Core/Communication.h"
29
#include "lldb/Core/Debugger.h"
30
#include "lldb/Core/PluginManager.h"
31
#include "lldb/Core/ValueObject.h"
32
#include "lldb/DataFormatters/TypeSummary.h"
33
#include "lldb/Host/FileSystem.h"
34
#include "lldb/Host/HostInfo.h"
35
#include "lldb/Host/Pipe.h"
36
#include "lldb/Interpreter/CommandInterpreter.h"
37
#include "lldb/Interpreter/CommandReturnObject.h"
38
#include "lldb/Target/Thread.h"
39
#include "lldb/Target/ThreadPlan.h"
40
#include "lldb/Utility/ReproducerInstrumentation.h"
41
#include "lldb/Utility/Timer.h"
42
#include "llvm/ADT/STLExtras.h"
43
#include "llvm/ADT/StringRef.h"
44
#include "llvm/Support/Error.h"
45
#include "llvm/Support/FileSystem.h"
46
#include "llvm/Support/FormatAdapters.h"
47
48
#include <cstdio>
49
#include <cstdlib>
50
#include <memory>
51
#include <mutex>
52
#include <string>
53
54
using namespace lldb;
55
using namespace lldb_private;
56
using namespace lldb_private::python;
57
using llvm::Expected;
58
59
LLDB_PLUGIN_DEFINE(ScriptInterpreterPython)
60
61
// Defined in the SWIG source file
62
#if PY_MAJOR_VERSION >= 3
63
extern "C" PyObject *PyInit__lldb(void);
64
65
1.80k
#define LLDBSwigPyInit PyInit__lldb
66
67
#else
68
extern "C" void init_lldb(void);
69
70
#define LLDBSwigPyInit init_lldb
71
#endif
72
73
#if defined(_WIN32)
74
// Don't mess with the signal handlers on Windows.
75
#define LLDB_USE_PYTHON_SET_INTERRUPT 0
76
#else
77
// PyErr_SetInterrupt was introduced in 3.2.
78
#define LLDB_USE_PYTHON_SET_INTERRUPT                                          \
79
  (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 2) || (PY_MAJOR_VERSION > 3)
80
#endif
81
82
188
static ScriptInterpreterPythonImpl *GetPythonInterpreter(Debugger &debugger) {
83
188
  ScriptInterpreter *script_interpreter =
84
188
      debugger.GetScriptInterpreter(true, lldb::eScriptLanguagePython);
85
188
  return static_cast<ScriptInterpreterPythonImpl *>(script_interpreter);
86
188
}
87
88
static bool g_initialized = false;
89
90
namespace {
91
92
// Initializing Python is not a straightforward process.  We cannot control
93
// what external code may have done before getting to this point in LLDB,
94
// including potentially having already initialized Python, so we need to do a
95
// lot of work to ensure that the existing state of the system is maintained
96
// across our initialization.  We do this by using an RAII pattern where we
97
// save off initial state at the beginning, and restore it at the end
98
struct InitializePythonRAII {
99
public:
100
903
  InitializePythonRAII() {
101
903
    InitializePythonHome();
102
103
#ifdef LLDB_USE_LIBEDIT_READLINE_COMPAT_MODULE
104
    // Python's readline is incompatible with libedit being linked into lldb.
105
    // Provide a patched version local to the embedded interpreter.
106
    bool ReadlinePatched = false;
107
    for (auto *p = PyImport_Inittab; p->name != NULL; p++) {
108
      if (strcmp(p->name, "readline") == 0) {
109
        p->initfunc = initlldb_readline;
110
        break;
111
      }
112
    }
113
    if (!ReadlinePatched) {
114
      PyImport_AppendInittab("readline", initlldb_readline);
115
      ReadlinePatched = true;
116
    }
117
#endif
118
119
    // Register _lldb as a built-in module.
120
903
    PyImport_AppendInittab("_lldb", LLDBSwigPyInit);
121
122
// Python < 3.2 and Python >= 3.2 reversed the ordering requirements for
123
// calling `Py_Initialize` and `PyEval_InitThreads`.  < 3.2 requires that you
124
// call `PyEval_InitThreads` first, and >= 3.2 requires that you call it last.
125
903
#if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 2) || (PY_MAJOR_VERSION > 3)
126
903
    Py_InitializeEx(0);
127
903
    InitializeThreadsPrivate();
128
#else
129
    InitializeThreadsPrivate();
130
    Py_InitializeEx(0);
131
#endif
132
903
  }
133
134
903
  ~InitializePythonRAII() {
135
903
    if (m_was_already_initialized) {
136
705
      Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
137
705
      LLDB_LOGV(log, "Releasing PyGILState. Returning to state = {0}locked",
138
705
                m_gil_state == PyGILState_UNLOCKED ? "un" : "");
139
705
      PyGILState_Release(m_gil_state);
140
705
    } else {
141
      // We initialized the threads in this function, just unlock the GIL.
142
198
      PyEval_SaveThread();
143
198
    }
144
903
  }
145
146
private:
147
903
  void InitializePythonHome() {
148
#if LLDB_EMBED_PYTHON_HOME
149
#if PY_MAJOR_VERSION >= 3
150
    typedef wchar_t* str_type;
151
#else
152
    typedef char* str_type;
153
#endif
154
    static str_type g_python_home = []() -> str_type {
155
      const char *lldb_python_home = LLDB_PYTHON_HOME;
156
      const char *absolute_python_home = nullptr;
157
      llvm::SmallString<64> path;
158
      if (llvm::sys::path::is_absolute(lldb_python_home)) {
159
        absolute_python_home = lldb_python_home;
160
      } else {
161
        FileSpec spec = HostInfo::GetShlibDir();
162
        if (!spec)
163
          return nullptr;
164
        spec.GetPath(path);
165
        llvm::sys::path::append(path, lldb_python_home);
166
        absolute_python_home = path.c_str();
167
      }
168
#if PY_MAJOR_VERSION >= 3
169
      size_t size = 0;
170
      return Py_DecodeLocale(absolute_python_home, &size);
171
#else
172
      return strdup(absolute_python_home);
173
#endif
174
    }();
175
    if (g_python_home != nullptr) {
176
      Py_SetPythonHome(g_python_home);
177
    }
178
#else
179
#if defined(__APPLE__) && PY_MAJOR_VERSION == 2 && PY_MINOR_VERSION == 7
180
    // For Darwin, the only Python version supported is the one shipped in the
181
    // OS OS and linked with lldb. Other installation of Python may have higher
182
    // priorities in the path, overriding PYTHONHOME and causing
183
    // problems/incompatibilities. In order to avoid confusion, always hardcode
184
    // the PythonHome to be right, as it's not going to change.
185
    static char path[] =
186
        "/System/Library/Frameworks/Python.framework/Versions/2.7";
187
    Py_SetPythonHome(path);
188
#endif
189
903
#endif
190
903
  }
191
192
903
  void InitializeThreadsPrivate() {
193
// Since Python 3.7 `Py_Initialize` calls `PyEval_InitThreads` inside itself,
194
// so there is no way to determine whether the embedded interpreter
195
// was already initialized by some external code. `PyEval_ThreadsInitialized`
196
// would always return `true` and `PyGILState_Ensure/Release` flow would be
197
// executed instead of unlocking GIL with `PyEval_SaveThread`. When
198
// an another thread calls `PyGILState_Ensure` it would get stuck in deadlock.
199
903
#if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 7) || (PY_MAJOR_VERSION > 3)
200
    // The only case we should go further and acquire the GIL: it is unlocked.
201
903
    if (PyGILState_Check())
202
198
      return;
203
705
#endif
204
205
705
    if (PyEval_ThreadsInitialized()) {
206
705
      Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
207
208
705
      m_was_already_initialized = true;
209
705
      m_gil_state = PyGILState_Ensure();
210
705
      LLDB_LOGV(log, "Ensured PyGILState. Previous state = {0}locked\n",
211
705
                m_gil_state == PyGILState_UNLOCKED ? "un" : "");
212
705
      return;
213
705
    }
214
215
    // InitThreads acquires the GIL if it hasn't been called before.
216
0
    PyEval_InitThreads();
217
0
  }
218
219
  PyGILState_STATE m_gil_state = PyGILState_UNLOCKED;
220
  bool m_was_already_initialized = false;
221
};
222
} // namespace
223
224
void ScriptInterpreterPython::ComputePythonDirForApple(
225
1.89k
    llvm::SmallVectorImpl<char> &path) {
226
1.89k
  auto style = llvm::sys::path::Style::posix;
227
228
1.89k
  llvm::StringRef path_ref(path.begin(), path.size());
229
1.89k
  auto rbegin = llvm::sys::path::rbegin(path_ref, style);
230
1.89k
  auto rend = llvm::sys::path::rend(path_ref);
231
1.89k
  auto framework = std::find(rbegin, rend, "LLDB.framework");
232
1.89k
  if (framework == rend) {
233
1.89k
    ComputePythonDir(path);
234
1.89k
    return;
235
1.89k
  }
236
0
  path.resize(framework - rend);
237
0
  llvm::sys::path::append(path, style, "LLDB.framework", "Resources", "Python");
238
0
}
239
240
void ScriptInterpreterPython::ComputePythonDir(
241
1.89k
    llvm::SmallVectorImpl<char> &path) {
242
  // Build the path by backing out of the lib dir, then building with whatever
243
  // the real python interpreter uses.  (e.g. lib for most, lib64 on RHEL
244
  // x86_64, or bin on Windows).
245
1.89k
  llvm::sys::path::remove_filename(path);
246
1.89k
  llvm::sys::path::append(path, LLDB_PYTHON_RELATIVE_LIBDIR);
247
248
#if defined(_WIN32)
249
  // This will be injected directly through FileSpec.GetDirectory().SetString(),
250
  // so we need to normalize manually.
251
  std::replace(path.begin(), path.end(), '\\', '/');
252
#endif
253
1.89k
}
254
255
1.90k
FileSpec ScriptInterpreterPython::GetPythonDir() {
256
1.90k
  static FileSpec g_spec = []() {
257
1.89k
    FileSpec spec = HostInfo::GetShlibDir();
258
1.89k
    if (!spec)
259
0
      return FileSpec();
260
1.89k
    llvm::SmallString<64> path;
261
1.89k
    spec.GetPath(path);
262
263
1.89k
#if defined(__APPLE__)
264
1.89k
    ComputePythonDirForApple(path);
265
#else
266
    ComputePythonDir(path);
267
#endif
268
1.89k
    spec.GetDirectory().SetString(path);
269
1.89k
    return spec;
270
1.89k
  }();
271
1.90k
  return g_spec;
272
1.90k
}
273
274
static const char GetInterpreterInfoScript[] = R"(
275
import os
276
import sys
277
278
def main(lldb_python_dir, python_exe_relative_path):
279
  info = {
280
    "lldb-pythonpath": lldb_python_dir,
281
    "language": "python",
282
    "prefix": sys.prefix,
283
    "executable": os.path.join(sys.prefix, python_exe_relative_path)
284
  }
285
  return info
286
)";
287
288
static const char python_exe_relative_path[] = LLDB_PYTHON_EXE_RELATIVE_PATH;
289
290
1
StructuredData::DictionarySP ScriptInterpreterPython::GetInterpreterInfo() {
291
1
  GIL gil;
292
1
  FileSpec python_dir_spec = GetPythonDir();
293
1
  if (!python_dir_spec)
294
0
    return nullptr;
295
1
  PythonScript get_info(GetInterpreterInfoScript);
296
1
  auto info_json = unwrapIgnoringErrors(
297
1
      As<PythonDictionary>(get_info(PythonString(python_dir_spec.GetPath()),
298
1
                                    PythonString(python_exe_relative_path))));
299
1
  if (!info_json)
300
0
    return nullptr;
301
1
  return info_json.CreateStructuredDictionary();
302
1
}
303
304
void ScriptInterpreterPython::SharedLibraryDirectoryHelper(
305
3.35k
    FileSpec &this_file) {
306
  // When we're loaded from python, this_file will point to the file inside the
307
  // python package directory. Replace it with the one in the lib directory.
308
#ifdef _WIN32
309
  // On windows, we need to manually back out of the python tree, and go into
310
  // the bin directory. This is pretty much the inverse of what ComputePythonDir
311
  // does.
312
  if (this_file.GetFileNameExtension() == ConstString(".pyd")) {
313
    this_file.RemoveLastPathComponent(); // _lldb.pyd or _lldb_d.pyd
314
    this_file.RemoveLastPathComponent(); // lldb
315
    llvm::StringRef libdir = LLDB_PYTHON_RELATIVE_LIBDIR;
316
    for (auto it = llvm::sys::path::begin(libdir),
317
              end = llvm::sys::path::end(libdir);
318
         it != end; ++it)
319
      this_file.RemoveLastPathComponent();
320
    this_file.AppendPathComponent("bin");
321
    this_file.AppendPathComponent("liblldb.dll");
322
  }
323
#else
324
  // The python file is a symlink, so we can find the real library by resolving
325
  // it. We can do this unconditionally.
326
3.35k
  FileSystem::Instance().ResolveSymbolicLink(this_file, this_file);
327
3.35k
#endif
328
3.35k
}
329
330
3.38k
llvm::StringRef ScriptInterpreterPython::GetPluginDescriptionStatic() {
331
3.38k
  return "Embedded Python interpreter";
332
3.38k
}
333
334
3.38k
void ScriptInterpreterPython::Initialize() {
335
3.38k
  static llvm::once_flag g_once_flag;
336
337
3.38k
  llvm::call_once(g_once_flag, []() {
338
3.38k
    PluginManager::RegisterPlugin(GetPluginNameStatic(),
339
3.38k
                                  GetPluginDescriptionStatic(),
340
3.38k
                                  lldb::eScriptLanguagePython,
341
3.38k
                                  ScriptInterpreterPythonImpl::CreateInstance);
342
3.38k
  });
343
3.38k
}
344
345
3.38k
void ScriptInterpreterPython::Terminate() {}
346
347
ScriptInterpreterPythonImpl::Locker::Locker(
348
    ScriptInterpreterPythonImpl *py_interpreter, uint16_t on_entry,
349
    uint16_t on_leave, FileSP in, FileSP out, FileSP err)
350
    : ScriptInterpreterLocker(),
351
      m_teardown_session((on_leave & TearDownSession) == TearDownSession),
352
11.3k
      m_python_interpreter(py_interpreter) {
353
11.3k
  DoAcquireLock();
354
11.3k
  if ((on_entry & InitSession) == InitSession) {
355
9.64k
    if (!DoInitSession(on_entry, in, out, err)) {
356
      // Don't teardown the session if we didn't init it.
357
343
      m_teardown_session = false;
358
343
    }
359
9.64k
  }
360
11.3k
}
361
362
11.3k
bool ScriptInterpreterPythonImpl::Locker::DoAcquireLock() {
363
11.3k
  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
364
11.3k
  m_GILState = PyGILState_Ensure();
365
11.3k
  LLDB_LOGV(log, "Ensured PyGILState. Previous state = {0}locked",
366
11.3k
            m_GILState == PyGILState_UNLOCKED ? "un" : "");
367
368
  // we need to save the thread state when we first start the command because
369
  // we might decide to interrupt it while some action is taking place outside
370
  // of Python (e.g. printing to screen, waiting for the network, ...) in that
371
  // case, _PyThreadState_Current will be NULL - and we would be unable to set
372
  // the asynchronous exception - not a desirable situation
373
11.3k
  m_python_interpreter->SetThreadState(PyThreadState_Get());
374
11.3k
  m_python_interpreter->IncrementLockCount();
375
11.3k
  return true;
376
11.3k
}
377
378
bool ScriptInterpreterPythonImpl::Locker::DoInitSession(uint16_t on_entry_flags,
379
                                                        FileSP in, FileSP out,
380
9.64k
                                                        FileSP err) {
381
9.64k
  if (!m_python_interpreter)
382
0
    return false;
383
9.64k
  return m_python_interpreter->EnterSession(on_entry_flags, in, out, err);
384
9.64k
}
385
386
11.3k
bool ScriptInterpreterPythonImpl::Locker::DoFreeLock() {
387
11.3k
  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
388
11.3k
  LLDB_LOGV(log, "Releasing PyGILState. Returning to state = {0}locked",
389
11.3k
            m_GILState == PyGILState_UNLOCKED ? "un" : "");
390
11.3k
  PyGILState_Release(m_GILState);
391
11.3k
  m_python_interpreter->DecrementLockCount();
392
11.3k
  return true;
393
11.3k
}
394
395
9.29k
bool ScriptInterpreterPythonImpl::Locker::DoTearDownSession() {
396
9.29k
  if (!m_python_interpreter)
397
0
    return false;
398
9.29k
  m_python_interpreter->LeaveSession();
399
9.29k
  return true;
400
9.29k
}
401
402
11.3k
ScriptInterpreterPythonImpl::Locker::~Locker() {
403
11.3k
  if (m_teardown_session)
404
9.29k
    DoTearDownSession();
405
11.3k
  DoFreeLock();
406
11.3k
}
407
408
ScriptInterpreterPythonImpl::ScriptInterpreterPythonImpl(Debugger &debugger)
409
    : ScriptInterpreterPython(debugger), m_saved_stdin(), m_saved_stdout(),
410
      m_saved_stderr(), m_main_module(),
411
      m_session_dict(PyInitialValue::Invalid),
412
      m_sys_module_dict(PyInitialValue::Invalid), m_run_one_line_function(),
413
      m_run_one_line_str_global(),
414
      m_dictionary_name(m_debugger.GetInstanceName().AsCString()),
415
      m_active_io_handler(eIOHandlerNone), m_session_is_active(false),
416
      m_pty_secondary_is_open(false), m_valid_session(true), m_lock_count(0),
417
1.43k
      m_command_thread_state(nullptr) {
418
1.43k
  InitializePrivate();
419
420
1.43k
  m_scripted_process_interface_up =
421
1.43k
      std::make_unique<ScriptedProcessPythonInterface>(*this);
422
423
1.43k
  m_dictionary_name.append("_dict");
424
1.43k
  StreamString run_string;
425
1.43k
  run_string.Printf("%s = dict()", m_dictionary_name.c_str());
426
427
1.43k
  Locker locker(this, Locker::AcquireLock, Locker::FreeAcquiredLock);
428
1.43k
  PyRun_SimpleString(run_string.GetData());
429
430
1.43k
  run_string.Clear();
431
1.43k
  run_string.Printf(
432
1.43k
      "run_one_line (%s, 'import copy, keyword, os, re, sys, uuid, lldb')",
433
1.43k
      m_dictionary_name.c_str());
434
1.43k
  PyRun_SimpleString(run_string.GetData());
435
436
  // Reloading modules requires a different syntax in Python 2 and Python 3.
437
  // This provides a consistent syntax no matter what version of Python.
438
1.43k
  run_string.Clear();
439
1.43k
  run_string.Printf("run_one_line (%s, 'from six.moves import reload_module')",
440
1.43k
                    m_dictionary_name.c_str());
441
1.43k
  PyRun_SimpleString(run_string.GetData());
442
443
  // WARNING: temporary code that loads Cocoa formatters - this should be done
444
  // on a per-platform basis rather than loading the whole set and letting the
445
  // individual formatter classes exploit APIs to check whether they can/cannot
446
  // do their task
447
1.43k
  run_string.Clear();
448
1.43k
  run_string.Printf(
449
1.43k
      "run_one_line (%s, 'import lldb.formatters, lldb.formatters.cpp, pydoc')",
450
1.43k
      m_dictionary_name.c_str());
451
1.43k
  PyRun_SimpleString(run_string.GetData());
452
1.43k
  run_string.Clear();
453
454
1.43k
  run_string.Printf("run_one_line (%s, 'import lldb.embedded_interpreter; from "
455
1.43k
                    "lldb.embedded_interpreter import run_python_interpreter; "
456
1.43k
                    "from lldb.embedded_interpreter import run_one_line')",
457
1.43k
                    m_dictionary_name.c_str());
458
1.43k
  PyRun_SimpleString(run_string.GetData());
459
1.43k
  run_string.Clear();
460
461
1.43k
  run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64
462
1.43k
                    "; pydoc.pager = pydoc.plainpager')",
463
1.43k
                    m_dictionary_name.c_str(), m_debugger.GetID());
464
1.43k
  PyRun_SimpleString(run_string.GetData());
465
1.43k
}
466
467
1.43k
ScriptInterpreterPythonImpl::~ScriptInterpreterPythonImpl() {
468
  // the session dictionary may hold objects with complex state which means
469
  // that they may need to be torn down with some level of smarts and that, in
470
  // turn, requires a valid thread state force Python to procure itself such a
471
  // thread state, nuke the session dictionary and then release it for others
472
  // to use and proceed with the rest of the shutdown
473
1.43k
  auto gil_state = PyGILState_Ensure();
474
1.43k
  m_session_dict.Reset();
475
1.43k
  PyGILState_Release(gil_state);
476
1.43k
}
477
478
void ScriptInterpreterPythonImpl::IOHandlerActivated(IOHandler &io_handler,
479
2
                                                     bool interactive) {
480
2
  const char *instructions = nullptr;
481
482
2
  switch (m_active_io_handler) {
483
0
  case eIOHandlerNone:
484
0
    break;
485
2
  case eIOHandlerBreakpoint:
486
2
    instructions = R"(Enter your Python command(s). Type 'DONE' to end.
487
2
def function (frame, bp_loc, internal_dict):
488
2
    """frame: the lldb.SBFrame for the location at which you stopped
489
2
       bp_loc: an lldb.SBBreakpointLocation for the breakpoint location information
490
2
       internal_dict: an LLDB support object not to be used"""
491
2
)";
492
2
    break;
493
0
  case eIOHandlerWatchpoint:
494
0
    instructions = "Enter your Python command(s). Type 'DONE' to end.\n";
495
0
    break;
496
2
  }
497
498
2
  if (instructions) {
499
2
    StreamFileSP output_sp(io_handler.GetOutputStreamFileSP());
500
2
    if (output_sp && interactive) {
501
1
      output_sp->PutCString(instructions);
502
1
      output_sp->Flush();
503
1
    }
504
2
  }
505
2
}
506
507
void ScriptInterpreterPythonImpl::IOHandlerInputComplete(IOHandler &io_handler,
508
2
                                                         std::string &data) {
509
2
  io_handler.SetIsDone(true);
510
2
  bool batch_mode = m_debugger.GetCommandInterpreter().GetBatchCommandMode();
511
512
2
  switch (m_active_io_handler) {
513
0
  case eIOHandlerNone:
514
0
    break;
515
2
  case eIOHandlerBreakpoint: {
516
2
    std::vector<std::reference_wrapper<BreakpointOptions>> *bp_options_vec =
517
2
        (std::vector<std::reference_wrapper<BreakpointOptions>> *)
518
2
            io_handler.GetUserData();
519
2
    for (BreakpointOptions &bp_options : *bp_options_vec) {
520
521
2
      auto data_up = std::make_unique<CommandDataPython>();
522
2
      if (!data_up)
523
0
        break;
524
2
      data_up->user_source.SplitIntoLines(data);
525
526
2
      StructuredData::ObjectSP empty_args_sp;
527
2
      if (GenerateBreakpointCommandCallbackData(data_up->user_source,
528
2
                                                data_up->script_source,
529
2
                                                false)
530
2
              .Success()) {
531
2
        auto baton_sp = std::make_shared<BreakpointOptions::CommandBaton>(
532
2
            std::move(data_up));
533
2
        bp_options.SetCallback(
534
2
            ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp);
535
2
      } else 
if (0
!batch_mode0
) {
536
0
        StreamFileSP error_sp = io_handler.GetErrorStreamFileSP();
537
0
        if (error_sp) {
538
0
          error_sp->Printf("Warning: No command attached to breakpoint.\n");
539
0
          error_sp->Flush();
540
0
        }
541
0
      }
542
2
    }
543
2
    m_active_io_handler = eIOHandlerNone;
544
2
  } break;
545
0
  case eIOHandlerWatchpoint: {
546
0
    WatchpointOptions *wp_options =
547
0
        (WatchpointOptions *)io_handler.GetUserData();
548
0
    auto data_up = std::make_unique<WatchpointOptions::CommandData>();
549
0
    data_up->user_source.SplitIntoLines(data);
550
551
0
    if (GenerateWatchpointCommandCallbackData(data_up->user_source,
552
0
                                              data_up->script_source)) {
553
0
      auto baton_sp =
554
0
          std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up));
555
0
      wp_options->SetCallback(
556
0
          ScriptInterpreterPythonImpl::WatchpointCallbackFunction, baton_sp);
557
0
    } else if (!batch_mode) {
558
0
      StreamFileSP error_sp = io_handler.GetErrorStreamFileSP();
559
0
      if (error_sp) {
560
0
        error_sp->Printf("Warning: No command attached to breakpoint.\n");
561
0
        error_sp->Flush();
562
0
      }
563
0
    }
564
0
    m_active_io_handler = eIOHandlerNone;
565
0
  } break;
566
2
  }
567
2
}
568
569
lldb::ScriptInterpreterSP
570
1.43k
ScriptInterpreterPythonImpl::CreateInstance(Debugger &debugger) {
571
1.43k
  return std::make_shared<ScriptInterpreterPythonImpl>(debugger);
572
1.43k
}
573
574
9.29k
void ScriptInterpreterPythonImpl::LeaveSession() {
575
9.29k
  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
576
9.29k
  if (log)
577
10
    log->PutCString("ScriptInterpreterPythonImpl::LeaveSession()");
578
579
  // Unset the LLDB global variables.
580
9.29k
  PyRun_SimpleString("lldb.debugger = None; lldb.target = None; lldb.process "
581
9.29k
                     "= None; lldb.thread = None; lldb.frame = None");
582
583
  // checking that we have a valid thread state - since we use our own
584
  // threading and locking in some (rare) cases during cleanup Python may end
585
  // up believing we have no thread state and PyImport_AddModule will crash if
586
  // that is the case - since that seems to only happen when destroying the
587
  // SBDebugger, we can make do without clearing up stdout and stderr
588
589
  // rdar://problem/11292882
590
  // When the current thread state is NULL, PyThreadState_Get() issues a fatal
591
  // error.
592
9.29k
  if (PyThreadState_GetDict()) {
593
9.29k
    PythonDictionary &sys_module_dict = GetSysModuleDictionary();
594
9.29k
    if (sys_module_dict.IsValid()) {
595
9.29k
      if (m_saved_stdin.IsValid()) {
596
39
        sys_module_dict.SetItemForKey(PythonString("stdin"), m_saved_stdin);
597
39
        m_saved_stdin.Reset();
598
39
      }
599
9.29k
      if (m_saved_stdout.IsValid()) {
600
9.29k
        sys_module_dict.SetItemForKey(PythonString("stdout"), m_saved_stdout);
601
9.29k
        m_saved_stdout.Reset();
602
9.29k
      }
603
9.29k
      if (m_saved_stderr.IsValid()) {
604
9.29k
        sys_module_dict.SetItemForKey(PythonString("stderr"), m_saved_stderr);
605
9.29k
        m_saved_stderr.Reset();
606
9.29k
      }
607
9.29k
    }
608
9.29k
  }
609
610
9.29k
  m_session_is_active = false;
611
9.29k
}
612
613
bool ScriptInterpreterPythonImpl::SetStdHandle(FileSP file_sp,
614
                                               const char *py_name,
615
                                               PythonObject &save_file,
616
26.6k
                                               const char *mode) {
617
26.6k
  if (!file_sp || 
!*file_sp18.6k
) {
618
8.03k
    save_file.Reset();
619
8.03k
    return false;
620
8.03k
  }
621
18.6k
  File &file = *file_sp;
622
623
  // Flush the file before giving it to python to avoid interleaved output.
624
18.6k
  file.Flush();
625
626
18.6k
  PythonDictionary &sys_module_dict = GetSysModuleDictionary();
627
628
18.6k
  auto new_file = PythonFile::FromFile(file, mode);
629
18.6k
  if (!new_file) {
630
0
    llvm::consumeError(new_file.takeError());
631
0
    return false;
632
0
  }
633
634
18.6k
  save_file = sys_module_dict.GetItemForKey(PythonString(py_name));
635
636
18.6k
  sys_module_dict.SetItemForKey(PythonString(py_name), new_file.get());
637
18.6k
  return true;
638
18.6k
}
639
640
bool ScriptInterpreterPythonImpl::EnterSession(uint16_t on_entry_flags,
641
                                               FileSP in_sp, FileSP out_sp,
642
9.64k
                                               FileSP err_sp) {
643
  // If we have already entered the session, without having officially 'left'
644
  // it, then there is no need to 'enter' it again.
645
9.64k
  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
646
9.64k
  if (m_session_is_active) {
647
343
    LLDB_LOGF(
648
343
        log,
649
343
        "ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%" PRIx16
650
343
        ") session is already active, returning without doing anything",
651
343
        on_entry_flags);
652
343
    return false;
653
343
  }
654
655
9.29k
  LLDB_LOGF(
656
9.29k
      log,
657
9.29k
      "ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%" PRIx16 ")",
658
9.29k
      on_entry_flags);
659
660
9.29k
  m_session_is_active = true;
661
662
9.29k
  StreamString run_string;
663
664
9.29k
  if (on_entry_flags & Locker::InitGlobals) {
665
205
    run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64,
666
205
                      m_dictionary_name.c_str(), m_debugger.GetID());
667
205
    run_string.Printf(
668
205
        "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64 ")",
669
205
        m_debugger.GetID());
670
205
    run_string.PutCString("; lldb.target = lldb.debugger.GetSelectedTarget()");
671
205
    run_string.PutCString("; lldb.process = lldb.target.GetProcess()");
672
205
    run_string.PutCString("; lldb.thread = lldb.process.GetSelectedThread ()");
673
205
    run_string.PutCString("; lldb.frame = lldb.thread.GetSelectedFrame ()");
674
205
    run_string.PutCString("')");
675
9.09k
  } else {
676
    // If we aren't initing the globals, we should still always set the
677
    // debugger (since that is always unique.)
678
9.09k
    run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64,
679
9.09k
                      m_dictionary_name.c_str(), m_debugger.GetID());
680
9.09k
    run_string.Printf(
681
9.09k
        "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64 ")",
682
9.09k
        m_debugger.GetID());
683
9.09k
    run_string.PutCString("')");
684
9.09k
  }
685
686
9.29k
  PyRun_SimpleString(run_string.GetData());
687
9.29k
  run_string.Clear();
688
689
9.29k
  PythonDictionary &sys_module_dict = GetSysModuleDictionary();
690
9.29k
  if (sys_module_dict.IsValid()) {
691
9.29k
    lldb::FileSP top_in_sp;
692
9.29k
    lldb::StreamFileSP top_out_sp, top_err_sp;
693
9.29k
    if (!in_sp || 
!out_sp5.29k
||
!err_sp5.29k
||
!*in_sp5.29k
||
!*out_sp5.29k
||
!*err_sp5.29k
)
694
4.00k
      m_debugger.AdoptTopIOHandlerFilesIfInvalid(top_in_sp, top_out_sp,
695
4.00k
                                                 top_err_sp);
696
697
9.29k
    if (on_entry_flags & Locker::NoSTDIN) {
698
9.25k
      m_saved_stdin.Reset();
699
9.25k
    } else {
700
39
      if (!SetStdHandle(in_sp, "stdin", m_saved_stdin, "r")) {
701
16
        if (top_in_sp)
702
16
          SetStdHandle(top_in_sp, "stdin", m_saved_stdin, "r");
703
16
      }
704
39
    }
705
706
9.29k
    if (!SetStdHandle(out_sp, "stdout", m_saved_stdout, "w")) {
707
4.00k
      if (top_out_sp)
708
4.00k
        SetStdHandle(top_out_sp->GetFileSP(), "stdout", m_saved_stdout, "w");
709
4.00k
    }
710
711
9.29k
    if (!SetStdHandle(err_sp, "stderr", m_saved_stderr, "w")) {
712
4.00k
      if (top_err_sp)
713
4.00k
        SetStdHandle(top_err_sp->GetFileSP(), "stderr", m_saved_stderr, "w");
714
4.00k
    }
715
9.29k
  }
716
717
9.29k
  if (PyErr_Occurred())
718
0
    PyErr_Clear();
719
720
9.29k
  return true;
721
9.64k
}
722
723
6.68k
PythonModule &ScriptInterpreterPythonImpl::GetMainModule() {
724
6.68k
  if (!m_main_module.IsValid())
725
1.25k
    m_main_module = unwrapIgnoringErrors(PythonModule::Import("__main__"));
726
6.68k
  return m_main_module;
727
6.68k
}
728
729
5.75k
PythonDictionary &ScriptInterpreterPythonImpl::GetSessionDictionary() {
730
5.75k
  if (m_session_dict.IsValid())
731
4.49k
    return m_session_dict;
732
733
1.25k
  PythonObject &main_module = GetMainModule();
734
1.25k
  if (!main_module.IsValid())
735
0
    return m_session_dict;
736
737
1.25k
  PythonDictionary main_dict(PyRefType::Borrowed,
738
1.25k
                             PyModule_GetDict(main_module.get()));
739
1.25k
  if (!main_dict.IsValid())
740
0
    return m_session_dict;
741
742
1.25k
  m_session_dict = unwrapIgnoringErrors(
743
1.25k
      As<PythonDictionary>(main_dict.GetItem(m_dictionary_name)));
744
1.25k
  return m_session_dict;
745
1.25k
}
746
747
37.2k
PythonDictionary &ScriptInterpreterPythonImpl::GetSysModuleDictionary() {
748
37.2k
  if (m_sys_module_dict.IsValid())
749
35.9k
    return m_sys_module_dict;
750
1.27k
  PythonModule sys_module = unwrapIgnoringErrors(PythonModule::Import("sys"));
751
1.27k
  m_sys_module_dict = sys_module.GetDictionary();
752
1.27k
  return m_sys_module_dict;
753
37.2k
}
754
755
llvm::Expected<unsigned>
756
ScriptInterpreterPythonImpl::GetMaxPositionalArgumentsForCallable(
757
12
    const llvm::StringRef &callable_name) {
758
12
  if (callable_name.empty()) {
759
0
    return llvm::createStringError(
760
0
        llvm::inconvertibleErrorCode(),
761
0
        "called with empty callable name.");
762
0
  }
763
12
  Locker py_lock(this, Locker::AcquireLock |
764
12
                 Locker::InitSession |
765
12
                 Locker::NoSTDIN);
766
12
  auto dict = PythonModule::MainModule()
767
12
      .ResolveName<PythonDictionary>(m_dictionary_name);
768
12
  auto pfunc = PythonObject::ResolveNameWithDictionary<PythonCallable>(
769
12
      callable_name, dict);
770
12
  if (!pfunc.IsAllocated()) {
771
1
    return llvm::createStringError(
772
1
        llvm::inconvertibleErrorCode(),
773
1
        "can't find callable: %s", callable_name.str().c_str());
774
1
  }
775
11
  llvm::Expected<PythonCallable::ArgInfo> arg_info = pfunc.GetArgInfo();
776
11
  if (!arg_info)
777
0
    return arg_info.takeError();
778
11
  return arg_info.get().max_positional_args;
779
11
}
780
781
static std::string GenerateUniqueName(const char *base_name_wanted,
782
                                      uint32_t &functions_counter,
783
47
                                      const void *name_token = nullptr) {
784
47
  StreamString sstr;
785
786
47
  if (!base_name_wanted)
787
0
    return std::string();
788
789
47
  if (!name_token)
790
45
    sstr.Printf("%s_%d", base_name_wanted, functions_counter++);
791
2
  else
792
2
    sstr.Printf("%s_%p", base_name_wanted, name_token);
793
794
47
  return std::string(sstr.GetString());
795
47
}
796
797
82
bool ScriptInterpreterPythonImpl::GetEmbeddedInterpreterModuleObjects() {
798
82
  if (m_run_one_line_function.IsValid())
799
36
    return true;
800
801
46
  PythonObject module(PyRefType::Borrowed,
802
46
                      PyImport_AddModule("lldb.embedded_interpreter"));
803
46
  if (!module.IsValid())
804
0
    return false;
805
806
46
  PythonDictionary module_dict(PyRefType::Borrowed,
807
46
                               PyModule_GetDict(module.get()));
808
46
  if (!module_dict.IsValid())
809
0
    return false;
810
811
46
  m_run_one_line_function =
812
46
      module_dict.GetItemForKey(PythonString("run_one_line"));
813
46
  m_run_one_line_str_global =
814
46
      module_dict.GetItemForKey(PythonString("g_run_one_line_str"));
815
46
  return m_run_one_line_function.IsValid();
816
46
}
817
818
bool ScriptInterpreterPythonImpl::ExecuteOneLine(
819
    llvm::StringRef command, CommandReturnObject *result,
820
82
    const ExecuteScriptOptions &options) {
821
82
  std::string command_str = command.str();
822
823
82
  if (!m_valid_session)
824
0
    return false;
825
826
82
  if (!command.empty()) {
827
    // We want to call run_one_line, passing in the dictionary and the command
828
    // string.  We cannot do this through PyRun_SimpleString here because the
829
    // command string may contain escaped characters, and putting it inside
830
    // another string to pass to PyRun_SimpleString messes up the escaping.  So
831
    // we use the following more complicated method to pass the command string
832
    // directly down to Python.
833
82
    llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
834
82
        io_redirect_or_error = ScriptInterpreterIORedirect::Create(
835
82
            options.GetEnableIO(), m_debugger, result);
836
82
    if (!io_redirect_or_error) {
837
0
      if (result)
838
0
        result->AppendErrorWithFormatv(
839
0
            "failed to redirect I/O: {0}\n",
840
0
            llvm::fmt_consume(io_redirect_or_error.takeError()));
841
0
      else
842
0
        llvm::consumeError(io_redirect_or_error.takeError());
843
0
      return false;
844
0
    }
845
846
82
    ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
847
848
82
    bool success = false;
849
82
    {
850
      // WARNING!  It's imperative that this RAII scope be as tight as
851
      // possible. In particular, the scope must end *before* we try to join
852
      // the read thread.  The reason for this is that a pre-requisite for
853
      // joining the read thread is that we close the write handle (to break
854
      // the pipe and cause it to wake up and exit).  But acquiring the GIL as
855
      // below will redirect Python's stdio to use this same handle.  If we
856
      // close the handle while Python is still using it, bad things will
857
      // happen.
858
82
      Locker locker(
859
82
          this,
860
82
          Locker::AcquireLock | Locker::InitSession |
861
82
              (options.GetSetLLDBGlobals() ? Locker::InitGlobals : 
00
) |
862
82
              ((result && result->GetInteractive()) ? 
024
:
Locker::NoSTDIN58
),
863
82
          Locker::FreeAcquiredLock | Locker::TearDownSession,
864
82
          io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
865
82
          io_redirect.GetErrorFile());
866
867
      // Find the correct script interpreter dictionary in the main module.
868
82
      PythonDictionary &session_dict = GetSessionDictionary();
869
82
      if (session_dict.IsValid()) {
870
82
        if (GetEmbeddedInterpreterModuleObjects()) {
871
82
          if (PyCallable_Check(m_run_one_line_function.get())) {
872
82
            PythonObject pargs(
873
82
                PyRefType::Owned,
874
82
                Py_BuildValue("(Os)", session_dict.get(), command_str.c_str()));
875
82
            if (pargs.IsValid()) {
876
82
              PythonObject return_value(
877
82
                  PyRefType::Owned,
878
82
                  PyObject_CallObject(m_run_one_line_function.get(),
879
82
                                      pargs.get()));
880
82
              if (return_value.IsValid())
881
82
                success = true;
882
0
              else if (options.GetMaskoutErrors() && PyErr_Occurred()) {
883
0
                PyErr_Print();
884
0
                PyErr_Clear();
885
0
              }
886
82
            }
887
82
          }
888
82
        }
889
82
      }
890
891
82
      io_redirect.Flush();
892
82
    }
893
894
82
    if (success)
895
82
      return true;
896
897
    // The one-liner failed.  Append the error message.
898
0
    if (result) {
899
0
      result->AppendErrorWithFormat(
900
0
          "python failed attempting to evaluate '%s'\n", command_str.c_str());
901
0
    }
902
0
    return false;
903
82
  }
904
905
0
  if (result)
906
0
    result->AppendError("empty command passed to python\n");
907
0
  return false;
908
82
}
909
910
3
void ScriptInterpreterPythonImpl::ExecuteInterpreterLoop() {
911
3
  LLDB_SCOPED_TIMER();
912
913
3
  Debugger &debugger = m_debugger;
914
915
  // At the moment, the only time the debugger does not have an input file
916
  // handle is when this is called directly from Python, in which case it is
917
  // both dangerous and unnecessary (not to mention confusing) to try to embed
918
  // a running interpreter loop inside the already running Python interpreter
919
  // loop, so we won't do it.
920
921
3
  if (!debugger.GetInputFile().IsValid())
922
0
    return;
923
924
3
  IOHandlerSP io_handler_sp(new IOHandlerPythonInterpreter(debugger, this));
925
3
  if (io_handler_sp) {
926
3
    debugger.RunIOHandlerAsync(io_handler_sp);
927
3
  }
928
3
}
929
930
0
bool ScriptInterpreterPythonImpl::Interrupt() {
931
0
#if LLDB_USE_PYTHON_SET_INTERRUPT
932
  // If the interpreter isn't evaluating any Python at the moment then return
933
  // false to signal that this function didn't handle the interrupt and the
934
  // next component should try handling it.
935
0
  if (!IsExecutingPython())
936
0
    return false;
937
938
  // Tell Python that it should pretend to have received a SIGINT.
939
0
  PyErr_SetInterrupt();
940
  // PyErr_SetInterrupt has no way to return an error so we can only pretend the
941
  // signal got successfully handled and return true.
942
  // Python 3.10 introduces PyErr_SetInterruptEx that could return an error, but
943
  // the error handling is limited to checking the arguments which would be
944
  // just our (hardcoded) input signal code SIGINT, so that's not useful at all.
945
0
  return true;
946
#else
947
  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SCRIPT));
948
949
  if (IsExecutingPython()) {
950
    PyThreadState *state = PyThreadState_GET();
951
    if (!state)
952
      state = GetThreadState();
953
    if (state) {
954
      long tid = state->thread_id;
955
      PyThreadState_Swap(state);
956
      int num_threads = PyThreadState_SetAsyncExc(tid, PyExc_KeyboardInterrupt);
957
      LLDB_LOGF(log,
958
                "ScriptInterpreterPythonImpl::Interrupt() sending "
959
                "PyExc_KeyboardInterrupt (tid = %li, num_threads = %i)...",
960
                tid, num_threads);
961
      return true;
962
    }
963
  }
964
  LLDB_LOGF(log,
965
            "ScriptInterpreterPythonImpl::Interrupt() python code not running, "
966
            "can't interrupt");
967
  return false;
968
#endif
969
0
}
970
971
bool ScriptInterpreterPythonImpl::ExecuteOneLineWithReturn(
972
    llvm::StringRef in_string, ScriptInterpreter::ScriptReturnType return_type,
973
5.16k
    void *ret_value, const ExecuteScriptOptions &options) {
974
975
5.16k
  llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
976
5.16k
      io_redirect_or_error = ScriptInterpreterIORedirect::Create(
977
5.16k
          options.GetEnableIO(), m_debugger, /*result=*/nullptr);
978
979
5.16k
  if (!io_redirect_or_error) {
980
0
    llvm::consumeError(io_redirect_or_error.takeError());
981
0
    return false;
982
0
  }
983
984
5.16k
  ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
985
986
5.16k
  Locker locker(this,
987
5.16k
                Locker::AcquireLock | Locker::InitSession |
988
5.16k
                    (options.GetSetLLDBGlobals() ? 
Locker::InitGlobals74
:
05.09k
) |
989
5.16k
                    Locker::NoSTDIN,
990
5.16k
                Locker::FreeAcquiredLock | Locker::TearDownSession,
991
5.16k
                io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
992
5.16k
                io_redirect.GetErrorFile());
993
994
5.16k
  PythonModule &main_module = GetMainModule();
995
5.16k
  PythonDictionary globals = main_module.GetDictionary();
996
997
5.16k
  PythonDictionary locals = GetSessionDictionary();
998
5.16k
  if (!locals.IsValid())
999
0
    locals = unwrapIgnoringErrors(
1000
0
        As<PythonDictionary>(globals.GetAttribute(m_dictionary_name)));
1001
5.16k
  if (!locals.IsValid())
1002
0
    locals = globals;
1003
1004
5.16k
  Expected<PythonObject> maybe_py_return =
1005
5.16k
      runStringOneLine(in_string, globals, locals);
1006
1007
5.16k
  if (!maybe_py_return) {
1008
3
    llvm::handleAllErrors(
1009
3
        maybe_py_return.takeError(),
1010
3
        [&](PythonException &E) {
1011
3
          E.Restore();
1012
3
          if (options.GetMaskoutErrors()) {
1013
3
            if (E.Matches(PyExc_SyntaxError)) {
1014
0
              PyErr_Print();
1015
0
            }
1016
3
            PyErr_Clear();
1017
3
          }
1018
3
        },
1019
3
        [](const llvm::ErrorInfoBase &E) 
{}0
);
1020
3
    return false;
1021
3
  }
1022
1023
5.16k
  PythonObject py_return = std::move(maybe_py_return.get());
1024
5.16k
  assert(py_return.IsValid());
1025
1026
0
  switch (return_type) {
1027
0
  case eScriptReturnTypeCharPtr: // "char *"
1028
0
  {
1029
0
    const char format[3] = "s#";
1030
0
    return PyArg_Parse(py_return.get(), format, (char **)ret_value);
1031
0
  }
1032
71
  case eScriptReturnTypeCharStrOrNone: // char* or NULL if py_return ==
1033
                                       // Py_None
1034
71
  {
1035
71
    const char format[3] = "z";
1036
71
    return PyArg_Parse(py_return.get(), format, (char **)ret_value);
1037
0
  }
1038
5.09k
  case eScriptReturnTypeBool: {
1039
5.09k
    const char format[2] = "b";
1040
5.09k
    return PyArg_Parse(py_return.get(), format, (bool *)ret_value);
1041
0
  }
1042
0
  case eScriptReturnTypeShortInt: {
1043
0
    const char format[2] = "h";
1044
0
    return PyArg_Parse(py_return.get(), format, (short *)ret_value);
1045
0
  }
1046
0
  case eScriptReturnTypeShortIntUnsigned: {
1047
0
    const char format[2] = "H";
1048
0
    return PyArg_Parse(py_return.get(), format, (unsigned short *)ret_value);
1049
0
  }
1050
0
  case eScriptReturnTypeInt: {
1051
0
    const char format[2] = "i";
1052
0
    return PyArg_Parse(py_return.get(), format, (int *)ret_value);
1053
0
  }
1054
0
  case eScriptReturnTypeIntUnsigned: {
1055
0
    const char format[2] = "I";
1056
0
    return PyArg_Parse(py_return.get(), format, (unsigned int *)ret_value);
1057
0
  }
1058
0
  case eScriptReturnTypeLongInt: {
1059
0
    const char format[2] = "l";
1060
0
    return PyArg_Parse(py_return.get(), format, (long *)ret_value);
1061
0
  }
1062
0
  case eScriptReturnTypeLongIntUnsigned: {
1063
0
    const char format[2] = "k";
1064
0
    return PyArg_Parse(py_return.get(), format, (unsigned long *)ret_value);
1065
0
  }
1066
0
  case eScriptReturnTypeLongLong: {
1067
0
    const char format[2] = "L";
1068
0
    return PyArg_Parse(py_return.get(), format, (long long *)ret_value);
1069
0
  }
1070
0
  case eScriptReturnTypeLongLongUnsigned: {
1071
0
    const char format[2] = "K";
1072
0
    return PyArg_Parse(py_return.get(), format,
1073
0
                       (unsigned long long *)ret_value);
1074
0
  }
1075
0
  case eScriptReturnTypeFloat: {
1076
0
    const char format[2] = "f";
1077
0
    return PyArg_Parse(py_return.get(), format, (float *)ret_value);
1078
0
  }
1079
0
  case eScriptReturnTypeDouble: {
1080
0
    const char format[2] = "d";
1081
0
    return PyArg_Parse(py_return.get(), format, (double *)ret_value);
1082
0
  }
1083
0
  case eScriptReturnTypeChar: {
1084
0
    const char format[2] = "c";
1085
0
    return PyArg_Parse(py_return.get(), format, (char *)ret_value);
1086
0
  }
1087
0
  case eScriptReturnTypeOpaqueObject: {
1088
0
    *((PyObject **)ret_value) = py_return.release();
1089
0
    return true;
1090
0
  }
1091
5.16k
  }
1092
0
  llvm_unreachable("Fully covered switch!");
1093
0
}
1094
1095
Status ScriptInterpreterPythonImpl::ExecuteMultipleLines(
1096
263
    const char *in_string, const ExecuteScriptOptions &options) {
1097
1098
263
  if (in_string == nullptr)
1099
0
    return Status();
1100
1101
263
  llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
1102
263
      io_redirect_or_error = ScriptInterpreterIORedirect::Create(
1103
263
          options.GetEnableIO(), m_debugger, /*result=*/nullptr);
1104
1105
263
  if (!io_redirect_or_error)
1106
0
    return Status(io_redirect_or_error.takeError());
1107
1108
263
  ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
1109
1110
263
  Locker locker(this,
1111
263
                Locker::AcquireLock | Locker::InitSession |
1112
263
                    (options.GetSetLLDBGlobals() ? 
Locker::InitGlobals47
:
0216
) |
1113
263
                    Locker::NoSTDIN,
1114
263
                Locker::FreeAcquiredLock | Locker::TearDownSession,
1115
263
                io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
1116
263
                io_redirect.GetErrorFile());
1117
1118
263
  PythonModule &main_module = GetMainModule();
1119
263
  PythonDictionary globals = main_module.GetDictionary();
1120
1121
263
  PythonDictionary locals = GetSessionDictionary();
1122
263
  if (!locals.IsValid())
1123
0
    locals = unwrapIgnoringErrors(
1124
0
        As<PythonDictionary>(globals.GetAttribute(m_dictionary_name)));
1125
263
  if (!locals.IsValid())
1126
0
    locals = globals;
1127
1128
263
  Expected<PythonObject> return_value =
1129
263
      runStringMultiLine(in_string, globals, locals);
1130
1131
263
  if (!return_value) {
1132
5
    llvm::Error error =
1133
5
        llvm::handleErrors(return_value.takeError(), [&](PythonException &E) {
1134
5
          llvm::Error error = llvm::createStringError(
1135
5
              llvm::inconvertibleErrorCode(), E.ReadBacktrace());
1136
5
          if (!options.GetMaskoutErrors())
1137
0
            E.Restore();
1138
5
          return error;
1139
5
        });
1140
5
    return Status(std::move(error));
1141
5
  }
1142
1143
258
  return Status();
1144
263
}
1145
1146
void ScriptInterpreterPythonImpl::CollectDataForBreakpointCommandCallback(
1147
    std::vector<std::reference_wrapper<BreakpointOptions>> &bp_options_vec,
1148
2
    CommandReturnObject &result) {
1149
2
  m_active_io_handler = eIOHandlerBreakpoint;
1150
2
  m_debugger.GetCommandInterpreter().GetPythonCommandsFromIOHandler(
1151
2
      "    ", *this, &bp_options_vec);
1152
2
}
1153
1154
void ScriptInterpreterPythonImpl::CollectDataForWatchpointCommandCallback(
1155
0
    WatchpointOptions *wp_options, CommandReturnObject &result) {
1156
0
  m_active_io_handler = eIOHandlerWatchpoint;
1157
0
  m_debugger.GetCommandInterpreter().GetPythonCommandsFromIOHandler(
1158
0
      "    ", *this, wp_options);
1159
0
}
1160
1161
Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallbackFunction(
1162
    BreakpointOptions &bp_options, const char *function_name,
1163
12
    StructuredData::ObjectSP extra_args_sp) {
1164
12
  Status error;
1165
  // For now just cons up a oneliner that calls the provided function.
1166
12
  std::string oneliner("return ");
1167
12
  oneliner += function_name;
1168
1169
12
  llvm::Expected<unsigned> maybe_args =
1170
12
      GetMaxPositionalArgumentsForCallable(function_name);
1171
12
  if (!maybe_args) {
1172
1
    error.SetErrorStringWithFormat(
1173
1
        "could not get num args: %s",
1174
1
        llvm::toString(maybe_args.takeError()).c_str());
1175
1
    return error;
1176
1
  }
1177
11
  size_t max_args = *maybe_args;
1178
1179
11
  bool uses_extra_args = false;
1180
11
  if (max_args >= 4) {
1181
4
    uses_extra_args = true;
1182
4
    oneliner += "(frame, bp_loc, extra_args, internal_dict)";
1183
7
  } else if (max_args >= 3) {
1184
6
    if (extra_args_sp) {
1185
1
      error.SetErrorString("cannot pass extra_args to a three argument callback"
1186
1
                          );
1187
1
      return error;
1188
1
    }
1189
5
    uses_extra_args = false;
1190
5
    oneliner += "(frame, bp_loc, internal_dict)";
1191
5
  } else {
1192
1
    error.SetErrorStringWithFormat("expected 3 or 4 argument "
1193
1
                                   "function, %s can only take %zu",
1194
1
                                   function_name, max_args);
1195
1
    return error;
1196
1
  }
1197
1198
9
  SetBreakpointCommandCallback(bp_options, oneliner.c_str(), extra_args_sp,
1199
9
                               uses_extra_args);
1200
9
  return error;
1201
11
}
1202
1203
Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback(
1204
    BreakpointOptions &bp_options,
1205
1
    std::unique_ptr<BreakpointOptions::CommandData> &cmd_data_up) {
1206
1
  Status error;
1207
1
  error = GenerateBreakpointCommandCallbackData(cmd_data_up->user_source,
1208
1
                                                cmd_data_up->script_source,
1209
1
                                                false);
1210
1
  if (error.Fail()) {
1211
0
    return error;
1212
0
  }
1213
1
  auto baton_sp =
1214
1
      std::make_shared<BreakpointOptions::CommandBaton>(std::move(cmd_data_up));
1215
1
  bp_options.SetCallback(
1216
1
      ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp);
1217
1
  return error;
1218
1
}
1219
1220
Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback(
1221
7
    BreakpointOptions &bp_options, const char *command_body_text) {
1222
7
  return SetBreakpointCommandCallback(bp_options, command_body_text, {},false);
1223
7
}
1224
1225
// Set a Python one-liner as the callback for the breakpoint.
1226
Status ScriptInterpreterPythonImpl::SetBreakpointCommandCallback(
1227
    BreakpointOptions &bp_options, const char *command_body_text,
1228
16
    StructuredData::ObjectSP extra_args_sp, bool uses_extra_args) {
1229
16
  auto data_up = std::make_unique<CommandDataPython>(extra_args_sp);
1230
  // Split the command_body_text into lines, and pass that to
1231
  // GenerateBreakpointCommandCallbackData.  That will wrap the body in an
1232
  // auto-generated function, and return the function name in script_source.
1233
  // That is what the callback will actually invoke.
1234
1235
16
  data_up->user_source.SplitIntoLines(command_body_text);
1236
16
  Status error = GenerateBreakpointCommandCallbackData(data_up->user_source,
1237
16
                                                       data_up->script_source,
1238
16
                                                       uses_extra_args);
1239
16
  if (error.Success()) {
1240
15
    auto baton_sp =
1241
15
        std::make_shared<BreakpointOptions::CommandBaton>(std::move(data_up));
1242
15
    bp_options.SetCallback(
1243
15
        ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp);
1244
15
    return error;
1245
15
  }
1246
1
  return error;
1247
16
}
1248
1249
// Set a Python one-liner as the callback for the watchpoint.
1250
void ScriptInterpreterPythonImpl::SetWatchpointCommandCallback(
1251
2
    WatchpointOptions *wp_options, const char *oneliner) {
1252
2
  auto data_up = std::make_unique<WatchpointOptions::CommandData>();
1253
1254
  // It's necessary to set both user_source and script_source to the oneliner.
1255
  // The former is used to generate callback description (as in watchpoint
1256
  // command list) while the latter is used for Python to interpret during the
1257
  // actual callback.
1258
1259
2
  data_up->user_source.AppendString(oneliner);
1260
2
  data_up->script_source.assign(oneliner);
1261
1262
2
  if (GenerateWatchpointCommandCallbackData(data_up->user_source,
1263
2
                                            data_up->script_source)) {
1264
2
    auto baton_sp =
1265
2
        std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up));
1266
2
    wp_options->SetCallback(
1267
2
        ScriptInterpreterPythonImpl::WatchpointCallbackFunction, baton_sp);
1268
2
  }
1269
1270
2
  return;
1271
2
}
1272
1273
Status ScriptInterpreterPythonImpl::ExportFunctionDefinitionToInterpreter(
1274
47
    StringList &function_def) {
1275
  // Convert StringList to one long, newline delimited, const char *.
1276
47
  std::string function_def_string(function_def.CopyList());
1277
1278
47
  Status error = ExecuteMultipleLines(
1279
47
      function_def_string.c_str(),
1280
47
      ExecuteScriptOptions().SetEnableIO(false));
1281
47
  return error;
1282
47
}
1283
1284
Status ScriptInterpreterPythonImpl::GenerateFunction(const char *signature,
1285
47
                                                     const StringList &input) {
1286
47
  Status error;
1287
47
  int num_lines = input.GetSize();
1288
47
  if (num_lines == 0) {
1289
0
    error.SetErrorString("No input data.");
1290
0
    return error;
1291
0
  }
1292
1293
47
  if (!signature || *signature == 0) {
1294
0
    error.SetErrorString("No output function name.");
1295
0
    return error;
1296
0
  }
1297
1298
47
  StreamString sstr;
1299
47
  StringList auto_generated_function;
1300
47
  auto_generated_function.AppendString(signature);
1301
47
  auto_generated_function.AppendString(
1302
47
      "     global_dict = globals()"); // Grab the global dictionary
1303
47
  auto_generated_function.AppendString(
1304
47
      "     new_keys = internal_dict.keys()"); // Make a list of keys in the
1305
                                               // session dict
1306
47
  auto_generated_function.AppendString(
1307
47
      "     old_keys = global_dict.keys()"); // Save list of keys in global dict
1308
47
  auto_generated_function.AppendString(
1309
47
      "     global_dict.update (internal_dict)"); // Add the session dictionary
1310
                                                  // to the
1311
  // global dictionary.
1312
1313
  // Wrap everything up inside the function, increasing the indentation.
1314
1315
47
  auto_generated_function.AppendString("     if True:");
1316
96
  for (int i = 0; i < num_lines; 
++i49
) {
1317
49
    sstr.Clear();
1318
49
    sstr.Printf("       %s", input.GetStringAtIndex(i));
1319
49
    auto_generated_function.AppendString(sstr.GetData());
1320
49
  }
1321
47
  auto_generated_function.AppendString(
1322
47
      "     for key in new_keys:"); // Iterate over all the keys from session
1323
                                    // dict
1324
47
  auto_generated_function.AppendString(
1325
47
      "         internal_dict[key] = global_dict[key]"); // Update session dict
1326
                                                         // values
1327
47
  auto_generated_function.AppendString(
1328
47
      "         if key not in old_keys:"); // If key was not originally in
1329
                                           // global dict
1330
47
  auto_generated_function.AppendString(
1331
47
      "             del global_dict[key]"); //  ...then remove key/value from
1332
                                            //  global dict
1333
1334
  // Verify that the results are valid Python.
1335
1336
47
  error = ExportFunctionDefinitionToInterpreter(auto_generated_function);
1337
1338
47
  return error;
1339
47
}
1340
1341
bool ScriptInterpreterPythonImpl::GenerateTypeScriptFunction(
1342
26
    StringList &user_input, std::string &output, const void *name_token) {
1343
26
  static uint32_t num_created_functions = 0;
1344
26
  user_input.RemoveBlankLines();
1345
26
  StreamString sstr;
1346
1347
  // Check to see if we have any data; if not, just return.
1348
26
  if (user_input.GetSize() == 0)
1349
0
    return false;
1350
1351
  // Take what the user wrote, wrap it all up inside one big auto-generated
1352
  // Python function, passing in the ValueObject as parameter to the function.
1353
1354
26
  std::string auto_generated_function_name(
1355
26
      GenerateUniqueName("lldb_autogen_python_type_print_func",
1356
26
                         num_created_functions, name_token));
1357
26
  sstr.Printf("def %s (valobj, internal_dict):",
1358
26
              auto_generated_function_name.c_str());
1359
1360
26
  if (!GenerateFunction(sstr.GetData(), user_input).Success())
1361
0
    return false;
1362
1363
  // Store the name of the auto-generated function to be called.
1364
26
  output.assign(auto_generated_function_name);
1365
26
  return true;
1366
26
}
1367
1368
bool ScriptInterpreterPythonImpl::GenerateScriptAliasFunction(
1369
0
    StringList &user_input, std::string &output) {
1370
0
  static uint32_t num_created_functions = 0;
1371
0
  user_input.RemoveBlankLines();
1372
0
  StreamString sstr;
1373
1374
  // Check to see if we have any data; if not, just return.
1375
0
  if (user_input.GetSize() == 0)
1376
0
    return false;
1377
1378
0
  std::string auto_generated_function_name(GenerateUniqueName(
1379
0
      "lldb_autogen_python_cmd_alias_func", num_created_functions));
1380
1381
0
  sstr.Printf("def %s (debugger, args, result, internal_dict):",
1382
0
              auto_generated_function_name.c_str());
1383
1384
0
  if (!GenerateFunction(sstr.GetData(), user_input).Success())
1385
0
    return false;
1386
1387
  // Store the name of the auto-generated function to be called.
1388
0
  output.assign(auto_generated_function_name);
1389
0
  return true;
1390
0
}
1391
1392
bool ScriptInterpreterPythonImpl::GenerateTypeSynthClass(
1393
0
    StringList &user_input, std::string &output, const void *name_token) {
1394
0
  static uint32_t num_created_classes = 0;
1395
0
  user_input.RemoveBlankLines();
1396
0
  int num_lines = user_input.GetSize();
1397
0
  StreamString sstr;
1398
1399
  // Check to see if we have any data; if not, just return.
1400
0
  if (user_input.GetSize() == 0)
1401
0
    return false;
1402
1403
  // Wrap all user input into a Python class
1404
1405
0
  std::string auto_generated_class_name(GenerateUniqueName(
1406
0
      "lldb_autogen_python_type_synth_class", num_created_classes, name_token));
1407
1408
0
  StringList auto_generated_class;
1409
1410
  // Create the function name & definition string.
1411
1412
0
  sstr.Printf("class %s:", auto_generated_class_name.c_str());
1413
0
  auto_generated_class.AppendString(sstr.GetString());
1414
1415
  // Wrap everything up inside the class, increasing the indentation. we don't
1416
  // need to play any fancy indentation tricks here because there is no
1417
  // surrounding code whose indentation we need to honor
1418
0
  for (int i = 0; i < num_lines; ++i) {
1419
0
    sstr.Clear();
1420
0
    sstr.Printf("     %s", user_input.GetStringAtIndex(i));
1421
0
    auto_generated_class.AppendString(sstr.GetString());
1422
0
  }
1423
1424
  // Verify that the results are valid Python. (even though the method is
1425
  // ExportFunctionDefinitionToInterpreter, a class will actually be exported)
1426
  // (TODO: rename that method to ExportDefinitionToInterpreter)
1427
0
  if (!ExportFunctionDefinitionToInterpreter(auto_generated_class).Success())
1428
0
    return false;
1429
1430
  // Store the name of the auto-generated class
1431
1432
0
  output.assign(auto_generated_class_name);
1433
0
  return true;
1434
0
}
1435
1436
StructuredData::GenericSP
1437
10
ScriptInterpreterPythonImpl::CreateFrameRecognizer(const char *class_name) {
1438
10
  if (class_name == nullptr || class_name[0] == '\0')
1439
0
    return StructuredData::GenericSP();
1440
1441
10
  Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1442
10
  PythonObject ret_val = LLDBSWIGPython_CreateFrameRecognizer(
1443
10
      class_name, m_dictionary_name.c_str());
1444
1445
10
  return StructuredData::GenericSP(
1446
10
      new StructuredPythonObject(std::move(ret_val)));
1447
10
}
1448
1449
lldb::ValueObjectListSP ScriptInterpreterPythonImpl::GetRecognizedArguments(
1450
    const StructuredData::ObjectSP &os_plugin_object_sp,
1451
4
    lldb::StackFrameSP frame_sp) {
1452
4
  Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1453
1454
4
  if (!os_plugin_object_sp)
1455
0
    return ValueObjectListSP();
1456
1457
4
  StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
1458
4
  if (!generic)
1459
0
    return nullptr;
1460
1461
4
  PythonObject implementor(PyRefType::Borrowed,
1462
4
                           (PyObject *)generic->GetValue());
1463
1464
4
  if (!implementor.IsAllocated())
1465
0
    return ValueObjectListSP();
1466
1467
4
  PythonObject py_return(
1468
4
      PyRefType::Owned,
1469
4
      LLDBSwigPython_GetRecognizedArguments(implementor.get(), frame_sp));
1470
1471
  // if it fails, print the error but otherwise go on
1472
4
  if (PyErr_Occurred()) {
1473
0
    PyErr_Print();
1474
0
    PyErr_Clear();
1475
0
  }
1476
4
  if (py_return.get()) {
1477
4
    PythonList result_list(PyRefType::Borrowed, py_return.get());
1478
4
    ValueObjectListSP result = ValueObjectListSP(new ValueObjectList());
1479
11
    for (size_t i = 0; i < result_list.GetSize(); 
i++7
) {
1480
7
      PyObject *item = result_list.GetItemAtIndex(i).get();
1481
7
      lldb::SBValue *sb_value_ptr =
1482
7
          (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(item);
1483
7
      auto valobj_sp = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr);
1484
7
      if (valobj_sp)
1485
7
        result->Append(valobj_sp);
1486
7
    }
1487
4
    return result;
1488
4
  }
1489
0
  return ValueObjectListSP();
1490
4
}
1491
1492
StructuredData::GenericSP
1493
ScriptInterpreterPythonImpl::OSPlugin_CreatePluginObject(
1494
8
    const char *class_name, lldb::ProcessSP process_sp) {
1495
8
  if (class_name == nullptr || class_name[0] == '\0')
1496
0
    return StructuredData::GenericSP();
1497
1498
8
  if (!process_sp)
1499
0
    return StructuredData::GenericSP();
1500
1501
8
  Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1502
8
  PythonObject ret_val = LLDBSWIGPythonCreateOSPlugin(
1503
8
      class_name, m_dictionary_name.c_str(), process_sp);
1504
1505
8
  return StructuredData::GenericSP(
1506
8
      new StructuredPythonObject(std::move(ret_val)));
1507
8
}
1508
1509
StructuredData::DictionarySP ScriptInterpreterPythonImpl::OSPlugin_RegisterInfo(
1510
1
    StructuredData::ObjectSP os_plugin_object_sp) {
1511
1
  Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1512
1513
1
  static char callee_name[] = "get_register_info";
1514
1515
1
  if (!os_plugin_object_sp)
1516
0
    return StructuredData::DictionarySP();
1517
1518
1
  StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
1519
1
  if (!generic)
1520
0
    return nullptr;
1521
1522
1
  PythonObject implementor(PyRefType::Borrowed,
1523
1
                           (PyObject *)generic->GetValue());
1524
1525
1
  if (!implementor.IsAllocated())
1526
0
    return StructuredData::DictionarySP();
1527
1528
1
  PythonObject pmeth(PyRefType::Owned,
1529
1
                     PyObject_GetAttrString(implementor.get(), callee_name));
1530
1531
1
  if (PyErr_Occurred())
1532
0
    PyErr_Clear();
1533
1534
1
  if (!pmeth.IsAllocated())
1535
0
    return StructuredData::DictionarySP();
1536
1537
1
  if (PyCallable_Check(pmeth.get()) == 0) {
1538
0
    if (PyErr_Occurred())
1539
0
      PyErr_Clear();
1540
1541
0
    return StructuredData::DictionarySP();
1542
0
  }
1543
1544
1
  if (PyErr_Occurred())
1545
0
    PyErr_Clear();
1546
1547
  // right now we know this function exists and is callable..
1548
1
  PythonObject py_return(
1549
1
      PyRefType::Owned,
1550
1
      PyObject_CallMethod(implementor.get(), callee_name, nullptr));
1551
1552
  // if it fails, print the error but otherwise go on
1553
1
  if (PyErr_Occurred()) {
1554
0
    PyErr_Print();
1555
0
    PyErr_Clear();
1556
0
  }
1557
1
  if (py_return.get()) {
1558
1
    PythonDictionary result_dict(PyRefType::Borrowed, py_return.get());
1559
1
    return result_dict.CreateStructuredDictionary();
1560
1
  }
1561
0
  return StructuredData::DictionarySP();
1562
1
}
1563
1564
StructuredData::ArraySP ScriptInterpreterPythonImpl::OSPlugin_ThreadsInfo(
1565
16
    StructuredData::ObjectSP os_plugin_object_sp) {
1566
16
  Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1567
1568
16
  static char callee_name[] = "get_thread_info";
1569
1570
16
  if (!os_plugin_object_sp)
1571
0
    return StructuredData::ArraySP();
1572
1573
16
  StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
1574
16
  if (!generic)
1575
0
    return nullptr;
1576
1577
16
  PythonObject implementor(PyRefType::Borrowed,
1578
16
                           (PyObject *)generic->GetValue());
1579
1580
16
  if (!implementor.IsAllocated())
1581
0
    return StructuredData::ArraySP();
1582
1583
16
  PythonObject pmeth(PyRefType::Owned,
1584
16
                     PyObject_GetAttrString(implementor.get(), callee_name));
1585
1586
16
  if (PyErr_Occurred())
1587
0
    PyErr_Clear();
1588
1589
16
  if (!pmeth.IsAllocated())
1590
0
    return StructuredData::ArraySP();
1591
1592
16
  if (PyCallable_Check(pmeth.get()) == 0) {
1593
0
    if (PyErr_Occurred())
1594
0
      PyErr_Clear();
1595
1596
0
    return StructuredData::ArraySP();
1597
0
  }
1598
1599
16
  if (PyErr_Occurred())
1600
0
    PyErr_Clear();
1601
1602
  // right now we know this function exists and is callable..
1603
16
  PythonObject py_return(
1604
16
      PyRefType::Owned,
1605
16
      PyObject_CallMethod(implementor.get(), callee_name, nullptr));
1606
1607
  // if it fails, print the error but otherwise go on
1608
16
  if (PyErr_Occurred()) {
1609
0
    PyErr_Print();
1610
0
    PyErr_Clear();
1611
0
  }
1612
1613
16
  if (py_return.get()) {
1614
16
    PythonList result_list(PyRefType::Borrowed, py_return.get());
1615
16
    return result_list.CreateStructuredArray();
1616
16
  }
1617
0
  return StructuredData::ArraySP();
1618
16
}
1619
1620
StructuredData::StringSP
1621
ScriptInterpreterPythonImpl::OSPlugin_RegisterContextData(
1622
9
    StructuredData::ObjectSP os_plugin_object_sp, lldb::tid_t tid) {
1623
9
  Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1624
1625
9
  static char callee_name[] = "get_register_data";
1626
9
  static char *param_format =
1627
9
      const_cast<char *>(GetPythonValueFormatString(tid));
1628
1629
9
  if (!os_plugin_object_sp)
1630
0
    return StructuredData::StringSP();
1631
1632
9
  StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
1633
9
  if (!generic)
1634
0
    return nullptr;
1635
9
  PythonObject implementor(PyRefType::Borrowed,
1636
9
                           (PyObject *)generic->GetValue());
1637
1638
9
  if (!implementor.IsAllocated())
1639
0
    return StructuredData::StringSP();
1640
1641
9
  PythonObject pmeth(PyRefType::Owned,
1642
9
                     PyObject_GetAttrString(implementor.get(), callee_name));
1643
1644
9
  if (PyErr_Occurred())
1645
6
    PyErr_Clear();
1646
1647
9
  if (!pmeth.IsAllocated())
1648
6
    return StructuredData::StringSP();
1649
1650
3
  if (PyCallable_Check(pmeth.get()) == 0) {
1651
0
    if (PyErr_Occurred())
1652
0
      PyErr_Clear();
1653
0
    return StructuredData::StringSP();
1654
0
  }
1655
1656
3
  if (PyErr_Occurred())
1657
0
    PyErr_Clear();
1658
1659
  // right now we know this function exists and is callable..
1660
3
  PythonObject py_return(
1661
3
      PyRefType::Owned,
1662
3
      PyObject_CallMethod(implementor.get(), callee_name, param_format, tid));
1663
1664
  // if it fails, print the error but otherwise go on
1665
3
  if (PyErr_Occurred()) {
1666
0
    PyErr_Print();
1667
0
    PyErr_Clear();
1668
0
  }
1669
1670
3
  if (py_return.get()) {
1671
3
    PythonBytes result(PyRefType::Borrowed, py_return.get());
1672
3
    return result.CreateStructuredString();
1673
3
  }
1674
0
  return StructuredData::StringSP();
1675
3
}
1676
1677
StructuredData::DictionarySP ScriptInterpreterPythonImpl::OSPlugin_CreateThread(
1678
    StructuredData::ObjectSP os_plugin_object_sp, lldb::tid_t tid,
1679
0
    lldb::addr_t context) {
1680
0
  Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
1681
1682
0
  static char callee_name[] = "create_thread";
1683
0
  std::string param_format;
1684
0
  param_format += GetPythonValueFormatString(tid);
1685
0
  param_format += GetPythonValueFormatString(context);
1686
1687
0
  if (!os_plugin_object_sp)
1688
0
    return StructuredData::DictionarySP();
1689
1690
0
  StructuredData::Generic *generic = os_plugin_object_sp->GetAsGeneric();
1691
0
  if (!generic)
1692
0
    return nullptr;
1693
1694
0
  PythonObject implementor(PyRefType::Borrowed,
1695
0
                           (PyObject *)generic->GetValue());
1696
1697
0
  if (!implementor.IsAllocated())
1698
0
    return StructuredData::DictionarySP();
1699
1700
0
  PythonObject pmeth(PyRefType::Owned,
1701
0
                     PyObject_GetAttrString(implementor.get(), callee_name));
1702
1703
0
  if (PyErr_Occurred())
1704
0
    PyErr_Clear();
1705
1706
0
  if (!pmeth.IsAllocated())
1707
0
    return StructuredData::DictionarySP();
1708
1709
0
  if (PyCallable_Check(pmeth.get()) == 0) {
1710
0
    if (PyErr_Occurred())
1711
0
      PyErr_Clear();
1712
0
    return StructuredData::DictionarySP();
1713
0
  }
1714
1715
0
  if (PyErr_Occurred())
1716
0
    PyErr_Clear();
1717
1718
  // right now we know this function exists and is callable..
1719
0
  PythonObject py_return(PyRefType::Owned,
1720
0
                         PyObject_CallMethod(implementor.get(), callee_name,
1721
0
                                             &param_format[0], tid, context));
1722
1723
  // if it fails, print the error but otherwise go on
1724
0
  if (PyErr_Occurred()) {
1725
0
    PyErr_Print();
1726
0
    PyErr_Clear();
1727
0
  }
1728
1729
0
  if (py_return.get()) {
1730
0
    PythonDictionary result_dict(PyRefType::Borrowed, py_return.get());
1731
0
    return result_dict.CreateStructuredDictionary();
1732
0
  }
1733
0
  return StructuredData::DictionarySP();
1734
0
}
1735
1736
StructuredData::ObjectSP ScriptInterpreterPythonImpl::CreateScriptedThreadPlan(
1737
    const char *class_name, const StructuredDataImpl &args_data,
1738
12
    std::string &error_str, lldb::ThreadPlanSP thread_plan_sp) {
1739
12
  if (class_name == nullptr || class_name[0] == '\0')
1740
0
    return StructuredData::ObjectSP();
1741
1742
12
  if (!thread_plan_sp.get())
1743
0
    return {};
1744
1745
12
  Debugger &debugger = thread_plan_sp->GetTarget().GetDebugger();
1746
12
  ScriptInterpreterPythonImpl *python_interpreter =
1747
12
      GetPythonInterpreter(debugger);
1748
1749
12
  if (!python_interpreter)
1750
0
    return {};
1751
1752
12
  Locker py_lock(this,
1753
12
                 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1754
12
  PythonObject ret_val = LLDBSwigPythonCreateScriptedThreadPlan(
1755
12
      class_name, python_interpreter->m_dictionary_name.c_str(), args_data,
1756
12
      error_str, thread_plan_sp);
1757
12
  if (!ret_val)
1758
1
    return {};
1759
1760
11
  return StructuredData::ObjectSP(
1761
11
      new StructuredPythonObject(std::move(ret_val)));
1762
12
}
1763
1764
bool ScriptInterpreterPythonImpl::ScriptedThreadPlanExplainsStop(
1765
4
    StructuredData::ObjectSP implementor_sp, Event *event, bool &script_error) {
1766
4
  bool explains_stop = true;
1767
4
  StructuredData::Generic *generic = nullptr;
1768
4
  if (implementor_sp)
1769
4
    generic = implementor_sp->GetAsGeneric();
1770
4
  if (generic) {
1771
4
    Locker py_lock(this,
1772
4
                   Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1773
4
    explains_stop = LLDBSWIGPythonCallThreadPlan(
1774
4
        generic->GetValue(), "explains_stop", event, script_error);
1775
4
    if (script_error)
1776
0
      return true;
1777
4
  }
1778
4
  return explains_stop;
1779
4
}
1780
1781
bool ScriptInterpreterPythonImpl::ScriptedThreadPlanShouldStop(
1782
13
    StructuredData::ObjectSP implementor_sp, Event *event, bool &script_error) {
1783
13
  bool should_stop = true;
1784
13
  StructuredData::Generic *generic = nullptr;
1785
13
  if (implementor_sp)
1786
13
    generic = implementor_sp->GetAsGeneric();
1787
13
  if (generic) {
1788
13
    Locker py_lock(this,
1789
13
                   Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1790
13
    should_stop = LLDBSWIGPythonCallThreadPlan(
1791
13
        generic->GetValue(), "should_stop", event, script_error);
1792
13
    if (script_error)
1793
0
      return true;
1794
13
  }
1795
13
  return should_stop;
1796
13
}
1797
1798
bool ScriptInterpreterPythonImpl::ScriptedThreadPlanIsStale(
1799
4
    StructuredData::ObjectSP implementor_sp, bool &script_error) {
1800
4
  bool is_stale = true;
1801
4
  StructuredData::Generic *generic = nullptr;
1802
4
  if (implementor_sp)
1803
4
    generic = implementor_sp->GetAsGeneric();
1804
4
  if (generic) {
1805
4
    Locker py_lock(this,
1806
4
                   Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1807
4
    is_stale = LLDBSWIGPythonCallThreadPlan(generic->GetValue(), "is_stale",
1808
4
                                            nullptr, script_error);
1809
4
    if (script_error)
1810
0
      return true;
1811
4
  }
1812
4
  return is_stale;
1813
4
}
1814
1815
lldb::StateType ScriptInterpreterPythonImpl::ScriptedThreadPlanGetRunState(
1816
7
    StructuredData::ObjectSP implementor_sp, bool &script_error) {
1817
7
  bool should_step = false;
1818
7
  StructuredData::Generic *generic = nullptr;
1819
7
  if (implementor_sp)
1820
7
    generic = implementor_sp->GetAsGeneric();
1821
7
  if (generic) {
1822
7
    Locker py_lock(this,
1823
7
                   Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1824
7
    should_step = LLDBSWIGPythonCallThreadPlan(
1825
7
        generic->GetValue(), "should_step", nullptr, script_error);
1826
7
    if (script_error)
1827
0
      should_step = true;
1828
7
  }
1829
7
  if (should_step)
1830
7
    return lldb::eStateStepping;
1831
0
  return lldb::eStateRunning;
1832
7
}
1833
1834
StructuredData::GenericSP
1835
ScriptInterpreterPythonImpl::CreateScriptedBreakpointResolver(
1836
    const char *class_name, const StructuredDataImpl &args_data,
1837
22
    lldb::BreakpointSP &bkpt_sp) {
1838
1839
22
  if (class_name == nullptr || class_name[0] == '\0')
1840
0
    return StructuredData::GenericSP();
1841
1842
22
  if (!bkpt_sp.get())
1843
0
    return StructuredData::GenericSP();
1844
1845
22
  Debugger &debugger = bkpt_sp->GetTarget().GetDebugger();
1846
22
  ScriptInterpreterPythonImpl *python_interpreter =
1847
22
      GetPythonInterpreter(debugger);
1848
1849
22
  if (!python_interpreter)
1850
0
    return StructuredData::GenericSP();
1851
1852
22
  Locker py_lock(this,
1853
22
                 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1854
1855
22
  PythonObject ret_val = LLDBSwigPythonCreateScriptedBreakpointResolver(
1856
22
      class_name, python_interpreter->m_dictionary_name.c_str(), args_data,
1857
22
      bkpt_sp);
1858
1859
22
  return StructuredData::GenericSP(
1860
22
      new StructuredPythonObject(std::move(ret_val)));
1861
22
}
1862
1863
bool ScriptInterpreterPythonImpl::ScriptedBreakpointResolverSearchCallback(
1864
479
    StructuredData::GenericSP implementor_sp, SymbolContext *sym_ctx) {
1865
479
  bool should_continue = false;
1866
1867
479
  if (implementor_sp) {
1868
479
    Locker py_lock(this,
1869
479
                   Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1870
479
    should_continue = LLDBSwigPythonCallBreakpointResolver(
1871
479
        implementor_sp->GetValue(), "__callback__", sym_ctx);
1872
479
    if (PyErr_Occurred()) {
1873
0
      PyErr_Print();
1874
0
      PyErr_Clear();
1875
0
    }
1876
479
  }
1877
479
  return should_continue;
1878
479
}
1879
1880
lldb::SearchDepth
1881
ScriptInterpreterPythonImpl::ScriptedBreakpointResolverSearchDepth(
1882
1.04k
    StructuredData::GenericSP implementor_sp) {
1883
1.04k
  int depth_as_int = lldb::eSearchDepthModule;
1884
1.04k
  if (implementor_sp) {
1885
1.04k
    Locker py_lock(this,
1886
1.04k
                   Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1887
1.04k
    depth_as_int = LLDBSwigPythonCallBreakpointResolver(
1888
1.04k
        implementor_sp->GetValue(), "__get_depth__", nullptr);
1889
1.04k
    if (PyErr_Occurred()) {
1890
0
      PyErr_Print();
1891
0
      PyErr_Clear();
1892
0
    }
1893
1.04k
  }
1894
1.04k
  if (depth_as_int == lldb::eSearchDepthInvalid)
1895
781
    return lldb::eSearchDepthModule;
1896
1897
265
  if (depth_as_int <= lldb::kLastSearchDepthKind)
1898
262
    return (lldb::SearchDepth)depth_as_int;
1899
3
  return lldb::eSearchDepthModule;
1900
265
}
1901
1902
StructuredData::GenericSP ScriptInterpreterPythonImpl::CreateScriptedStopHook(
1903
    TargetSP target_sp, const char *class_name,
1904
10
    const StructuredDataImpl &args_data, Status &error) {
1905
1906
10
  if (!target_sp) {
1907
0
    error.SetErrorString("No target for scripted stop-hook.");
1908
0
    return StructuredData::GenericSP();
1909
0
  }
1910
1911
10
  if (class_name == nullptr || class_name[0] == '\0') {
1912
0
    error.SetErrorString("No class name for scripted stop-hook.");
1913
0
    return StructuredData::GenericSP();
1914
0
  }
1915
1916
10
  ScriptInterpreterPythonImpl *python_interpreter =
1917
10
      GetPythonInterpreter(m_debugger);
1918
1919
10
  if (!python_interpreter) {
1920
0
    error.SetErrorString("No script interpreter for scripted stop-hook.");
1921
0
    return StructuredData::GenericSP();
1922
0
  }
1923
1924
10
  Locker py_lock(this,
1925
10
                 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1926
1927
10
  PythonObject ret_val = LLDBSwigPythonCreateScriptedStopHook(
1928
10
      target_sp, class_name, python_interpreter->m_dictionary_name.c_str(),
1929
10
      args_data, error);
1930
1931
10
  return StructuredData::GenericSP(
1932
10
      new StructuredPythonObject(std::move(ret_val)));
1933
10
}
1934
1935
bool ScriptInterpreterPythonImpl::ScriptedStopHookHandleStop(
1936
    StructuredData::GenericSP implementor_sp, ExecutionContext &exc_ctx,
1937
6
    lldb::StreamSP stream_sp) {
1938
6
  assert(implementor_sp &&
1939
6
         "can't call a stop hook with an invalid implementor");
1940
0
  assert(stream_sp && "can't call a stop hook with an invalid stream");
1941
1942
0
  Locker py_lock(this,
1943
6
                 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1944
1945
6
  lldb::ExecutionContextRefSP exc_ctx_ref_sp(new ExecutionContextRef(exc_ctx));
1946
1947
6
  bool ret_val = LLDBSwigPythonStopHookCallHandleStop(
1948
6
      implementor_sp->GetValue(), exc_ctx_ref_sp, stream_sp);
1949
6
  return ret_val;
1950
6
}
1951
1952
StructuredData::ObjectSP
1953
ScriptInterpreterPythonImpl::LoadPluginModule(const FileSpec &file_spec,
1954
0
                                              lldb_private::Status &error) {
1955
0
  if (!FileSystem::Instance().Exists(file_spec)) {
1956
0
    error.SetErrorString("no such file");
1957
0
    return StructuredData::ObjectSP();
1958
0
  }
1959
1960
0
  StructuredData::ObjectSP module_sp;
1961
1962
0
  LoadScriptOptions load_script_options =
1963
0
      LoadScriptOptions().SetInitSession(true).SetSilent(false);
1964
0
  if (LoadScriptingModule(file_spec.GetPath().c_str(), load_script_options,
1965
0
                          error, &module_sp))
1966
0
    return module_sp;
1967
1968
0
  return StructuredData::ObjectSP();
1969
0
}
1970
1971
StructuredData::DictionarySP ScriptInterpreterPythonImpl::GetDynamicSettings(
1972
    StructuredData::ObjectSP plugin_module_sp, Target *target,
1973
0
    const char *setting_name, lldb_private::Status &error) {
1974
0
  if (!plugin_module_sp || !target || !setting_name || !setting_name[0])
1975
0
    return StructuredData::DictionarySP();
1976
0
  StructuredData::Generic *generic = plugin_module_sp->GetAsGeneric();
1977
0
  if (!generic)
1978
0
    return StructuredData::DictionarySP();
1979
1980
0
  Locker py_lock(this,
1981
0
                 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
1982
0
  TargetSP target_sp(target->shared_from_this());
1983
1984
0
  auto setting = (PyObject *)LLDBSWIGPython_GetDynamicSetting(
1985
0
      generic->GetValue(), setting_name, target_sp);
1986
1987
0
  if (!setting)
1988
0
    return StructuredData::DictionarySP();
1989
1990
0
  PythonDictionary py_dict =
1991
0
      unwrapIgnoringErrors(As<PythonDictionary>(Take<PythonObject>(setting)));
1992
1993
0
  if (!py_dict)
1994
0
    return StructuredData::DictionarySP();
1995
1996
0
  return py_dict.CreateStructuredDictionary();
1997
0
}
1998
1999
StructuredData::ObjectSP
2000
ScriptInterpreterPythonImpl::CreateSyntheticScriptedProvider(
2001
120
    const char *class_name, lldb::ValueObjectSP valobj) {
2002
120
  if (class_name == nullptr || class_name[0] == '\0')
2003
0
    return StructuredData::ObjectSP();
2004
2005
120
  if (!valobj.get())
2006
0
    return StructuredData::ObjectSP();
2007
2008
120
  ExecutionContext exe_ctx(valobj->GetExecutionContextRef());
2009
120
  Target *target = exe_ctx.GetTargetPtr();
2010
2011
120
  if (!target)
2012
0
    return StructuredData::ObjectSP();
2013
2014
120
  Debugger &debugger = target->GetDebugger();
2015
120
  ScriptInterpreterPythonImpl *python_interpreter =
2016
120
      GetPythonInterpreter(debugger);
2017
2018
120
  if (!python_interpreter)
2019
0
    return StructuredData::ObjectSP();
2020
2021
120
  Locker py_lock(this,
2022
120
                 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2023
120
  PythonObject ret_val = LLDBSwigPythonCreateSyntheticProvider(
2024
120
      class_name, python_interpreter->m_dictionary_name.c_str(), valobj);
2025
2026
120
  return StructuredData::ObjectSP(
2027
120
      new StructuredPythonObject(std::move(ret_val)));
2028
120
}
2029
2030
StructuredData::GenericSP
2031
14
ScriptInterpreterPythonImpl::CreateScriptCommandObject(const char *class_name) {
2032
14
  DebuggerSP debugger_sp(m_debugger.shared_from_this());
2033
2034
14
  if (class_name == nullptr || class_name[0] == '\0')
2035
0
    return StructuredData::GenericSP();
2036
2037
14
  if (!debugger_sp.get())
2038
0
    return StructuredData::GenericSP();
2039
2040
14
  Locker py_lock(this,
2041
14
                 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2042
14
  PythonObject ret_val = LLDBSwigPythonCreateCommandObject(
2043
14
      class_name, m_dictionary_name.c_str(), debugger_sp);
2044
2045
14
  return StructuredData::GenericSP(
2046
14
      new StructuredPythonObject(std::move(ret_val)));
2047
14
}
2048
2049
bool ScriptInterpreterPythonImpl::GenerateTypeScriptFunction(
2050
0
    const char *oneliner, std::string &output, const void *name_token) {
2051
0
  StringList input;
2052
0
  input.SplitIntoLines(oneliner, strlen(oneliner));
2053
0
  return GenerateTypeScriptFunction(input, output, name_token);
2054
0
}
2055
2056
bool ScriptInterpreterPythonImpl::GenerateTypeSynthClass(
2057
0
    const char *oneliner, std::string &output, const void *name_token) {
2058
0
  StringList input;
2059
0
  input.SplitIntoLines(oneliner, strlen(oneliner));
2060
0
  return GenerateTypeSynthClass(input, output, name_token);
2061
0
}
2062
2063
Status ScriptInterpreterPythonImpl::GenerateBreakpointCommandCallbackData(
2064
    StringList &user_input, std::string &output,
2065
19
    bool has_extra_args) {
2066
19
  static uint32_t num_created_functions = 0;
2067
19
  user_input.RemoveBlankLines();
2068
19
  StreamString sstr;
2069
19
  Status error;
2070
19
  if (user_input.GetSize() == 0) {
2071
0
    error.SetErrorString("No input data.");
2072
0
    return error;
2073
0
  }
2074
2075
19
  std::string auto_generated_function_name(GenerateUniqueName(
2076
19
      "lldb_autogen_python_bp_callback_func_", num_created_functions));
2077
19
  if (has_extra_args)
2078
4
    sstr.Printf("def %s (frame, bp_loc, extra_args, internal_dict):",
2079
4
                auto_generated_function_name.c_str());
2080
15
  else
2081
15
    sstr.Printf("def %s (frame, bp_loc, internal_dict):",
2082
15
                auto_generated_function_name.c_str());
2083
2084
19
  error = GenerateFunction(sstr.GetData(), user_input);
2085
19
  if (!error.Success())
2086
1
    return error;
2087
2088
  // Store the name of the auto-generated function to be called.
2089
18
  output.assign(auto_generated_function_name);
2090
18
  return error;
2091
19
}
2092
2093
bool ScriptInterpreterPythonImpl::GenerateWatchpointCommandCallbackData(
2094
2
    StringList &user_input, std::string &output) {
2095
2
  static uint32_t num_created_functions = 0;
2096
2
  user_input.RemoveBlankLines();
2097
2
  StreamString sstr;
2098
2099
2
  if (user_input.GetSize() == 0)
2100
0
    return false;
2101
2102
2
  std::string auto_generated_function_name(GenerateUniqueName(
2103
2
      "lldb_autogen_python_wp_callback_func_", num_created_functions));
2104
2
  sstr.Printf("def %s (frame, wp, internal_dict):",
2105
2
              auto_generated_function_name.c_str());
2106
2107
2
  if (!GenerateFunction(sstr.GetData(), user_input).Success())
2108
0
    return false;
2109
2110
  // Store the name of the auto-generated function to be called.
2111
2
  output.assign(auto_generated_function_name);
2112
2
  return true;
2113
2
}
2114
2115
bool ScriptInterpreterPythonImpl::GetScriptedSummary(
2116
    const char *python_function_name, lldb::ValueObjectSP valobj,
2117
    StructuredData::ObjectSP &callee_wrapper_sp,
2118
124
    const TypeSummaryOptions &options, std::string &retval) {
2119
2120
124
  LLDB_SCOPED_TIMER();
2121
2122
124
  if (!valobj.get()) {
2123
0
    retval.assign("<no object>");
2124
0
    return false;
2125
0
  }
2126
2127
124
  void *old_callee = nullptr;
2128
124
  StructuredData::Generic *generic = nullptr;
2129
124
  if (callee_wrapper_sp) {
2130
80
    generic = callee_wrapper_sp->GetAsGeneric();
2131
80
    if (generic)
2132
80
      old_callee = generic->GetValue();
2133
80
  }
2134
124
  void *new_callee = old_callee;
2135
2136
124
  bool ret_val;
2137
124
  if (python_function_name && *python_function_name) {
2138
124
    {
2139
124
      Locker py_lock(this, Locker::AcquireLock | Locker::InitSession |
2140
124
                               Locker::NoSTDIN);
2141
124
      {
2142
124
        TypeSummaryOptionsSP options_sp(new TypeSummaryOptions(options));
2143
2144
124
        static Timer::Category func_cat("LLDBSwigPythonCallTypeScript");
2145
124
        Timer scoped_timer(func_cat, "LLDBSwigPythonCallTypeScript");
2146
124
        ret_val = LLDBSwigPythonCallTypeScript(
2147
124
            python_function_name, GetSessionDictionary().get(), valobj,
2148
124
            &new_callee, options_sp, retval);
2149
124
      }
2150
124
    }
2151
124
  } else {
2152
0
    retval.assign("<no function name>");
2153
0
    return false;
2154
0
  }
2155
2156
124
  if (new_callee && old_callee != new_callee) {
2157
44
    Locker py_lock(this,
2158
44
                   Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2159
44
    callee_wrapper_sp = std::make_shared<StructuredPythonObject>(
2160
44
        PythonObject(PyRefType::Borrowed, static_cast<PyObject *>(new_callee)));
2161
44
  }
2162
2163
124
  return ret_val;
2164
124
}
2165
2166
bool ScriptInterpreterPythonImpl::BreakpointCallbackFunction(
2167
    void *baton, StoppointCallbackContext *context, user_id_t break_id,
2168
21
    user_id_t break_loc_id) {
2169
21
  CommandDataPython *bp_option_data = (CommandDataPython *)baton;
2170
21
  const char *python_function_name = bp_option_data->script_source.c_str();
2171
2172
21
  if (!context)
2173
0
    return true;
2174
2175
21
  ExecutionContext exe_ctx(context->exe_ctx_ref);
2176
21
  Target *target = exe_ctx.GetTargetPtr();
2177
2178
21
  if (!target)
2179
0
    return true;
2180
2181
21
  Debugger &debugger = target->GetDebugger();
2182
21
  ScriptInterpreterPythonImpl *python_interpreter =
2183
21
      GetPythonInterpreter(debugger);
2184
2185
21
  if (!python_interpreter)
2186
0
    return true;
2187
2188
21
  if (python_function_name && python_function_name[0]) {
2189
21
    const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
2190
21
    BreakpointSP breakpoint_sp = target->GetBreakpointByID(break_id);
2191
21
    if (breakpoint_sp) {
2192
21
      const BreakpointLocationSP bp_loc_sp(
2193
21
          breakpoint_sp->FindLocationByID(break_loc_id));
2194
2195
21
      if (stop_frame_sp && bp_loc_sp) {
2196
21
        bool ret_val = true;
2197
21
        {
2198
21
          Locker py_lock(python_interpreter, Locker::AcquireLock |
2199
21
                                                 Locker::InitSession |
2200
21
                                                 Locker::NoSTDIN);
2201
21
          Expected<bool> maybe_ret_val =
2202
21
              LLDBSwigPythonBreakpointCallbackFunction(
2203
21
                  python_function_name,
2204
21
                  python_interpreter->m_dictionary_name.c_str(), stop_frame_sp,
2205
21
                  bp_loc_sp, bp_option_data->m_extra_args);
2206
2207
21
          if (!maybe_ret_val) {
2208
2209
1
            llvm::handleAllErrors(
2210
1
                maybe_ret_val.takeError(),
2211
1
                [&](PythonException &E) {
2212
1
                  debugger.GetErrorStream() << E.ReadBacktrace();
2213
1
                },
2214
1
                [&](const llvm::ErrorInfoBase &E) {
2215
0
                  debugger.GetErrorStream() << E.message();
2216
0
                });
2217
2218
20
          } else {
2219
20
            ret_val = maybe_ret_val.get();
2220
20
          }
2221
21
        }
2222
21
        return ret_val;
2223
21
      }
2224
21
    }
2225
21
  }
2226
  // We currently always true so we stop in case anything goes wrong when
2227
  // trying to call the script function
2228
0
  return true;
2229
21
}
2230
2231
bool ScriptInterpreterPythonImpl::WatchpointCallbackFunction(
2232
3
    void *baton, StoppointCallbackContext *context, user_id_t watch_id) {
2233
3
  WatchpointOptions::CommandData *wp_option_data =
2234
3
      (WatchpointOptions::CommandData *)baton;
2235
3
  const char *python_function_name = wp_option_data->script_source.c_str();
2236
2237
3
  if (!context)
2238
0
    return true;
2239
2240
3
  ExecutionContext exe_ctx(context->exe_ctx_ref);
2241
3
  Target *target = exe_ctx.GetTargetPtr();
2242
2243
3
  if (!target)
2244
0
    return true;
2245
2246
3
  Debugger &debugger = target->GetDebugger();
2247
3
  ScriptInterpreterPythonImpl *python_interpreter =
2248
3
      GetPythonInterpreter(debugger);
2249
2250
3
  if (!python_interpreter)
2251
0
    return true;
2252
2253
3
  if (python_function_name && python_function_name[0]) {
2254
3
    const StackFrameSP stop_frame_sp(exe_ctx.GetFrameSP());
2255
3
    WatchpointSP wp_sp = target->GetWatchpointList().FindByID(watch_id);
2256
3
    if (wp_sp) {
2257
3
      if (stop_frame_sp && wp_sp) {
2258
3
        bool ret_val = true;
2259
3
        {
2260
3
          Locker py_lock(python_interpreter, Locker::AcquireLock |
2261
3
                                                 Locker::InitSession |
2262
3
                                                 Locker::NoSTDIN);
2263
3
          ret_val = LLDBSwigPythonWatchpointCallbackFunction(
2264
3
              python_function_name,
2265
3
              python_interpreter->m_dictionary_name.c_str(), stop_frame_sp,
2266
3
              wp_sp);
2267
3
        }
2268
3
        return ret_val;
2269
3
      }
2270
3
    }
2271
3
  }
2272
  // We currently always true so we stop in case anything goes wrong when
2273
  // trying to call the script function
2274
0
  return true;
2275
3
}
2276
2277
size_t ScriptInterpreterPythonImpl::CalculateNumChildren(
2278
110
    const StructuredData::ObjectSP &implementor_sp, uint32_t max) {
2279
110
  if (!implementor_sp)
2280
0
    return 0;
2281
110
  StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2282
110
  if (!generic)
2283
0
    return 0;
2284
110
  auto *implementor = static_cast<PyObject *>(generic->GetValue());
2285
110
  if (!implementor)
2286
0
    return 0;
2287
2288
110
  size_t ret_val = 0;
2289
2290
110
  {
2291
110
    Locker py_lock(this,
2292
110
                   Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2293
110
    ret_val = LLDBSwigPython_CalculateNumChildren(implementor, max);
2294
110
  }
2295
2296
110
  return ret_val;
2297
110
}
2298
2299
lldb::ValueObjectSP ScriptInterpreterPythonImpl::GetChildAtIndex(
2300
1.39k
    const StructuredData::ObjectSP &implementor_sp, uint32_t idx) {
2301
1.39k
  if (!implementor_sp)
2302
0
    return lldb::ValueObjectSP();
2303
2304
1.39k
  StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2305
1.39k
  if (!generic)
2306
0
    return lldb::ValueObjectSP();
2307
1.39k
  auto *implementor = static_cast<PyObject *>(generic->GetValue());
2308
1.39k
  if (!implementor)
2309
0
    return lldb::ValueObjectSP();
2310
2311
1.39k
  lldb::ValueObjectSP ret_val;
2312
1.39k
  {
2313
1.39k
    Locker py_lock(this,
2314
1.39k
                   Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2315
1.39k
    PyObject *child_ptr = LLDBSwigPython_GetChildAtIndex(implementor, idx);
2316
1.39k
    if (child_ptr != nullptr && child_ptr != Py_None) {
2317
1.39k
      lldb::SBValue *sb_value_ptr =
2318
1.39k
          (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr);
2319
1.39k
      if (sb_value_ptr == nullptr)
2320
0
        Py_XDECREF(child_ptr);
2321
1.39k
      else
2322
1.39k
        ret_val = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr);
2323
1.39k
    } else {
2324
0
      Py_XDECREF(child_ptr);
2325
0
    }
2326
1.39k
  }
2327
2328
1.39k
  return ret_val;
2329
1.39k
}
2330
2331
int ScriptInterpreterPythonImpl::GetIndexOfChildWithName(
2332
9
    const StructuredData::ObjectSP &implementor_sp, const char *child_name) {
2333
9
  if (!implementor_sp)
2334
0
    return UINT32_MAX;
2335
2336
9
  StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2337
9
  if (!generic)
2338
0
    return UINT32_MAX;
2339
9
  auto *implementor = static_cast<PyObject *>(generic->GetValue());
2340
9
  if (!implementor)
2341
0
    return UINT32_MAX;
2342
2343
9
  int ret_val = UINT32_MAX;
2344
2345
9
  {
2346
9
    Locker py_lock(this,
2347
9
                   Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2348
9
    ret_val = LLDBSwigPython_GetIndexOfChildWithName(implementor, child_name);
2349
9
  }
2350
2351
9
  return ret_val;
2352
9
}
2353
2354
bool ScriptInterpreterPythonImpl::UpdateSynthProviderInstance(
2355
138
    const StructuredData::ObjectSP &implementor_sp) {
2356
138
  bool ret_val = false;
2357
2358
138
  if (!implementor_sp)
2359
0
    return ret_val;
2360
2361
138
  StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2362
138
  if (!generic)
2363
0
    return ret_val;
2364
138
  auto *implementor = static_cast<PyObject *>(generic->GetValue());
2365
138
  if (!implementor)
2366
0
    return ret_val;
2367
2368
138
  {
2369
138
    Locker py_lock(this,
2370
138
                   Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2371
138
    ret_val = LLDBSwigPython_UpdateSynthProviderInstance(implementor);
2372
138
  }
2373
2374
138
  return ret_val;
2375
138
}
2376
2377
bool ScriptInterpreterPythonImpl::MightHaveChildrenSynthProviderInstance(
2378
29
    const StructuredData::ObjectSP &implementor_sp) {
2379
29
  bool ret_val = false;
2380
2381
29
  if (!implementor_sp)
2382
0
    return ret_val;
2383
2384
29
  StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2385
29
  if (!generic)
2386
0
    return ret_val;
2387
29
  auto *implementor = static_cast<PyObject *>(generic->GetValue());
2388
29
  if (!implementor)
2389
0
    return ret_val;
2390
2391
29
  {
2392
29
    Locker py_lock(this,
2393
29
                   Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2394
29
    ret_val =
2395
29
        LLDBSwigPython_MightHaveChildrenSynthProviderInstance(implementor);
2396
29
  }
2397
2398
29
  return ret_val;
2399
29
}
2400
2401
lldb::ValueObjectSP ScriptInterpreterPythonImpl::GetSyntheticValue(
2402
138
    const StructuredData::ObjectSP &implementor_sp) {
2403
138
  lldb::ValueObjectSP ret_val(nullptr);
2404
2405
138
  if (!implementor_sp)
2406
0
    return ret_val;
2407
2408
138
  StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2409
138
  if (!generic)
2410
0
    return ret_val;
2411
138
  auto *implementor = static_cast<PyObject *>(generic->GetValue());
2412
138
  if (!implementor)
2413
0
    return ret_val;
2414
2415
138
  {
2416
138
    Locker py_lock(this,
2417
138
                   Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2418
138
    PyObject *child_ptr =
2419
138
        LLDBSwigPython_GetValueSynthProviderInstance(implementor);
2420
138
    if (child_ptr != nullptr && 
child_ptr != 18
Py_None18
) {
2421
18
      lldb::SBValue *sb_value_ptr =
2422
18
          (lldb::SBValue *)LLDBSWIGPython_CastPyObjectToSBValue(child_ptr);
2423
18
      if (sb_value_ptr == nullptr)
2424
0
        Py_XDECREF(child_ptr);
2425
18
      else
2426
18
        ret_val = LLDBSWIGPython_GetValueObjectSPFromSBValue(sb_value_ptr);
2427
120
    } else {
2428
120
      Py_XDECREF(child_ptr);
2429
120
    }
2430
138
  }
2431
2432
138
  return ret_val;
2433
138
}
2434
2435
ConstString ScriptInterpreterPythonImpl::GetSyntheticTypeName(
2436
154
    const StructuredData::ObjectSP &implementor_sp) {
2437
154
  Locker py_lock(this,
2438
154
                 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2439
2440
154
  static char callee_name[] = "get_type_name";
2441
2442
154
  ConstString ret_val;
2443
154
  bool got_string = false;
2444
154
  std::string buffer;
2445
2446
154
  if (!implementor_sp)
2447
0
    return ret_val;
2448
2449
154
  StructuredData::Generic *generic = implementor_sp->GetAsGeneric();
2450
154
  if (!generic)
2451
0
    return ret_val;
2452
154
  PythonObject implementor(PyRefType::Borrowed,
2453
154
                           (PyObject *)generic->GetValue());
2454
154
  if (!implementor.IsAllocated())
2455
0
    return ret_val;
2456
2457
154
  PythonObject pmeth(PyRefType::Owned,
2458
154
                     PyObject_GetAttrString(implementor.get(), callee_name));
2459
2460
154
  if (PyErr_Occurred())
2461
145
    PyErr_Clear();
2462
2463
154
  if (!pmeth.IsAllocated())
2464
145
    return ret_val;
2465
2466
9
  if (PyCallable_Check(pmeth.get()) == 0) {
2467
0
    if (PyErr_Occurred())
2468
0
      PyErr_Clear();
2469
0
    return ret_val;
2470
0
  }
2471
2472
9
  if (PyErr_Occurred())
2473
0
    PyErr_Clear();
2474
2475
  // right now we know this function exists and is callable..
2476
9
  PythonObject py_return(
2477
9
      PyRefType::Owned,
2478
9
      PyObject_CallMethod(implementor.get(), callee_name, nullptr));
2479
2480
  // if it fails, print the error but otherwise go on
2481
9
  if (PyErr_Occurred()) {
2482
0
    PyErr_Print();
2483
0
    PyErr_Clear();
2484
0
  }
2485
2486
9
  if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
2487
9
    PythonString py_string(PyRefType::Borrowed, py_return.get());
2488
9
    llvm::StringRef return_data(py_string.GetString());
2489
9
    if (!return_data.empty()) {
2490
9
      buffer.assign(return_data.data(), return_data.size());
2491
9
      got_string = true;
2492
9
    }
2493
9
  }
2494
2495
9
  if (got_string)
2496
9
    ret_val.SetCStringWithLength(buffer.c_str(), buffer.size());
2497
2498
9
  return ret_val;
2499
9
}
2500
2501
bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2502
    const char *impl_function, Process *process, std::string &output,
2503
0
    Status &error) {
2504
0
  bool ret_val;
2505
0
  if (!process) {
2506
0
    error.SetErrorString("no process");
2507
0
    return false;
2508
0
  }
2509
0
  if (!impl_function || !impl_function[0]) {
2510
0
    error.SetErrorString("no function to execute");
2511
0
    return false;
2512
0
  }
2513
2514
0
  {
2515
0
    Locker py_lock(this,
2516
0
                   Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2517
0
    ret_val = LLDBSWIGPythonRunScriptKeywordProcess(
2518
0
        impl_function, m_dictionary_name.c_str(), process->shared_from_this(),
2519
0
        output);
2520
0
    if (!ret_val)
2521
0
      error.SetErrorString("python script evaluation failed");
2522
0
  }
2523
0
  return ret_val;
2524
0
}
2525
2526
bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2527
    const char *impl_function, Thread *thread, std::string &output,
2528
0
    Status &error) {
2529
0
  if (!thread) {
2530
0
    error.SetErrorString("no thread");
2531
0
    return false;
2532
0
  }
2533
0
  if (!impl_function || !impl_function[0]) {
2534
0
    error.SetErrorString("no function to execute");
2535
0
    return false;
2536
0
  }
2537
2538
0
  Locker py_lock(this,
2539
0
                 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2540
0
  if (llvm::Optional<std::string> result = LLDBSWIGPythonRunScriptKeywordThread(
2541
0
          impl_function, m_dictionary_name.c_str(),
2542
0
          thread->shared_from_this())) {
2543
0
    output = std::move(*result);
2544
0
    return true;
2545
0
  }
2546
0
  error.SetErrorString("python script evaluation failed");
2547
0
  return false;
2548
0
}
2549
2550
bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2551
    const char *impl_function, Target *target, std::string &output,
2552
0
    Status &error) {
2553
0
  bool ret_val;
2554
0
  if (!target) {
2555
0
    error.SetErrorString("no thread");
2556
0
    return false;
2557
0
  }
2558
0
  if (!impl_function || !impl_function[0]) {
2559
0
    error.SetErrorString("no function to execute");
2560
0
    return false;
2561
0
  }
2562
2563
0
  {
2564
0
    TargetSP target_sp(target->shared_from_this());
2565
0
    Locker py_lock(this,
2566
0
                   Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2567
0
    ret_val = LLDBSWIGPythonRunScriptKeywordTarget(
2568
0
        impl_function, m_dictionary_name.c_str(), target_sp, output);
2569
0
    if (!ret_val)
2570
0
      error.SetErrorString("python script evaluation failed");
2571
0
  }
2572
0
  return ret_val;
2573
0
}
2574
2575
bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2576
    const char *impl_function, StackFrame *frame, std::string &output,
2577
0
    Status &error) {
2578
0
  if (!frame) {
2579
0
    error.SetErrorString("no frame");
2580
0
    return false;
2581
0
  }
2582
0
  if (!impl_function || !impl_function[0]) {
2583
0
    error.SetErrorString("no function to execute");
2584
0
    return false;
2585
0
  }
2586
2587
0
  Locker py_lock(this,
2588
0
                 Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2589
0
  if (llvm::Optional<std::string> result = LLDBSWIGPythonRunScriptKeywordFrame(
2590
0
          impl_function, m_dictionary_name.c_str(),
2591
0
          frame->shared_from_this())) {
2592
0
    output = std::move(*result);
2593
0
    return true;
2594
0
  }
2595
0
  error.SetErrorString("python script evaluation failed");
2596
0
  return false;
2597
0
}
2598
2599
bool ScriptInterpreterPythonImpl::RunScriptFormatKeyword(
2600
    const char *impl_function, ValueObject *value, std::string &output,
2601
6
    Status &error) {
2602
6
  bool ret_val;
2603
6
  if (!value) {
2604
0
    error.SetErrorString("no value");
2605
0
    return false;
2606
0
  }
2607
6
  if (!impl_function || !impl_function[0]) {
2608
0
    error.SetErrorString("no function to execute");
2609
0
    return false;
2610
0
  }
2611
2612
6
  {
2613
6
    Locker py_lock(this,
2614
6
                   Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN);
2615
6
    ret_val = LLDBSWIGPythonRunScriptKeywordValue(
2616
6
        impl_function, m_dictionary_name.c_str(), value->GetSP(), output);
2617
6
    if (!ret_val)
2618
0
      error.SetErrorString("python script evaluation failed");
2619
6
  }
2620
6
  return ret_val;
2621
6
}
2622
2623
uint64_t replace_all(std::string &str, const std::string &oldStr,
2624
206
                     const std::string &newStr) {
2625
206
  size_t pos = 0;
2626
206
  uint64_t matches = 0;
2627
206
  while ((pos = str.find(oldStr, pos)) != std::string::npos) {
2628
0
    matches++;
2629
0
    str.replace(pos, oldStr.length(), newStr);
2630
0
    pos += newStr.length();
2631
0
  }
2632
206
  return matches;
2633
206
}
2634
2635
bool ScriptInterpreterPythonImpl::LoadScriptingModule(
2636
    const char *pathname, const LoadScriptOptions &options,
2637
    lldb_private::Status &error, StructuredData::ObjectSP *module_sp,
2638
119
    FileSpec extra_search_dir) {
2639
119
  namespace fs = llvm::sys::fs;
2640
119
  namespace path = llvm::sys::path;
2641
2642
119
  ExecuteScriptOptions exc_options = ExecuteScriptOptions()
2643
119
                                         .SetEnableIO(!options.GetSilent())
2644
119
                                         .SetSetLLDBGlobals(false);
2645
2646
119
  if (!pathname || !pathname[0]) {
2647
0
    error.SetErrorString("invalid pathname");
2648
0
    return false;
2649
0
  }
2650
2651
119
  llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
2652
119
      io_redirect_or_error = ScriptInterpreterIORedirect::Create(
2653
119
          exc_options.GetEnableIO(), m_debugger, /*result=*/nullptr);
2654
2655
119
  if (!io_redirect_or_error) {
2656
0
    error = io_redirect_or_error.takeError();
2657
0
    return false;
2658
0
  }
2659
2660
119
  ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
2661
2662
  // Before executing Python code, lock the GIL.
2663
119
  Locker py_lock(this,
2664
119
                 Locker::AcquireLock |
2665
119
                     (options.GetInitSession() ? 
Locker::InitSession109
:
010
) |
2666
119
                     Locker::NoSTDIN,
2667
119
                 Locker::FreeAcquiredLock |
2668
119
                     (options.GetInitSession() ? 
Locker::TearDownSession109
:
010
),
2669
119
                 io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
2670
119
                 io_redirect.GetErrorFile());
2671
2672
119
  auto ExtendSysPath = [&](std::string directory) -> llvm::Error {
2673
103
    if (directory.empty()) {
2674
0
      return llvm::make_error<llvm::StringError>(
2675
0
          "invalid directory name", llvm::inconvertibleErrorCode());
2676
0
    }
2677
2678
103
    replace_all(directory, "\\", "\\\\");
2679
103
    replace_all(directory, "'", "\\'");
2680
2681
    // Make sure that Python has "directory" in the search path.
2682
103
    StreamString command_stream;
2683
103
    command_stream.Printf("if not (sys.path.__contains__('%s')):\n    "
2684
103
                          "sys.path.insert(1,'%s');\n\n",
2685
103
                          directory.c_str(), directory.c_str());
2686
103
    bool syspath_retval =
2687
103
        ExecuteMultipleLines(command_stream.GetData(), exc_options).Success();
2688
103
    if (!syspath_retval) {
2689
0
      return llvm::make_error<llvm::StringError>(
2690
0
          "Python sys.path handling failed", llvm::inconvertibleErrorCode());
2691
0
    }
2692
2693
103
    return llvm::Error::success();
2694
103
  };
2695
2696
119
  std::string module_name(pathname);
2697
119
  bool possible_package = false;
2698
2699
119
  if (extra_search_dir) {
2700
2
    if (llvm::Error e = ExtendSysPath(extra_search_dir.GetPath())) {
2701
0
      error = std::move(e);
2702
0
      return false;
2703
0
    }
2704
117
  } else {
2705
117
    FileSpec module_file(pathname);
2706
117
    FileSystem::Instance().Resolve(module_file);
2707
117
    FileSystem::Instance().Collect(module_file);
2708
2709
117
    fs::file_status st;
2710
117
    std::error_code ec = status(module_file.GetPath(), st);
2711
2712
117
    if (ec || 
st.type() == fs::file_type::status_error101
||
2713
117
        
st.type() == fs::file_type::type_unknown101
||
2714
117
        
st.type() == fs::file_type::file_not_found101
) {
2715
      // if not a valid file of any sort, check if it might be a filename still
2716
      // dot can't be used but / and \ can, and if either is found, reject
2717
16
      if (strchr(pathname, '\\') || strchr(pathname, '/')) {
2718
2
        error.SetErrorString("invalid pathname");
2719
2
        return false;
2720
2
      }
2721
      // Not a filename, probably a package of some sort, let it go through.
2722
14
      possible_package = true;
2723
101
    } else if (is_directory(st) || 
is_regular_file(st)100
) {
2724
101
      if (module_file.GetDirectory().IsEmpty()) {
2725
0
        error.SetErrorString("invalid directory name");
2726
0
        return false;
2727
0
      }
2728
101
      if (llvm::Error e =
2729
101
              ExtendSysPath(module_file.GetDirectory().GetCString())) {
2730
0
        error = std::move(e);
2731
0
        return false;
2732
0
      }
2733
101
      module_name = module_file.GetFilename().GetCString();
2734
101
    } else {
2735
0
      error.SetErrorString("no known way to import this module specification");
2736
0
      return false;
2737
0
    }
2738
117
  }
2739
2740
  // Strip .py or .pyc extension
2741
117
  llvm::StringRef extension = llvm::sys::path::extension(module_name);
2742
117
  if (!extension.empty()) {
2743
113
    if (extension == ".py")
2744
99
      module_name.resize(module_name.length() - 3);
2745
14
    else if (extension == ".pyc")
2746
0
      module_name.resize(module_name.length() - 4);
2747
113
  }
2748
2749
117
  if (!possible_package && 
module_name.find('.') != llvm::StringRef::npos103
) {
2750
3
    error.SetErrorStringWithFormat(
2751
3
        "Python does not allow dots in module names: %s", module_name.c_str());
2752
3
    return false;
2753
3
  }
2754
2755
114
  if (module_name.find('-') != llvm::StringRef::npos) {
2756
1
    error.SetErrorStringWithFormat(
2757
1
        "Python discourages dashes in module names: %s", module_name.c_str());
2758
1
    return false;
2759
1
  }
2760
2761
  // Check if the module is already imported.
2762
113
  StreamString command_stream;
2763
113
  command_stream.Clear();
2764
113
  command_stream.Printf("sys.modules.__contains__('%s')", module_name.c_str());
2765
113
  bool does_contain = false;
2766
  // This call will succeed if the module was ever imported in any Debugger in
2767
  // the lifetime of the process in which this LLDB framework is living.
2768
113
  const bool does_contain_executed = ExecuteOneLineWithReturn(
2769
113
      command_stream.GetData(),
2770
113
      ScriptInterpreterPythonImpl::eScriptReturnTypeBool, &does_contain, exc_options);
2771
2772
113
  const bool was_imported_globally = does_contain_executed && does_contain;
2773
113
  const bool was_imported_locally =
2774
113
      GetSessionDictionary()
2775
113
          .GetItemForKey(PythonString(module_name))
2776
113
          .IsAllocated();
2777
2778
  // now actually do the import
2779
113
  command_stream.Clear();
2780
2781
113
  if (was_imported_globally || 
was_imported_locally64
) {
2782
49
    if (!was_imported_locally)
2783
44
      command_stream.Printf("import %s ; reload_module(%s)",
2784
44
                            module_name.c_str(), module_name.c_str());
2785
5
    else
2786
5
      command_stream.Printf("reload_module(%s)", module_name.c_str());
2787
49
  } else
2788
64
    command_stream.Printf("import %s", module_name.c_str());
2789
2790
113
  error = ExecuteMultipleLines(command_stream.GetData(), exc_options);
2791
113
  if (error.Fail())
2792
4
    return false;
2793
2794
  // if we are here, everything worked
2795
  // call __lldb_init_module(debugger,dict)
2796
109
  if (!LLDBSwigPythonCallModuleInit(module_name.c_str(),
2797
109
                                    m_dictionary_name.c_str(),
2798
109
                                    m_debugger.shared_from_this())) {
2799
0
    error.SetErrorString("calling __lldb_init_module failed");
2800
0
    return false;
2801
0
  }
2802
2803
109
  if (module_sp) {
2804
    // everything went just great, now set the module object
2805
0
    command_stream.Clear();
2806
0
    command_stream.Printf("%s", module_name.c_str());
2807
0
    void *module_pyobj = nullptr;
2808
0
    if (ExecuteOneLineWithReturn(
2809
0
            command_stream.GetData(),
2810
0
            ScriptInterpreter::eScriptReturnTypeOpaqueObject, &module_pyobj,
2811
0
            exc_options) &&
2812
0
        module_pyobj)
2813
0
      *module_sp = std::make_shared<StructuredPythonObject>(PythonObject(
2814
0
          PyRefType::Owned, static_cast<PyObject *>(module_pyobj)));
2815
0
  }
2816
2817
109
  return true;
2818
109
}
2819
2820
4.98k
bool ScriptInterpreterPythonImpl::IsReservedWord(const char *word) {
2821
4.98k
  if (!word || !word[0])
2822
0
    return false;
2823
2824
4.98k
  llvm::StringRef word_sr(word);
2825
2826
  // filter out a few characters that would just confuse us and that are
2827
  // clearly not keyword material anyway
2828
4.98k
  if (word_sr.find('"') != llvm::StringRef::npos ||
2829
4.98k
      word_sr.find('\'') != llvm::StringRef::npos)
2830
1
    return false;
2831
2832
4.98k
  StreamString command_stream;
2833
4.98k
  command_stream.Printf("keyword.iskeyword('%s')", word);
2834
4.98k
  bool result;
2835
4.98k
  ExecuteScriptOptions options;
2836
4.98k
  options.SetEnableIO(false);
2837
4.98k
  options.SetMaskoutErrors(true);
2838
4.98k
  options.SetSetLLDBGlobals(false);
2839
4.98k
  if (ExecuteOneLineWithReturn(command_stream.GetData(),
2840
4.98k
                               ScriptInterpreter::eScriptReturnTypeBool,
2841
4.98k
                               &result, options))
2842
4.98k
    return result;
2843
0
  return false;
2844
4.98k
}
2845
2846
ScriptInterpreterPythonImpl::SynchronicityHandler::SynchronicityHandler(
2847
    lldb::DebuggerSP debugger_sp, ScriptedCommandSynchronicity synchro)
2848
    : m_debugger_sp(debugger_sp), m_synch_wanted(synchro),
2849
68
      m_old_asynch(debugger_sp->GetAsyncExecution()) {
2850
68
  if (m_synch_wanted == eScriptedCommandSynchronicitySynchronous)
2851
66
    m_debugger_sp->SetAsyncExecution(false);
2852
2
  else if (m_synch_wanted == eScriptedCommandSynchronicityAsynchronous)
2853
1
    m_debugger_sp->SetAsyncExecution(true);
2854
68
}
2855
2856
68
ScriptInterpreterPythonImpl::SynchronicityHandler::~SynchronicityHandler() {
2857
68
  if (m_synch_wanted != eScriptedCommandSynchronicityCurrentValue)
2858
67
    m_debugger_sp->SetAsyncExecution(m_old_asynch);
2859
68
}
2860
2861
bool ScriptInterpreterPythonImpl::RunScriptBasedCommand(
2862
    const char *impl_function, llvm::StringRef args,
2863
    ScriptedCommandSynchronicity synchronicity,
2864
    lldb_private::CommandReturnObject &cmd_retobj, Status &error,
2865
51
    const lldb_private::ExecutionContext &exe_ctx) {
2866
51
  if (!impl_function) {
2867
0
    error.SetErrorString("no function to execute");
2868
0
    return false;
2869
0
  }
2870
2871
51
  lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
2872
51
  lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx));
2873
2874
51
  if (!debugger_sp.get()) {
2875
0
    error.SetErrorString("invalid Debugger pointer");
2876
0
    return false;
2877
0
  }
2878
2879
51
  bool ret_val = false;
2880
2881
51
  std::string err_msg;
2882
2883
51
  {
2884
51
    Locker py_lock(this,
2885
51
                   Locker::AcquireLock | Locker::InitSession |
2886
51
                       (cmd_retobj.GetInteractive() ? 
09
:
Locker::NoSTDIN42
),
2887
51
                   Locker::FreeLock | Locker::TearDownSession);
2888
2889
51
    SynchronicityHandler synch_handler(debugger_sp, synchronicity);
2890
2891
51
    std::string args_str = args.str();
2892
51
    ret_val = LLDBSwigPythonCallCommand(
2893
51
        impl_function, m_dictionary_name.c_str(), debugger_sp, args_str.c_str(),
2894
51
        cmd_retobj, exe_ctx_ref_sp);
2895
51
  }
2896
2897
51
  if (!ret_val)
2898
1
    error.SetErrorString("unable to execute script function");
2899
50
  else
2900
50
    error.Clear();
2901
2902
51
  return ret_val;
2903
51
}
2904
2905
bool ScriptInterpreterPythonImpl::RunScriptBasedCommand(
2906
    StructuredData::GenericSP impl_obj_sp, llvm::StringRef args,
2907
    ScriptedCommandSynchronicity synchronicity,
2908
    lldb_private::CommandReturnObject &cmd_retobj, Status &error,
2909
17
    const lldb_private::ExecutionContext &exe_ctx) {
2910
17
  if (!impl_obj_sp || !impl_obj_sp->IsValid()) {
2911
0
    error.SetErrorString("no function to execute");
2912
0
    return false;
2913
0
  }
2914
2915
17
  lldb::DebuggerSP debugger_sp = m_debugger.shared_from_this();
2916
17
  lldb::ExecutionContextRefSP exe_ctx_ref_sp(new ExecutionContextRef(exe_ctx));
2917
2918
17
  if (!debugger_sp.get()) {
2919
0
    error.SetErrorString("invalid Debugger pointer");
2920
0
    return false;
2921
0
  }
2922
2923
17
  bool ret_val = false;
2924
2925
17
  std::string err_msg;
2926
2927
17
  {
2928
17
    Locker py_lock(this,
2929
17
                   Locker::AcquireLock | Locker::InitSession |
2930
17
                       (cmd_retobj.GetInteractive() ? 
04
:
Locker::NoSTDIN13
),
2931
17
                   Locker::FreeLock | Locker::TearDownSession);
2932
2933
17
    SynchronicityHandler synch_handler(debugger_sp, synchronicity);
2934
2935
17
    std::string args_str = args.str();
2936
17
    ret_val = LLDBSwigPythonCallCommandObject(
2937
17
        static_cast<PyObject *>(impl_obj_sp->GetValue()), debugger_sp,
2938
17
        args_str.c_str(), cmd_retobj, exe_ctx_ref_sp);
2939
17
  }
2940
2941
17
  if (!ret_val)
2942
0
    error.SetErrorString("unable to execute script function");
2943
17
  else
2944
17
    error.Clear();
2945
2946
17
  return ret_val;
2947
17
}
2948
2949
/// In Python, a special attribute __doc__ contains the docstring for an object
2950
/// (function, method, class, ...) if any is defined Otherwise, the attribute's
2951
/// value is None.
2952
bool ScriptInterpreterPythonImpl::GetDocumentationForItem(const char *item,
2953
74
                                                          std::string &dest) {
2954
74
  dest.clear();
2955
2956
74
  if (!item || !*item)
2957
0
    return false;
2958
2959
74
  std::string command(item);
2960
74
  command += ".__doc__";
2961
2962
  // Python is going to point this to valid data if ExecuteOneLineWithReturn
2963
  // returns successfully.
2964
74
  char *result_ptr = nullptr;
2965
2966
74
  if (ExecuteOneLineWithReturn(
2967
74
          command, ScriptInterpreter::eScriptReturnTypeCharStrOrNone,
2968
74
          &result_ptr,
2969
74
          ExecuteScriptOptions().SetEnableIO(false))) {
2970
71
    if (result_ptr)
2971
4
      dest.assign(result_ptr);
2972
71
    return true;
2973
71
  }
2974
2975
3
  StreamString str_stream;
2976
3
  str_stream << "Function " << item
2977
3
             << " was not found. Containing module might be missing.";
2978
3
  dest = std::string(str_stream.GetString());
2979
2980
3
  return false;
2981
74
}
2982
2983
bool ScriptInterpreterPythonImpl::GetShortHelpForCommandObject(
2984
9
    StructuredData::GenericSP cmd_obj_sp, std::string &dest) {
2985
9
  dest.clear();
2986
2987
9
  Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
2988
2989
9
  static char callee_name[] = "get_short_help";
2990
2991
9
  if (!cmd_obj_sp)
2992
0
    return false;
2993
2994
9
  PythonObject implementor(PyRefType::Borrowed,
2995
9
                           (PyObject *)cmd_obj_sp->GetValue());
2996
2997
9
  if (!implementor.IsAllocated())
2998
0
    return false;
2999
3000
9
  PythonObject pmeth(PyRefType::Owned,
3001
9
                     PyObject_GetAttrString(implementor.get(), callee_name));
3002
3003
9
  if (PyErr_Occurred())
3004
4
    PyErr_Clear();
3005
3006
9
  if (!pmeth.IsAllocated())
3007
4
    return false;
3008
3009
5
  if (PyCallable_Check(pmeth.get()) == 0) {
3010
0
    if (PyErr_Occurred())
3011
0
      PyErr_Clear();
3012
0
    return false;
3013
0
  }
3014
3015
5
  if (PyErr_Occurred())
3016
0
    PyErr_Clear();
3017
3018
  // Right now we know this function exists and is callable.
3019
5
  PythonObject py_return(
3020
5
      PyRefType::Owned,
3021
5
      PyObject_CallMethod(implementor.get(), callee_name, nullptr));
3022
3023
  // If it fails, print the error but otherwise go on.
3024
5
  if (PyErr_Occurred()) {
3025
0
    PyErr_Print();
3026
0
    PyErr_Clear();
3027
0
  }
3028
3029
5
  if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
3030
5
    PythonString py_string(PyRefType::Borrowed, py_return.get());
3031
5
    llvm::StringRef return_data(py_string.GetString());
3032
5
    dest.assign(return_data.data(), return_data.size());
3033
5
    return true;
3034
5
  }
3035
3036
0
  return false;
3037
5
}
3038
3039
uint32_t ScriptInterpreterPythonImpl::GetFlagsForCommandObject(
3040
14
    StructuredData::GenericSP cmd_obj_sp) {
3041
14
  uint32_t result = 0;
3042
3043
14
  Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
3044
3045
14
  static char callee_name[] = "get_flags";
3046
3047
14
  if (!cmd_obj_sp)
3048
0
    return result;
3049
3050
14
  PythonObject implementor(PyRefType::Borrowed,
3051
14
                           (PyObject *)cmd_obj_sp->GetValue());
3052
3053
14
  if (!implementor.IsAllocated())
3054
0
    return result;
3055
3056
14
  PythonObject pmeth(PyRefType::Owned,
3057
14
                     PyObject_GetAttrString(implementor.get(), callee_name));
3058
3059
14
  if (PyErr_Occurred())
3060
12
    PyErr_Clear();
3061
3062
14
  if (!pmeth.IsAllocated())
3063
12
    return result;
3064
3065
2
  if (PyCallable_Check(pmeth.get()) == 0) {
3066
0
    if (PyErr_Occurred())
3067
0
      PyErr_Clear();
3068
0
    return result;
3069
0
  }
3070
3071
2
  if (PyErr_Occurred())
3072
0
    PyErr_Clear();
3073
3074
2
  long long py_return = unwrapOrSetPythonException(
3075
2
      As<long long>(implementor.CallMethod(callee_name)));
3076
3077
  // if it fails, print the error but otherwise go on
3078
2
  if (PyErr_Occurred()) {
3079
0
    PyErr_Print();
3080
0
    PyErr_Clear();
3081
2
  } else {
3082
2
    result = py_return;
3083
2
  }
3084
3085
2
  return result;
3086
2
}
3087
3088
bool ScriptInterpreterPythonImpl::GetLongHelpForCommandObject(
3089
3
    StructuredData::GenericSP cmd_obj_sp, std::string &dest) {
3090
3
  bool got_string = false;
3091
3
  dest.clear();
3092
3093
3
  Locker py_lock(this, Locker::AcquireLock | Locker::NoSTDIN, Locker::FreeLock);
3094
3095
3
  static char callee_name[] = "get_long_help";
3096
3097
3
  if (!cmd_obj_sp)
3098
0
    return false;
3099
3100
3
  PythonObject implementor(PyRefType::Borrowed,
3101
3
                           (PyObject *)cmd_obj_sp->GetValue());
3102
3103
3
  if (!implementor.IsAllocated())
3104
0
    return false;
3105
3106
3
  PythonObject pmeth(PyRefType::Owned,
3107
3
                     PyObject_GetAttrString(implementor.get(), callee_name));
3108
3109
3
  if (PyErr_Occurred())
3110
3
    PyErr_Clear();
3111
3112
3
  if (!pmeth.IsAllocated())
3113
3
    return false;
3114
3115
0
  if (PyCallable_Check(pmeth.get()) == 0) {
3116
0
    if (PyErr_Occurred())
3117
0
      PyErr_Clear();
3118
3119
0
    return false;
3120
0
  }
3121
3122
0
  if (PyErr_Occurred())
3123
0
    PyErr_Clear();
3124
3125
  // right now we know this function exists and is callable..
3126
0
  PythonObject py_return(
3127
0
      PyRefType::Owned,
3128
0
      PyObject_CallMethod(implementor.get(), callee_name, nullptr));
3129
3130
  // if it fails, print the error but otherwise go on
3131
0
  if (PyErr_Occurred()) {
3132
0
    PyErr_Print();
3133
0
    PyErr_Clear();
3134
0
  }
3135
3136
0
  if (py_return.IsAllocated() && PythonString::Check(py_return.get())) {
3137
0
    PythonString str(PyRefType::Borrowed, py_return.get());
3138
0
    llvm::StringRef str_data(str.GetString());
3139
0
    dest.assign(str_data.data(), str_data.size());
3140
0
    got_string = true;
3141
0
  }
3142
3143
0
  return got_string;
3144
0
}
3145
3146
std::unique_ptr<ScriptInterpreterLocker>
3147
25
ScriptInterpreterPythonImpl::AcquireInterpreterLock() {
3148
25
  std::unique_ptr<ScriptInterpreterLocker> py_lock(new Locker(
3149
25
      this, Locker::AcquireLock | Locker::InitSession | Locker::NoSTDIN,
3150
25
      Locker::FreeLock | Locker::TearDownSession));
3151
25
  return py_lock;
3152
25
}
3153
3154
#if LLDB_USE_PYTHON_SET_INTERRUPT
3155
namespace {
3156
/// Saves the current signal handler for the specified signal and restores
3157
/// it at the end of the current scope.
3158
struct RestoreSignalHandlerScope {
3159
  /// The signal handler.
3160
  struct sigaction m_prev_handler;
3161
  int m_signal_code;
3162
903
  RestoreSignalHandlerScope(int signal_code) : m_signal_code(signal_code) {
3163
    // Initialize sigaction to their default state.
3164
903
    std::memset(&m_prev_handler, 0, sizeof(m_prev_handler));
3165
    // Don't install a new handler, just read back the old one.
3166
903
    struct sigaction *new_handler = nullptr;
3167
903
    int signal_err = ::sigaction(m_signal_code, new_handler, &m_prev_handler);
3168
903
    lldbassert(signal_err == 0 && "sigaction failed to read handler");
3169
903
  }
3170
903
  ~RestoreSignalHandlerScope() {
3171
903
    int signal_err = ::sigaction(m_signal_code, &m_prev_handler, nullptr);
3172
903
    lldbassert(signal_err == 0 && "sigaction failed to restore old handler");
3173
903
  }
3174
};
3175
} // namespace
3176
#endif
3177
3178
1.47k
void ScriptInterpreterPythonImpl::InitializePrivate() {
3179
1.47k
  if (g_initialized)
3180
568
    return;
3181
3182
903
  g_initialized = true;
3183
3184
903
  LLDB_SCOPED_TIMER();
3185
3186
  // RAII-based initialization which correctly handles multiple-initialization,
3187
  // version- specific differences among Python 2 and Python 3, and saving and
3188
  // restoring various other pieces of state that can get mucked with during
3189
  // initialization.
3190
903
  InitializePythonRAII initialize_guard;
3191
3192
903
  LLDBSwigPyInit();
3193
3194
  // Update the path python uses to search for modules to include the current
3195
  // directory.
3196
3197
903
  PyRun_SimpleString("import sys");
3198
903
  AddToSysPath(AddLocation::End, ".");
3199
3200
  // Don't denormalize paths when calling file_spec.GetPath().  On platforms
3201
  // that use a backslash as the path separator, this will result in executing
3202
  // python code containing paths with unescaped backslashes.  But Python also
3203
  // accepts forward slashes, so to make life easier we just use that.
3204
903
  if (FileSpec file_spec = GetPythonDir())
3205
903
    AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false));
3206
903
  if (FileSpec file_spec = HostInfo::GetShlibDir())
3207
903
    AddToSysPath(AddLocation::Beginning, file_spec.GetPath(false));
3208
3209
903
  PyRun_SimpleString("sys.dont_write_bytecode = 1; import "
3210
903
                     "lldb.embedded_interpreter; from "
3211
903
                     "lldb.embedded_interpreter import run_python_interpreter; "
3212
903
                     "from lldb.embedded_interpreter import run_one_line");
3213
3214
903
#if LLDB_USE_PYTHON_SET_INTERRUPT
3215
  // Python will not just overwrite its internal SIGINT handler but also the
3216
  // one from the process. Backup the current SIGINT handler to prevent that
3217
  // Python deletes it.
3218
903
  RestoreSignalHandlerScope save_sigint(SIGINT);
3219
3220
  // Setup a default SIGINT signal handler that works the same way as the
3221
  // normal Python REPL signal handler which raises a KeyboardInterrupt.
3222
  // Also make sure to not pollute the user's REPL with the signal module nor
3223
  // our utility function.
3224
903
  PyRun_SimpleString("def lldb_setup_sigint_handler():\n"
3225
903
                     "  import signal;\n"
3226
903
                     "  def signal_handler(sig, frame):\n"
3227
903
                     "    raise KeyboardInterrupt()\n"
3228
903
                     "  signal.signal(signal.SIGINT, signal_handler);\n"
3229
903
                     "lldb_setup_sigint_handler();\n"
3230
903
                     "del lldb_setup_sigint_handler\n");
3231
903
#endif
3232
903
}
3233
3234
void ScriptInterpreterPythonImpl::AddToSysPath(AddLocation location,
3235
2.70k
                                               std::string path) {
3236
2.70k
  std::string path_copy;
3237
3238
2.70k
  std::string statement;
3239
2.70k
  if (location == AddLocation::Beginning) {
3240
1.80k
    statement.assign("sys.path.insert(0,\"");
3241
1.80k
    statement.append(path);
3242
1.80k
    statement.append("\")");
3243
1.80k
  } else {
3244
903
    statement.assign("sys.path.append(\"");
3245
903
    statement.append(path);
3246
903
    statement.append("\")");
3247
903
  }
3248
2.70k
  PyRun_SimpleString(statement.c_str());
3249
2.70k
}
3250
3251
// We are intentionally NOT calling Py_Finalize here (this would be the logical
3252
// place to call it).  Calling Py_Finalize here causes test suite runs to seg
3253
// fault:  The test suite runs in Python.  It registers SBDebugger::Terminate to
3254
// be called 'at_exit'.  When the test suite Python harness finishes up, it
3255
// calls Py_Finalize, which calls all the 'at_exit' registered functions.
3256
// SBDebugger::Terminate calls Debugger::Terminate, which calls lldb::Terminate,
3257
// which calls ScriptInterpreter::Terminate, which calls
3258
// ScriptInterpreterPythonImpl::Terminate.  So if we call Py_Finalize here, we
3259
// end up with Py_Finalize being called from within Py_Finalize, which results
3260
// in a seg fault. Since this function only gets called when lldb is shutting
3261
// down and going away anyway, the fact that we don't actually call Py_Finalize
3262
// should not cause any problems (everything should shut down/go away anyway
3263
// when the process exits).
3264
//
3265
// void ScriptInterpreterPythonImpl::Terminate() { Py_Finalize (); }
3266
3267
#endif