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