forked from swiftlang/llvm-project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathScriptInterpreterPython.cpp
3260 lines (2733 loc) · 110 KB
/
ScriptInterpreterPython.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===-- ScriptInterpreterPython.cpp ---------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "lldb/Host/Config.h"
#if LLDB_ENABLE_PYTHON
// LLDB Python header must be included first
#include "lldb-python.h"
#include "Interfaces/ScriptInterpreterPythonInterfaces.h"
#include "PythonDataObjects.h"
#include "PythonReadline.h"
#include "SWIGPythonBridge.h"
#include "ScriptInterpreterPythonImpl.h"
#include "lldb/API/SBError.h"
#include "lldb/API/SBExecutionContext.h"
#include "lldb/API/SBFrame.h"
#include "lldb/API/SBValue.h"
#include "lldb/Breakpoint/StoppointCallbackContext.h"
#include "lldb/Breakpoint/WatchpointOptions.h"
#include "lldb/Core/Debugger.h"
#include "lldb/Core/PluginManager.h"
#include "lldb/Core/ThreadedCommunication.h"
#include "lldb/DataFormatters/TypeSummary.h"
#include "lldb/Host/FileSystem.h"
#include "lldb/Host/HostInfo.h"
#include "lldb/Host/Pipe.h"
#include "lldb/Host/StreamFile.h"
#include "lldb/Interpreter/CommandInterpreter.h"
#include "lldb/Interpreter/CommandReturnObject.h"
#include "lldb/Target/Thread.h"
#include "lldb/Target/ThreadPlan.h"
#include "lldb/Utility/Instrumentation.h"
#include "lldb/Utility/LLDBLog.h"
#include "lldb/Utility/Timer.h"
#include "lldb/ValueObject/ValueObject.h"
#include "lldb/lldb-enumerations.h"
#include "lldb/lldb-forward.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/FormatAdapters.h"
#include <cstdio>
#include <cstdlib>
#include <memory>
#include <mutex>
#include <optional>
#include <string>
using namespace lldb;
using namespace lldb_private;
using namespace lldb_private::python;
using llvm::Expected;
LLDB_PLUGIN_DEFINE(ScriptInterpreterPython)
// Defined in the SWIG source file
extern "C" PyObject *PyInit__lldb(void);
#define LLDBSwigPyInit PyInit__lldb
#if defined(_WIN32)
// Don't mess with the signal handlers on Windows.
#define LLDB_USE_PYTHON_SET_INTERRUPT 0
#else
// PyErr_SetInterrupt was introduced in 3.2.
#define LLDB_USE_PYTHON_SET_INTERRUPT \
(PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 2) || (PY_MAJOR_VERSION > 3)
#endif
static ScriptInterpreterPythonImpl *GetPythonInterpreter(Debugger &debugger) {
ScriptInterpreter *script_interpreter =
debugger.GetScriptInterpreter(true, lldb::eScriptLanguagePython);
return static_cast<ScriptInterpreterPythonImpl *>(script_interpreter);
}
namespace {
// Initializing Python is not a straightforward process. We cannot control
// what external code may have done before getting to this point in LLDB,
// including potentially having already initialized Python, so we need to do a
// lot of work to ensure that the existing state of the system is maintained
// across our initialization. We do this by using an RAII pattern where we
// save off initial state at the beginning, and restore it at the end
struct InitializePythonRAII {
public:
InitializePythonRAII() {
InitializePythonHome();
// The table of built-in modules can only be extended before Python is
// initialized.
if (!Py_IsInitialized()) {
#ifdef LLDB_USE_LIBEDIT_READLINE_COMPAT_MODULE
// Python's readline is incompatible with libedit being linked into lldb.
// Provide a patched version local to the embedded interpreter.
bool ReadlinePatched = false;
for (auto *p = PyImport_Inittab; p->name != nullptr; p++) {
if (strcmp(p->name, "readline") == 0) {
p->initfunc = initlldb_readline;
break;
}
}
if (!ReadlinePatched) {
PyImport_AppendInittab("readline", initlldb_readline);
ReadlinePatched = true;
}
#endif
// Register _lldb as a built-in module.
PyImport_AppendInittab("_lldb", LLDBSwigPyInit);
}
// Python < 3.2 and Python >= 3.2 reversed the ordering requirements for
// calling `Py_Initialize` and `PyEval_InitThreads`. < 3.2 requires that you
// call `PyEval_InitThreads` first, and >= 3.2 requires that you call it last.
#if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 2) || (PY_MAJOR_VERSION > 3)
Py_InitializeEx(0);
InitializeThreadsPrivate();
#else
InitializeThreadsPrivate();
Py_InitializeEx(0);
#endif
}
~InitializePythonRAII() {
if (m_was_already_initialized) {
Log *log = GetLog(LLDBLog::Script);
LLDB_LOGV(log, "Releasing PyGILState. Returning to state = {0}locked",
m_gil_state == PyGILState_UNLOCKED ? "un" : "");
PyGILState_Release(m_gil_state);
} else {
// We initialized the threads in this function, just unlock the GIL.
PyEval_SaveThread();
}
}
private:
void InitializePythonHome() {
#if LLDB_EMBED_PYTHON_HOME
typedef wchar_t *str_type;
static str_type g_python_home = []() -> str_type {
const char *lldb_python_home = LLDB_PYTHON_HOME;
const char *absolute_python_home = nullptr;
llvm::SmallString<64> path;
if (llvm::sys::path::is_absolute(lldb_python_home)) {
absolute_python_home = lldb_python_home;
} else {
FileSpec spec = HostInfo::GetShlibDir();
if (!spec)
return nullptr;
spec.GetPath(path);
llvm::sys::path::append(path, lldb_python_home);
absolute_python_home = path.c_str();
}
size_t size = 0;
return Py_DecodeLocale(absolute_python_home, &size);
}();
if (g_python_home != nullptr) {
Py_SetPythonHome(g_python_home);
}
#endif
}
void InitializeThreadsPrivate() {
// Since Python 3.7 `Py_Initialize` calls `PyEval_InitThreads` inside itself,
// so there is no way to determine whether the embedded interpreter
// was already initialized by some external code. `PyEval_ThreadsInitialized`
// would always return `true` and `PyGILState_Ensure/Release` flow would be
// executed instead of unlocking GIL with `PyEval_SaveThread`. When
// an another thread calls `PyGILState_Ensure` it would get stuck in deadlock.
#if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION >= 7) || (PY_MAJOR_VERSION > 3)
// The only case we should go further and acquire the GIL: it is unlocked.
if (PyGILState_Check())
return;
#endif
// `PyEval_ThreadsInitialized` was deprecated in Python 3.9 and removed in
// Python 3.13. It has been returning `true` always since Python 3.7.
#if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION < 9) || (PY_MAJOR_VERSION < 3)
if (PyEval_ThreadsInitialized()) {
#else
if (true) {
#endif
Log *log = GetLog(LLDBLog::Script);
m_was_already_initialized = true;
m_gil_state = PyGILState_Ensure();
LLDB_LOGV(log, "Ensured PyGILState. Previous state = {0}locked\n",
m_gil_state == PyGILState_UNLOCKED ? "un" : "");
// `PyEval_InitThreads` was deprecated in Python 3.9 and removed in
// Python 3.13.
#if (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION < 9) || (PY_MAJOR_VERSION < 3)
return;
}
// InitThreads acquires the GIL if it hasn't been called before.
PyEval_InitThreads();
#else
}
#endif
}
PyGILState_STATE m_gil_state = PyGILState_UNLOCKED;
bool m_was_already_initialized = false;
};
#if LLDB_USE_PYTHON_SET_INTERRUPT
/// Saves the current signal handler for the specified signal and restores
/// it at the end of the current scope.
struct RestoreSignalHandlerScope {
/// The signal handler.
struct sigaction m_prev_handler;
int m_signal_code;
RestoreSignalHandlerScope(int signal_code) : m_signal_code(signal_code) {
// Initialize sigaction to their default state.
std::memset(&m_prev_handler, 0, sizeof(m_prev_handler));
// Don't install a new handler, just read back the old one.
struct sigaction *new_handler = nullptr;
int signal_err = ::sigaction(m_signal_code, new_handler, &m_prev_handler);
lldbassert(signal_err == 0 && "sigaction failed to read handler");
}
~RestoreSignalHandlerScope() {
int signal_err = ::sigaction(m_signal_code, &m_prev_handler, nullptr);
lldbassert(signal_err == 0 && "sigaction failed to restore old handler");
}
};
#endif
} // namespace
void ScriptInterpreterPython::ComputePythonDirForApple(
llvm::SmallVectorImpl<char> &path) {
auto style = llvm::sys::path::Style::posix;
llvm::StringRef path_ref(path.begin(), path.size());
auto rbegin = llvm::sys::path::rbegin(path_ref, style);
auto rend = llvm::sys::path::rend(path_ref);
auto framework = std::find(rbegin, rend, "LLDB.framework");
if (framework == rend) {
ComputePythonDir(path);
return;
}
path.resize(framework - rend);
llvm::sys::path::append(path, style, "LLDB.framework", "Resources", "Python");
}
void ScriptInterpreterPython::ComputePythonDir(
llvm::SmallVectorImpl<char> &path) {
// Build the path by backing out of the lib dir, then building with whatever
// the real python interpreter uses. (e.g. lib for most, lib64 on RHEL
// x86_64, or bin on Windows).
llvm::sys::path::remove_filename(path);
llvm::sys::path::append(path, LLDB_PYTHON_RELATIVE_LIBDIR);
#if defined(_WIN32)
// This will be injected directly through FileSpec.SetDirectory(),
// so we need to normalize manually.
std::replace(path.begin(), path.end(), '\\', '/');
#endif
}
FileSpec ScriptInterpreterPython::GetPythonDir() {
static FileSpec g_spec = []() {
FileSpec spec = HostInfo::GetShlibDir();
if (!spec)
return FileSpec();
llvm::SmallString<64> path;
spec.GetPath(path);
#if defined(__APPLE__)
ComputePythonDirForApple(path);
#else
ComputePythonDir(path);
#endif
spec.SetDirectory(path);
return spec;
}();
return g_spec;
}
static const char GetInterpreterInfoScript[] = R"(
import os
import sys
def main(lldb_python_dir, python_exe_relative_path):
info = {
"lldb-pythonpath": lldb_python_dir,
"language": "python",
"prefix": sys.prefix,
"executable": os.path.join(sys.prefix, python_exe_relative_path)
}
return info
)";
static const char python_exe_relative_path[] = LLDB_PYTHON_EXE_RELATIVE_PATH;
StructuredData::DictionarySP ScriptInterpreterPython::GetInterpreterInfo() {
GIL gil;
FileSpec python_dir_spec = GetPythonDir();
if (!python_dir_spec)
return nullptr;
PythonScript get_info(GetInterpreterInfoScript);
auto info_json = unwrapIgnoringErrors(
As<PythonDictionary>(get_info(PythonString(python_dir_spec.GetPath()),
PythonString(python_exe_relative_path))));
if (!info_json)
return nullptr;
return info_json.CreateStructuredDictionary();
}
void ScriptInterpreterPython::SharedLibraryDirectoryHelper(
FileSpec &this_file) {
// When we're loaded from python, this_file will point to the file inside the
// python package directory. Replace it with the one in the lib directory.
#ifdef _WIN32
// On windows, we need to manually back out of the python tree, and go into
// the bin directory. This is pretty much the inverse of what ComputePythonDir
// does.
if (this_file.GetFileNameExtension() == ".pyd") {
this_file.RemoveLastPathComponent(); // _lldb.pyd or _lldb_d.pyd
this_file.RemoveLastPathComponent(); // lldb
llvm::StringRef libdir = LLDB_PYTHON_RELATIVE_LIBDIR;
for (auto it = llvm::sys::path::begin(libdir),
end = llvm::sys::path::end(libdir);
it != end; ++it)
this_file.RemoveLastPathComponent();
this_file.AppendPathComponent("bin");
this_file.AppendPathComponent("liblldb.dll");
}
#else
// The python file is a symlink, so we can find the real library by resolving
// it. We can do this unconditionally.
FileSystem::Instance().ResolveSymbolicLink(this_file, this_file);
#endif
}
llvm::StringRef ScriptInterpreterPython::GetPluginDescriptionStatic() {
return "Embedded Python interpreter";
}
void ScriptInterpreterPython::Initialize() {
static llvm::once_flag g_once_flag;
llvm::call_once(g_once_flag, []() {
PluginManager::RegisterPlugin(GetPluginNameStatic(),
GetPluginDescriptionStatic(),
lldb::eScriptLanguagePython,
ScriptInterpreterPythonImpl::CreateInstance);
ScriptInterpreterPythonImpl::Initialize();
});
}
void ScriptInterpreterPython::Terminate() {}
ScriptInterpreterPythonImpl::Locker::Locker(
ScriptInterpreterPythonImpl *py_interpreter, uint16_t on_entry,
uint16_t on_leave, FileSP in, FileSP out, FileSP err)
: ScriptInterpreterLocker(),
m_teardown_session((on_leave & TearDownSession) == TearDownSession),
m_python_interpreter(py_interpreter) {
DoAcquireLock();
if ((on_entry & InitSession) == InitSession) {
if (!DoInitSession(on_entry, in, out, err)) {
// Don't teardown the session if we didn't init it.
m_teardown_session = false;
}
}
}
bool ScriptInterpreterPythonImpl::Locker::DoAcquireLock() {
Log *log = GetLog(LLDBLog::Script);
m_GILState = PyGILState_Ensure();
LLDB_LOGV(log, "Ensured PyGILState. Previous state = {0}locked",
m_GILState == PyGILState_UNLOCKED ? "un" : "");
// we need to save the thread state when we first start the command because
// we might decide to interrupt it while some action is taking place outside
// of Python (e.g. printing to screen, waiting for the network, ...) in that
// case, _PyThreadState_Current will be NULL - and we would be unable to set
// the asynchronous exception - not a desirable situation
m_python_interpreter->SetThreadState(PyThreadState_Get());
m_python_interpreter->IncrementLockCount();
return true;
}
bool ScriptInterpreterPythonImpl::Locker::DoInitSession(uint16_t on_entry_flags,
FileSP in, FileSP out,
FileSP err) {
if (!m_python_interpreter)
return false;
return m_python_interpreter->EnterSession(on_entry_flags, in, out, err);
}
bool ScriptInterpreterPythonImpl::Locker::DoFreeLock() {
Log *log = GetLog(LLDBLog::Script);
LLDB_LOGV(log, "Releasing PyGILState. Returning to state = {0}locked",
m_GILState == PyGILState_UNLOCKED ? "un" : "");
PyGILState_Release(m_GILState);
m_python_interpreter->DecrementLockCount();
return true;
}
bool ScriptInterpreterPythonImpl::Locker::DoTearDownSession() {
if (!m_python_interpreter)
return false;
m_python_interpreter->LeaveSession();
return true;
}
ScriptInterpreterPythonImpl::Locker::~Locker() {
if (m_teardown_session)
DoTearDownSession();
DoFreeLock();
}
ScriptInterpreterPythonImpl::ScriptInterpreterPythonImpl(Debugger &debugger)
: ScriptInterpreterPython(debugger), m_saved_stdin(), m_saved_stdout(),
m_saved_stderr(), m_main_module(),
m_session_dict(PyInitialValue::Invalid),
m_sys_module_dict(PyInitialValue::Invalid), m_run_one_line_function(),
m_run_one_line_str_global(),
m_dictionary_name(m_debugger.GetInstanceName()),
m_active_io_handler(eIOHandlerNone), m_session_is_active(false),
m_pty_secondary_is_open(false), m_valid_session(true), m_lock_count(0),
m_command_thread_state(nullptr) {
m_dictionary_name.append("_dict");
StreamString run_string;
run_string.Printf("%s = dict()", m_dictionary_name.c_str());
Locker locker(this, Locker::AcquireLock, Locker::FreeAcquiredLock);
PyRun_SimpleString(run_string.GetData());
run_string.Clear();
run_string.Printf(
"run_one_line (%s, 'import copy, keyword, os, re, sys, uuid, lldb')",
m_dictionary_name.c_str());
PyRun_SimpleString(run_string.GetData());
// Reloading modules requires a different syntax in Python 2 and Python 3.
// This provides a consistent syntax no matter what version of Python.
run_string.Clear();
run_string.Printf("run_one_line (%s, 'from importlib import reload as reload_module')",
m_dictionary_name.c_str());
PyRun_SimpleString(run_string.GetData());
// WARNING: temporary code that loads Cocoa formatters - this should be done
// on a per-platform basis rather than loading the whole set and letting the
// individual formatter classes exploit APIs to check whether they can/cannot
// do their task
run_string.Clear();
run_string.Printf(
"run_one_line (%s, 'import lldb.formatters, lldb.formatters.cpp')",
m_dictionary_name.c_str());
PyRun_SimpleString(run_string.GetData());
run_string.Clear();
run_string.Printf("run_one_line (%s, 'import lldb.embedded_interpreter; from "
"lldb.embedded_interpreter import run_python_interpreter; "
"from lldb.embedded_interpreter import run_one_line')",
m_dictionary_name.c_str());
PyRun_SimpleString(run_string.GetData());
run_string.Clear();
run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64
"')",
m_dictionary_name.c_str(), m_debugger.GetID());
PyRun_SimpleString(run_string.GetData());
}
ScriptInterpreterPythonImpl::~ScriptInterpreterPythonImpl() {
// the session dictionary may hold objects with complex state which means
// that they may need to be torn down with some level of smarts and that, in
// turn, requires a valid thread state force Python to procure itself such a
// thread state, nuke the session dictionary and then release it for others
// to use and proceed with the rest of the shutdown
auto gil_state = PyGILState_Ensure();
m_session_dict.Reset();
PyGILState_Release(gil_state);
}
void ScriptInterpreterPythonImpl::IOHandlerActivated(IOHandler &io_handler,
bool interactive) {
const char *instructions = nullptr;
switch (m_active_io_handler) {
case eIOHandlerNone:
break;
case eIOHandlerBreakpoint:
instructions = R"(Enter your Python command(s). Type 'DONE' to end.
def function (frame, bp_loc, internal_dict):
"""frame: the lldb.SBFrame for the location at which you stopped
bp_loc: an lldb.SBBreakpointLocation for the breakpoint location information
internal_dict: an LLDB support object not to be used"""
)";
break;
case eIOHandlerWatchpoint:
instructions = "Enter your Python command(s). Type 'DONE' to end.\n";
break;
}
if (instructions && interactive) {
if (LockableStreamFileSP stream_sp = io_handler.GetOutputStreamFileSP()) {
LockedStreamFile locked_stream = stream_sp->Lock();
locked_stream.PutCString(instructions);
locked_stream.Flush();
}
}
}
void ScriptInterpreterPythonImpl::IOHandlerInputComplete(IOHandler &io_handler,
std::string &data) {
io_handler.SetIsDone(true);
bool batch_mode = m_debugger.GetCommandInterpreter().GetBatchCommandMode();
switch (m_active_io_handler) {
case eIOHandlerNone:
break;
case eIOHandlerBreakpoint: {
std::vector<std::reference_wrapper<BreakpointOptions>> *bp_options_vec =
(std::vector<std::reference_wrapper<BreakpointOptions>> *)
io_handler.GetUserData();
for (BreakpointOptions &bp_options : *bp_options_vec) {
auto data_up = std::make_unique<CommandDataPython>();
if (!data_up)
break;
data_up->user_source.SplitIntoLines(data);
if (GenerateBreakpointCommandCallbackData(data_up->user_source,
data_up->script_source,
/*has_extra_args=*/false,
/*is_callback=*/false)
.Success()) {
auto baton_sp = std::make_shared<BreakpointOptions::CommandBaton>(
std::move(data_up));
bp_options.SetCallback(
ScriptInterpreterPythonImpl::BreakpointCallbackFunction, baton_sp);
} else if (!batch_mode) {
if (LockableStreamFileSP error_sp = io_handler.GetErrorStreamFileSP()) {
LockedStreamFile locked_stream = error_sp->Lock();
locked_stream.Printf("Warning: No command attached to breakpoint.\n");
}
}
}
m_active_io_handler = eIOHandlerNone;
} break;
case eIOHandlerWatchpoint: {
WatchpointOptions *wp_options =
(WatchpointOptions *)io_handler.GetUserData();
auto data_up = std::make_unique<WatchpointOptions::CommandData>();
data_up->user_source.SplitIntoLines(data);
if (GenerateWatchpointCommandCallbackData(data_up->user_source,
data_up->script_source,
/*is_callback=*/false)) {
auto baton_sp =
std::make_shared<WatchpointOptions::CommandBaton>(std::move(data_up));
wp_options->SetCallback(
ScriptInterpreterPythonImpl::WatchpointCallbackFunction, baton_sp);
} else if (!batch_mode) {
if (LockableStreamFileSP error_sp = io_handler.GetErrorStreamFileSP()) {
LockedStreamFile locked_stream = error_sp->Lock();
locked_stream.Printf("Warning: No command attached to breakpoint.\n");
}
}
m_active_io_handler = eIOHandlerNone;
} break;
}
}
lldb::ScriptInterpreterSP
ScriptInterpreterPythonImpl::CreateInstance(Debugger &debugger) {
return std::make_shared<ScriptInterpreterPythonImpl>(debugger);
}
void ScriptInterpreterPythonImpl::LeaveSession() {
Log *log = GetLog(LLDBLog::Script);
if (log)
log->PutCString("ScriptInterpreterPythonImpl::LeaveSession()");
// Unset the LLDB global variables.
PyRun_SimpleString("lldb.debugger = None; lldb.target = None; lldb.process "
"= None; lldb.thread = None; lldb.frame = None");
// checking that we have a valid thread state - since we use our own
// threading and locking in some (rare) cases during cleanup Python may end
// up believing we have no thread state and PyImport_AddModule will crash if
// that is the case - since that seems to only happen when destroying the
// SBDebugger, we can make do without clearing up stdout and stderr
if (PyThreadState_GetDict()) {
PythonDictionary &sys_module_dict = GetSysModuleDictionary();
if (sys_module_dict.IsValid()) {
if (m_saved_stdin.IsValid()) {
sys_module_dict.SetItemForKey(PythonString("stdin"), m_saved_stdin);
m_saved_stdin.Reset();
}
if (m_saved_stdout.IsValid()) {
sys_module_dict.SetItemForKey(PythonString("stdout"), m_saved_stdout);
m_saved_stdout.Reset();
}
if (m_saved_stderr.IsValid()) {
sys_module_dict.SetItemForKey(PythonString("stderr"), m_saved_stderr);
m_saved_stderr.Reset();
}
}
}
m_session_is_active = false;
}
bool ScriptInterpreterPythonImpl::SetStdHandle(FileSP file_sp,
const char *py_name,
PythonObject &save_file,
const char *mode) {
if (!file_sp || !*file_sp) {
save_file.Reset();
return false;
}
File &file = *file_sp;
// Flush the file before giving it to python to avoid interleaved output.
file.Flush();
PythonDictionary &sys_module_dict = GetSysModuleDictionary();
auto new_file = PythonFile::FromFile(file, mode);
if (!new_file) {
llvm::consumeError(new_file.takeError());
return false;
}
save_file = sys_module_dict.GetItemForKey(PythonString(py_name));
sys_module_dict.SetItemForKey(PythonString(py_name), new_file.get());
return true;
}
bool ScriptInterpreterPythonImpl::EnterSession(uint16_t on_entry_flags,
FileSP in_sp, FileSP out_sp,
FileSP err_sp) {
// If we have already entered the session, without having officially 'left'
// it, then there is no need to 'enter' it again.
Log *log = GetLog(LLDBLog::Script);
if (m_session_is_active) {
LLDB_LOGF(
log,
"ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%" PRIx16
") session is already active, returning without doing anything",
on_entry_flags);
return false;
}
LLDB_LOGF(
log,
"ScriptInterpreterPythonImpl::EnterSession(on_entry_flags=0x%" PRIx16 ")",
on_entry_flags);
m_session_is_active = true;
StreamString run_string;
if (on_entry_flags & Locker::InitGlobals) {
run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64,
m_dictionary_name.c_str(), m_debugger.GetID());
run_string.Printf(
"; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64 ")",
m_debugger.GetID());
run_string.PutCString("; lldb.target = lldb.debugger.GetSelectedTarget()");
run_string.PutCString("; lldb.process = lldb.target.GetProcess()");
run_string.PutCString("; lldb.thread = lldb.process.GetSelectedThread ()");
run_string.PutCString("; lldb.frame = lldb.thread.GetSelectedFrame ()");
run_string.PutCString("')");
} else {
// If we aren't initing the globals, we should still always set the
// debugger (since that is always unique.)
run_string.Printf("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64,
m_dictionary_name.c_str(), m_debugger.GetID());
run_string.Printf(
"; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64 ")",
m_debugger.GetID());
run_string.PutCString("')");
}
PyRun_SimpleString(run_string.GetData());
run_string.Clear();
PythonDictionary &sys_module_dict = GetSysModuleDictionary();
if (sys_module_dict.IsValid()) {
lldb::FileSP top_in_sp;
lldb::LockableStreamFileSP top_out_sp, top_err_sp;
if (!in_sp || !out_sp || !err_sp || !*in_sp || !*out_sp || !*err_sp)
m_debugger.AdoptTopIOHandlerFilesIfInvalid(top_in_sp, top_out_sp,
top_err_sp);
if (on_entry_flags & Locker::NoSTDIN) {
m_saved_stdin.Reset();
} else {
if (!SetStdHandle(in_sp, "stdin", m_saved_stdin, "r")) {
if (top_in_sp)
SetStdHandle(top_in_sp, "stdin", m_saved_stdin, "r");
}
}
if (!SetStdHandle(out_sp, "stdout", m_saved_stdout, "w")) {
if (top_out_sp)
SetStdHandle(top_out_sp->GetUnlockedFileSP(), "stdout", m_saved_stdout,
"w");
}
if (!SetStdHandle(err_sp, "stderr", m_saved_stderr, "w")) {
if (top_err_sp)
SetStdHandle(top_err_sp->GetUnlockedFileSP(), "stderr", m_saved_stderr,
"w");
}
}
if (PyErr_Occurred())
PyErr_Clear();
return true;
}
PythonModule &ScriptInterpreterPythonImpl::GetMainModule() {
if (!m_main_module.IsValid())
m_main_module = unwrapIgnoringErrors(PythonModule::Import("__main__"));
return m_main_module;
}
PythonDictionary &ScriptInterpreterPythonImpl::GetSessionDictionary() {
if (m_session_dict.IsValid())
return m_session_dict;
PythonObject &main_module = GetMainModule();
if (!main_module.IsValid())
return m_session_dict;
PythonDictionary main_dict(PyRefType::Borrowed,
PyModule_GetDict(main_module.get()));
if (!main_dict.IsValid())
return m_session_dict;
m_session_dict = unwrapIgnoringErrors(
As<PythonDictionary>(main_dict.GetItem(m_dictionary_name)));
return m_session_dict;
}
PythonDictionary &ScriptInterpreterPythonImpl::GetSysModuleDictionary() {
if (m_sys_module_dict.IsValid())
return m_sys_module_dict;
PythonModule sys_module = unwrapIgnoringErrors(PythonModule::Import("sys"));
m_sys_module_dict = sys_module.GetDictionary();
return m_sys_module_dict;
}
llvm::Expected<unsigned>
ScriptInterpreterPythonImpl::GetMaxPositionalArgumentsForCallable(
const llvm::StringRef &callable_name) {
if (callable_name.empty()) {
return llvm::createStringError(
llvm::inconvertibleErrorCode(),
"called with empty callable name.");
}
Locker py_lock(this, Locker::AcquireLock |
Locker::InitSession |
Locker::NoSTDIN);
auto dict = PythonModule::MainModule()
.ResolveName<PythonDictionary>(m_dictionary_name);
auto pfunc = PythonObject::ResolveNameWithDictionary<PythonCallable>(
callable_name, dict);
if (!pfunc.IsAllocated()) {
return llvm::createStringError(
llvm::inconvertibleErrorCode(),
"can't find callable: %s", callable_name.str().c_str());
}
llvm::Expected<PythonCallable::ArgInfo> arg_info = pfunc.GetArgInfo();
if (!arg_info)
return arg_info.takeError();
return arg_info.get().max_positional_args;
}
static std::string GenerateUniqueName(const char *base_name_wanted,
uint32_t &functions_counter,
const void *name_token = nullptr) {
StreamString sstr;
if (!base_name_wanted)
return std::string();
if (!name_token)
sstr.Printf("%s_%d", base_name_wanted, functions_counter++);
else
sstr.Printf("%s_%p", base_name_wanted, name_token);
return std::string(sstr.GetString());
}
bool ScriptInterpreterPythonImpl::GetEmbeddedInterpreterModuleObjects() {
if (m_run_one_line_function.IsValid())
return true;
PythonObject module(PyRefType::Borrowed,
PyImport_AddModule("lldb.embedded_interpreter"));
if (!module.IsValid())
return false;
PythonDictionary module_dict(PyRefType::Borrowed,
PyModule_GetDict(module.get()));
if (!module_dict.IsValid())
return false;
m_run_one_line_function =
module_dict.GetItemForKey(PythonString("run_one_line"));
m_run_one_line_str_global =
module_dict.GetItemForKey(PythonString("g_run_one_line_str"));
return m_run_one_line_function.IsValid();
}
bool ScriptInterpreterPythonImpl::ExecuteOneLine(
llvm::StringRef command, CommandReturnObject *result,
const ExecuteScriptOptions &options) {
std::string command_str = command.str();
if (!m_valid_session)
return false;
if (!command.empty()) {
// We want to call run_one_line, passing in the dictionary and the command
// string. We cannot do this through PyRun_SimpleString here because the
// command string may contain escaped characters, and putting it inside
// another string to pass to PyRun_SimpleString messes up the escaping. So
// we use the following more complicated method to pass the command string
// directly down to Python.
llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
io_redirect_or_error = ScriptInterpreterIORedirect::Create(
options.GetEnableIO(), m_debugger, result);
if (!io_redirect_or_error) {
if (result)
result->AppendErrorWithFormatv(
"failed to redirect I/O: {0}\n",
llvm::fmt_consume(io_redirect_or_error.takeError()));
else
llvm::consumeError(io_redirect_or_error.takeError());
return false;
}
ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
bool success = false;
{
// WARNING! It's imperative that this RAII scope be as tight as
// possible. In particular, the scope must end *before* we try to join
// the read thread. The reason for this is that a pre-requisite for
// joining the read thread is that we close the write handle (to break
// the pipe and cause it to wake up and exit). But acquiring the GIL as
// below will redirect Python's stdio to use this same handle. If we
// close the handle while Python is still using it, bad things will
// happen.
Locker locker(
this,
Locker::AcquireLock | Locker::InitSession |
(options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) |
((result && result->GetInteractive()) ? 0 : Locker::NoSTDIN),
Locker::FreeAcquiredLock | Locker::TearDownSession,
io_redirect.GetInputFile(), io_redirect.GetOutputFile(),
io_redirect.GetErrorFile());
// Find the correct script interpreter dictionary in the main module.
PythonDictionary &session_dict = GetSessionDictionary();
if (session_dict.IsValid()) {
if (GetEmbeddedInterpreterModuleObjects()) {
if (PyCallable_Check(m_run_one_line_function.get())) {
PythonObject pargs(
PyRefType::Owned,
Py_BuildValue("(Os)", session_dict.get(), command_str.c_str()));
if (pargs.IsValid()) {
PythonObject return_value(
PyRefType::Owned,
PyObject_CallObject(m_run_one_line_function.get(),
pargs.get()));
if (return_value.IsValid())
success = true;
else if (options.GetMaskoutErrors() && PyErr_Occurred()) {
PyErr_Print();
PyErr_Clear();
}
}
}
}
}
io_redirect.Flush();
}
if (success)
return true;
// The one-liner failed. Append the error message.
if (result) {
result->AppendErrorWithFormat(
"python failed attempting to evaluate '%s'\n", command_str.c_str());
}
return false;
}
if (result)
result->AppendError("empty command passed to python\n");
return false;
}
void ScriptInterpreterPythonImpl::ExecuteInterpreterLoop() {
LLDB_SCOPED_TIMER();
Debugger &debugger = m_debugger;
// At the moment, the only time the debugger does not have an input file
// handle is when this is called directly from Python, in which case it is
// both dangerous and unnecessary (not to mention confusing) to try to embed
// a running interpreter loop inside the already running Python interpreter
// loop, so we won't do it.
if (!debugger.GetInputFile().IsValid())
return;
IOHandlerSP io_handler_sp(new IOHandlerPythonInterpreter(debugger, this));
if (io_handler_sp) {
debugger.RunIOHandlerAsync(io_handler_sp);
}
}
bool ScriptInterpreterPythonImpl::Interrupt() {
#if LLDB_USE_PYTHON_SET_INTERRUPT
// If the interpreter isn't evaluating any Python at the moment then return
// false to signal that this function didn't handle the interrupt and the
// next component should try handling it.
if (!IsExecutingPython())
return false;
// Tell Python that it should pretend to have received a SIGINT.
PyErr_SetInterrupt();
// PyErr_SetInterrupt has no way to return an error so we can only pretend the
// signal got successfully handled and return true.
// Python 3.10 introduces PyErr_SetInterruptEx that could return an error, but
// the error handling is limited to checking the arguments which would be
// just our (hardcoded) input signal code SIGINT, so that's not useful at all.
return true;
#else
Log *log = GetLog(LLDBLog::Script);
if (IsExecutingPython()) {
PyThreadState *state = PyThreadState_GET();
if (!state)
state = GetThreadState();
if (state) {
long tid = state->thread_id;
PyThreadState_Swap(state);
int num_threads = PyThreadState_SetAsyncExc(tid, PyExc_KeyboardInterrupt);
LLDB_LOGF(log,
"ScriptInterpreterPythonImpl::Interrupt() sending "
"PyExc_KeyboardInterrupt (tid = %li, num_threads = %i)...",
tid, num_threads);
return true;
}
}
LLDB_LOGF(log,
"ScriptInterpreterPythonImpl::Interrupt() python code not running, "
"can't interrupt");
return false;
#endif
}
bool ScriptInterpreterPythonImpl::ExecuteOneLineWithReturn(
llvm::StringRef in_string, ScriptInterpreter::ScriptReturnType return_type,
void *ret_value, const ExecuteScriptOptions &options) {
llvm::Expected<std::unique_ptr<ScriptInterpreterIORedirect>>
io_redirect_or_error = ScriptInterpreterIORedirect::Create(
options.GetEnableIO(), m_debugger, /*result=*/nullptr);
if (!io_redirect_or_error) {
llvm::consumeError(io_redirect_or_error.takeError());
return false;
}
ScriptInterpreterIORedirect &io_redirect = **io_redirect_or_error;
Locker locker(this,
Locker::AcquireLock | Locker::InitSession |
(options.GetSetLLDBGlobals() ? Locker::InitGlobals : 0) |
Locker::NoSTDIN,
Locker::FreeAcquiredLock | Locker::TearDownSession,
io_redirect.GetInputFile(), io_redirect.GetOutputFile(),