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