blob: 10b9792f009ff19a525238452e60d5dccd74fc33 [file] [log] [blame]
Chris Lattner24943d22010-06-08 16:52:24 +00001//===-- 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
Greg Clayton17f5afe2011-02-05 02:56:16 +000011// the *FIRST* header file included in ScriptInterpreterPython.h, and that
12// must be the *FIRST* header file included here.
Chris Lattner24943d22010-06-08 16:52:24 +000013
14#include "lldb/Interpreter/ScriptInterpreterPython.h"
15
Chris Lattner24943d22010-06-08 16:52:24 +000016#include <stdlib.h>
17#include <stdio.h>
18
19#include <string>
20
Greg Clayton5144f382010-10-07 17:14:24 +000021#include "lldb/API/SBFrame.h"
22#include "lldb/API/SBBreakpointLocation.h"
Greg Clayton63094e02010-06-23 01:19:29 +000023#include "lldb/Breakpoint/StoppointCallbackContext.h"
Chris Lattner24943d22010-06-08 16:52:24 +000024#include "lldb/Core/Debugger.h"
Chris Lattner24943d22010-06-08 16:52:24 +000025#include "lldb/Core/Timer.h"
26#include "lldb/Host/Host.h"
27#include "lldb/Interpreter/CommandInterpreter.h"
28#include "lldb/Interpreter/CommandReturnObject.h"
Greg Clayton5144f382010-10-07 17:14:24 +000029#include "lldb/Target/Thread.h"
Chris Lattner24943d22010-06-08 16:52:24 +000030
Chris Lattner24943d22010-06-08 16:52:24 +000031using namespace lldb;
32using namespace lldb_private;
33
Greg Claytone86cbb92011-03-22 01:14:58 +000034
35static ScriptInterpreter::SWIGInitCallback g_swig_init_callback = NULL;
36static ScriptInterpreter::SWIGBreakpointCallbackFunction g_swig_breakpoint_callback = NULL;
37
Chris Lattner24943d22010-06-08 16:52:24 +000038const char embedded_interpreter_string[] =
39"import readline\n\
40import code\n\
41import sys\n\
42import traceback\n\
43\n\
44class SimpleREPL(code.InteractiveConsole):\n\
45 def __init__(self, prompt, dict):\n\
46 code.InteractiveConsole.__init__(self,dict)\n\
47 self.prompt = prompt\n\
48 self.loop_exit = False\n\
49 self.dict = dict\n\
50\n\
51 def interact(self):\n\
52 try:\n\
53 sys.ps1\n\
54 except AttributeError:\n\
55 sys.ps1 = \">>> \"\n\
56 try:\n\
57 sys.ps2\n\
58 except AttributeError:\n\
59 sys.ps2 = \"... \"\n\
60\n\
61 while not self.loop_exit:\n\
62 try:\n\
63 self.read_py_command()\n\
64 except (SystemExit, EOFError):\n\
65 # EOF while in Python just breaks out to top level.\n\
66 self.write('\\n')\n\
67 self.loop_exit = True\n\
68 break\n\
69 except KeyboardInterrupt:\n\
70 self.write(\"\\nKeyboardInterrupt\\n\")\n\
71 self.resetbuffer()\n\
72 more = 0\n\
73 except:\n\
74 traceback.print_exc()\n\
75\n\
76 def process_input (self, in_str):\n\
77 # Canonicalize the format of the input string\n\
78 temp_str = in_str\n\
79 temp_str.strip(' \t')\n\
80 words = temp_str.split()\n\
81 temp_str = ('').join(words)\n\
82\n\
83 # Check the input string to see if it was the quit\n\
84 # command. If so, intercept it, so that it doesn't\n\
85 # close stdin on us!\n\
Jason Molendaa8a5e562010-06-09 21:56:00 +000086 if (temp_str.lower() == \"quit()\" or temp_str.lower() == \"exit()\"):\n\
Chris Lattner24943d22010-06-08 16:52:24 +000087 self.loop_exit = True\n\
88 in_str = \"raise SystemExit \"\n\
89 return in_str\n\
90\n\
91 def my_raw_input (self, prompt):\n\
92 stream = sys.stdout\n\
93 stream.write (prompt)\n\
94 stream.flush ()\n\
95 try:\n\
96 line = sys.stdin.readline()\n\
97 except KeyboardInterrupt:\n\
98 line = \" \\n\"\n\
99 except (SystemExit, EOFError):\n\
100 line = \"quit()\\n\"\n\
101 if not line:\n\
102 raise EOFError\n\
103 if line[-1] == '\\n':\n\
104 line = line[:-1]\n\
105 return line\n\
106\n\
107 def read_py_command(self):\n\
108 # Read off a complete Python command.\n\
109 more = 0\n\
110 while 1:\n\
111 if more:\n\
112 prompt = sys.ps2\n\
113 else:\n\
114 prompt = sys.ps1\n\
115 line = self.my_raw_input(prompt)\n\
116 # Can be None if sys.stdin was redefined\n\
117 encoding = getattr(sys.stdin, \"encoding\", None)\n\
118 if encoding and not isinstance(line, unicode):\n\
119 line = line.decode(encoding)\n\
120 line = self.process_input (line)\n\
121 more = self.push(line)\n\
122 if not more:\n\
123 break\n\
124\n\
Caroline Tice0aa2e552011-01-14 00:29:16 +0000125 def one_line (self, input):\n\
126 line = self.process_input (input)\n\
127 more = self.push(line)\n\
128 if more:\n\
129 self.write (\"Input not a complete line.\")\n\
130 self.resetbuffer()\n\
131 more = 0\n\
132\n\
Chris Lattner24943d22010-06-08 16:52:24 +0000133def run_python_interpreter (dict):\n\
134 # Pass in the dictionary, for continuity from one session to the next.\n\
135 repl = SimpleREPL('>>> ', dict)\n\
Caroline Tice0aa2e552011-01-14 00:29:16 +0000136 repl.interact()\n\
137\n\
138def run_one_line (dict, input_string):\n\
139 repl = SimpleREPL ('', dict)\n\
140 repl.one_line (input_string)\n";
Chris Lattner24943d22010-06-08 16:52:24 +0000141
142static int
143_check_and_flush (FILE *stream)
144{
145 int prev_fail = ferror (stream);
146 return fflush (stream) || prev_fail ? EOF : 0;
147}
148
Caroline Tice202f6b82011-01-17 21:55:19 +0000149static Predicate<lldb::tid_t> &
150PythonMutexPredicate ()
Caroline Tice0aa2e552011-01-14 00:29:16 +0000151{
Caroline Tice202f6b82011-01-17 21:55:19 +0000152 static lldb_private::Predicate<lldb::tid_t> g_interpreter_is_running (LLDB_INVALID_THREAD_ID);
153 return g_interpreter_is_running;
154}
155
156static bool
157CurrentThreadHasPythonLock ()
158{
159 TimeValue timeout;
160
161 timeout = TimeValue::Now(); // Don't wait any time.
162
163 return PythonMutexPredicate().WaitForValueEqualTo (Host::GetCurrentThreadID(), &timeout, NULL);
164}
165
166static bool
167GetPythonLock (uint32_t seconds_to_wait)
168{
169
170 TimeValue timeout;
171
172 if (seconds_to_wait != UINT32_MAX)
173 {
174 timeout = TimeValue::Now();
175 timeout.OffsetWithSeconds (seconds_to_wait);
176 }
177
178 return PythonMutexPredicate().WaitForValueEqualToAndSetValueTo (LLDB_INVALID_THREAD_ID,
179 Host::GetCurrentThreadID(), &timeout, NULL);
180}
181
182static void
183ReleasePythonLock ()
184{
185 PythonMutexPredicate().SetValue (LLDB_INVALID_THREAD_ID, eBroadcastAlways);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000186}
187
Greg Clayton63094e02010-06-23 01:19:29 +0000188ScriptInterpreterPython::ScriptInterpreterPython (CommandInterpreter &interpreter) :
Greg Clayton238c0a12010-09-18 01:14:36 +0000189 ScriptInterpreter (interpreter, eScriptLanguagePython),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000190 m_embedded_python_pty (),
191 m_embedded_thread_input_reader_sp (),
Greg Clayton58928562011-02-09 01:08:52 +0000192 m_dbg_stdout (interpreter.GetDebugger().GetOutputFile().GetStream()),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000193 m_new_sysout (NULL),
194 m_dictionary_name (interpreter.GetDebugger().GetInstanceName().AsCString()),
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000195 m_terminal_state (),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000196 m_session_is_active (false),
197 m_pty_slave_is_open (false),
198 m_valid_session (true)
Chris Lattner24943d22010-06-08 16:52:24 +0000199{
200
Greg Clayton7c330d62011-01-27 01:01:10 +0000201 static int g_initialized = false;
202
203 if (!g_initialized)
204 {
205 g_initialized = true;
Greg Claytone86cbb92011-03-22 01:14:58 +0000206 ScriptInterpreterPython::InitializePrivate ();
Greg Clayton7c330d62011-01-27 01:01:10 +0000207 }
208
Caroline Tice202f6b82011-01-17 21:55:19 +0000209 bool safe_to_run = false;
210 bool need_to_release_lock = true;
211 int interval = 5; // Number of seconds to try getting the Python lock before timing out.
212
213 // We don't dare exit this function without finishing setting up the script interpreter, so we must wait until
214 // we can get the Python lock.
215
216 if (CurrentThreadHasPythonLock())
217 {
218 safe_to_run = true;
219 need_to_release_lock = false;
220 }
221
222 while (!safe_to_run)
223 {
224 safe_to_run = GetPythonLock (interval);
225 if (!safe_to_run)
226 {
227 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
228 fprintf (tmp_fh,
229 "Python interpreter is locked on another thread; "
230 "please release interpreter in order to continue.\n");
231 interval = interval * 2;
232 }
233 }
234
Caroline Tice0aa2e552011-01-14 00:29:16 +0000235 m_dictionary_name.append("_dict");
236 StreamString run_string;
237 run_string.Printf ("%s = dict()", m_dictionary_name.c_str());
238 PyRun_SimpleString (run_string.GetData());
Caroline Tice5867f6b2010-10-18 18:24:17 +0000239
Caroline Tice0aa2e552011-01-14 00:29:16 +0000240 run_string.Clear();
241 run_string.Printf ("run_one_line (%s, 'import sys')", m_dictionary_name.c_str());
242 PyRun_SimpleString (run_string.GetData());
243
244 // Importing 'lldb' module calls SBDebugger::Initialize, which calls Debugger::Initialize, which increments a
245 // global debugger ref-count; therefore we need to check the ref-count before and after importing lldb, and if the
246 // ref-count increased we need to call Debugger::Terminate here to decrement the ref-count so that when the final
247 // call to Debugger::Terminate is made, the ref-count has the correct value.
248 //
249 // Bonus question: Why doesn't the ref-count always increase? Because sometimes lldb has already been imported, in
250 // which case the code inside it, including the call to SBDebugger::Initialize(), does not get executed.
Caroline Tice5867f6b2010-10-18 18:24:17 +0000251
Caroline Tice0aa2e552011-01-14 00:29:16 +0000252 int old_count = Debugger::TestDebuggerRefCount();
Chris Lattner24943d22010-06-08 16:52:24 +0000253
Caroline Tice0aa2e552011-01-14 00:29:16 +0000254 run_string.Clear();
255 run_string.Printf ("run_one_line (%s, 'import lldb')", m_dictionary_name.c_str());
256 PyRun_SimpleString (run_string.GetData());
Greg Clayton24b48ff2010-10-17 22:03:32 +0000257
Caroline Tice0aa2e552011-01-14 00:29:16 +0000258 int new_count = Debugger::TestDebuggerRefCount();
Chris Lattner24943d22010-06-08 16:52:24 +0000259
Caroline Tice0aa2e552011-01-14 00:29:16 +0000260 if (new_count > old_count)
261 Debugger::Terminate();
Caroline Tice5867f6b2010-10-18 18:24:17 +0000262
Caroline Tice0aa2e552011-01-14 00:29:16 +0000263 run_string.Clear();
264 run_string.Printf ("run_one_line (%s, 'import copy')", m_dictionary_name.c_str());
265 PyRun_SimpleString (run_string.GetData());
266
267 run_string.Clear();
268 run_string.Printf ("run_one_line (%s, 'lldb.debugger_unique_id = %d')", m_dictionary_name.c_str(),
269 interpreter.GetDebugger().GetID());
270 PyRun_SimpleString (run_string.GetData());
271
272 if (m_dbg_stdout != NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000273 {
Caroline Tice0aa2e552011-01-14 00:29:16 +0000274 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
Caroline Tice5867f6b2010-10-18 18:24:17 +0000275 }
Caroline Tice202f6b82011-01-17 21:55:19 +0000276
277 if (need_to_release_lock)
278 ReleasePythonLock();
Chris Lattner24943d22010-06-08 16:52:24 +0000279}
280
281ScriptInterpreterPython::~ScriptInterpreterPython ()
282{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000283 Debugger &debugger = GetCommandInterpreter().GetDebugger();
284
285 if (m_embedded_thread_input_reader_sp.get() != NULL)
286 {
287 m_embedded_thread_input_reader_sp->SetIsDone (true);
288 m_embedded_python_pty.CloseSlaveFileDescriptor();
289 m_pty_slave_is_open = false;
290 const InputReaderSP reader_sp = m_embedded_thread_input_reader_sp;
291 m_embedded_thread_input_reader_sp.reset();
292 debugger.PopInputReader (reader_sp);
293 }
294
295 if (m_new_sysout)
296 {
Caroline Tice202f6b82011-01-17 21:55:19 +0000297 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
298 if (!CurrentThreadHasPythonLock ())
299 {
300 while (!GetPythonLock (1))
301 fprintf (tmp_fh, "Python interpreter locked on another thread; waiting to acquire lock...\n");
302 Py_DECREF (m_new_sysout);
303 ReleasePythonLock ();
304 }
305 else
306 Py_DECREF (m_new_sysout);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000307 }
Chris Lattner24943d22010-06-08 16:52:24 +0000308}
309
Caroline Tice0aa2e552011-01-14 00:29:16 +0000310void
311ScriptInterpreterPython::ResetOutputFileHandle (FILE *fh)
312{
313 if (fh == NULL)
314 return;
315
316 m_dbg_stdout = fh;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000317
Caroline Tice202f6b82011-01-17 21:55:19 +0000318 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
319 if (!CurrentThreadHasPythonLock ())
320 {
321 while (!GetPythonLock (1))
322 fprintf (tmp_fh, "Python interpreter locked on another thread; waiting to acquire lock...\n");
323 EnterSession ();
324 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
325 LeaveSession ();
326 ReleasePythonLock ();
327 }
328 else
329 {
330 EnterSession ();
331 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
332 LeaveSession ();
333 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000334}
335
336void
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000337ScriptInterpreterPython::SaveTerminalState (int fd)
338{
339 // Python mucks with the terminal state of STDIN. If we can possibly avoid
340 // this by setting the file handles up correctly prior to entering the
341 // interpreter we should. For now we save and restore the terminal state
342 // on the input file handle.
343 m_terminal_state.Save (fd, false);
344}
345
346void
347ScriptInterpreterPython::RestoreTerminalState ()
348{
349 // Python mucks with the terminal state of STDIN. If we can possibly avoid
350 // this by setting the file handles up correctly prior to entering the
351 // interpreter we should. For now we save and restore the terminal state
352 // on the input file handle.
353 m_terminal_state.Restore();
354}
355
356
357
358void
Caroline Tice0aa2e552011-01-14 00:29:16 +0000359ScriptInterpreterPython::LeaveSession ()
360{
361 m_session_is_active = false;
362}
363
364void
365ScriptInterpreterPython::EnterSession ()
366{
367 // If we have already entered the session, without having officially 'left' it, then there is no need to
368 // 'enter' it again.
369
370 if (m_session_is_active)
371 return;
372
373 m_session_is_active = true;
374
Caroline Tice202f6b82011-01-17 21:55:19 +0000375 StreamString run_string;
376
377 run_string.Printf ("run_one_line (%s, 'lldb.debugger_unique_id = %d')", m_dictionary_name.c_str(),
378 GetCommandInterpreter().GetDebugger().GetID());
379 PyRun_SimpleString (run_string.GetData());
380
Caroline Tice0aa2e552011-01-14 00:29:16 +0000381
382 PyObject *sysmod = PyImport_AddModule ("sys");
383 PyObject *sysdict = PyModule_GetDict (sysmod);
384
385 if ((m_new_sysout != NULL)
386 && (sysmod != NULL)
387 && (sysdict != NULL))
388 PyDict_SetItemString (sysdict, "stdout", m_new_sysout);
389
390 if (PyErr_Occurred())
391 PyErr_Clear ();
392
Caroline Tice0aa2e552011-01-14 00:29:16 +0000393 if (!m_pty_slave_is_open)
394 {
Caroline Tice202f6b82011-01-17 21:55:19 +0000395 run_string.Clear();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000396 run_string.Printf ("run_one_line (%s, \"new_stdin = open('%s', 'r')\")", m_dictionary_name.c_str(),
397 m_pty_slave_name.c_str());
398 PyRun_SimpleString (run_string.GetData());
399 m_pty_slave_is_open = true;
400
401 run_string.Clear();
402 run_string.Printf ("run_one_line (%s, 'sys.stdin = new_stdin')", m_dictionary_name.c_str());
403 PyRun_SimpleString (run_string.GetData());
404 }
405}
406
407
Johnny Chen60dde642010-07-30 22:33:14 +0000408bool
Greg Clayton238c0a12010-09-18 01:14:36 +0000409ScriptInterpreterPython::ExecuteOneLine (const char *command, CommandReturnObject *result)
Chris Lattner24943d22010-06-08 16:52:24 +0000410{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000411 if (!m_valid_session)
412 return false;
413
Caroline Tice0aa2e552011-01-14 00:29:16 +0000414
Caroline Tice0aa2e552011-01-14 00:29:16 +0000415
Caroline Tice4a461da2011-01-14 21:09:29 +0000416 // We want to call run_one_line, passing in the dictionary and the command string. We cannot do this through
417 // PyRun_SimpleString here because the command string may contain escaped characters, and putting it inside
418 // another string to pass to PyRun_SimpleString messes up the escaping. So we use the following more complicated
419 // method to pass the command string directly down to Python.
420
421
Caroline Tice202f6b82011-01-17 21:55:19 +0000422 bool need_to_release_lock = true;
423
424 if (CurrentThreadHasPythonLock())
425 need_to_release_lock = false;
426 else if (!GetPythonLock (1))
427 {
428 fprintf ((m_dbg_stdout ? m_dbg_stdout : stdout),
429 "Python interpreter is currently locked by another thread; unable to process command.\n");
430 return false;
431 }
432
433 EnterSession ();
Caroline Tice4a461da2011-01-14 21:09:29 +0000434 bool success = false;
435
Greg Clayton63094e02010-06-23 01:19:29 +0000436 if (command)
Chris Lattner24943d22010-06-08 16:52:24 +0000437 {
Caroline Tice4a461da2011-01-14 21:09:29 +0000438 // Find the correct script interpreter dictionary in the main module.
439 PyObject *main_mod = PyImport_AddModule ("__main__");
440 PyObject *script_interpreter_dict = NULL;
441 if (main_mod != NULL)
442 {
443 PyObject *main_dict = PyModule_GetDict (main_mod);
444 if ((main_dict != NULL)
445 && PyDict_Check (main_dict))
446 {
447 // Go through the main dictionary looking for the correct python script interpreter dictionary
448 PyObject *key, *value;
449 Py_ssize_t pos = 0;
450
451 while (PyDict_Next (main_dict, &pos, &key, &value))
452 {
453 // We have stolen references to the key and value objects in the dictionary; we need to increment
454 // them now so that Python's garbage collector doesn't collect them out from under us.
455 Py_INCREF (key);
456 Py_INCREF (value);
457 if (strcmp (PyString_AsString (key), m_dictionary_name.c_str()) == 0)
458 {
459 script_interpreter_dict = value;
460 break;
461 }
462 }
463 }
464
465 if (script_interpreter_dict != NULL)
466 {
467 PyObject *pfunc = NULL;
468 PyObject *pmod = PyImport_AddModule ("embedded_interpreter");
469 if (pmod != NULL)
470 {
471 PyObject *pmod_dict = PyModule_GetDict (pmod);
472 if ((pmod_dict != NULL)
473 && PyDict_Check (pmod_dict))
474 {
475 PyObject *key, *value;
476 Py_ssize_t pos = 0;
477
478 while (PyDict_Next (pmod_dict, &pos, &key, &value))
479 {
480 Py_INCREF (key);
481 Py_INCREF (value);
482 if (strcmp (PyString_AsString (key), "run_one_line") == 0)
483 {
484 pfunc = value;
485 break;
486 }
487 }
488
489 PyObject *string_arg = PyString_FromString (command);
490 if (pfunc && string_arg && PyCallable_Check (pfunc))
491 {
492 PyObject *pargs = PyTuple_New (2);
493 if (pargs != NULL)
494 {
495 PyTuple_SetItem (pargs, 0, script_interpreter_dict);
496 PyTuple_SetItem (pargs, 1, string_arg);
497 PyObject *pvalue = PyObject_CallObject (pfunc, pargs);
498 Py_DECREF (pargs);
499 if (pvalue != NULL)
500 {
501 Py_DECREF (pvalue);
502 success = true;
503 }
504 else if (PyErr_Occurred ())
505 {
506 PyErr_Print();
507 PyErr_Clear();
508 }
509 }
510 }
511 }
512 }
513 Py_INCREF (script_interpreter_dict);
514 }
515 }
Greg Clayton63094e02010-06-23 01:19:29 +0000516
Caroline Tice0aa2e552011-01-14 00:29:16 +0000517 LeaveSession ();
518
Caroline Tice202f6b82011-01-17 21:55:19 +0000519 if (need_to_release_lock)
520 ReleasePythonLock();
521
Caroline Tice4a461da2011-01-14 21:09:29 +0000522 if (success)
Johnny Chen60dde642010-07-30 22:33:14 +0000523 return true;
524
525 // The one-liner failed. Append the error message.
526 if (result)
527 result->AppendErrorWithFormat ("python failed attempting to evaluate '%s'\n", command);
528 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000529 }
Johnny Chen60dde642010-07-30 22:33:14 +0000530
Caroline Tice0aa2e552011-01-14 00:29:16 +0000531 LeaveSession ();
Caroline Tice202f6b82011-01-17 21:55:19 +0000532
533 if (need_to_release_lock)
534 ReleasePythonLock ();
535
Johnny Chen60dde642010-07-30 22:33:14 +0000536 if (result)
537 result->AppendError ("empty command passed to python\n");
538 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000539}
540
541
542
543size_t
544ScriptInterpreterPython::InputReaderCallback
545(
546 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000547 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000548 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000549 const char *bytes,
550 size_t bytes_len
551)
552{
Caroline Tice2ade6112010-11-10 19:18:14 +0000553 lldb::thread_t embedded_interpreter_thread;
554 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
555
Chris Lattner24943d22010-06-08 16:52:24 +0000556 if (baton == NULL)
557 return 0;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000558
559 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
560
561 if (script_interpreter->m_script_lang != eScriptLanguagePython)
562 return 0;
563
Greg Clayton58928562011-02-09 01:08:52 +0000564 File &out_file = reader.GetDebugger().GetOutputFile();
Caroline Tice67637d82010-12-15 19:51:12 +0000565
Chris Lattner24943d22010-06-08 16:52:24 +0000566 switch (notification)
567 {
568 case eInputReaderActivate:
569 {
Greg Clayton58928562011-02-09 01:08:52 +0000570 out_file.Printf ("Python Interactive Interpreter. To exit, type 'quit()', 'exit()' or Ctrl-D.\n");
571
Chris Lattner24943d22010-06-08 16:52:24 +0000572 // Save terminal settings if we can
Greg Clayton58928562011-02-09 01:08:52 +0000573 int input_fd = reader.GetDebugger().GetInputFile().GetDescriptor();
574 if (input_fd == File::kInvalidDescriptor)
Greg Clayton24b48ff2010-10-17 22:03:32 +0000575 input_fd = STDIN_FILENO;
Caroline Ticec95c6d12010-09-14 22:49:06 +0000576
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000577 script_interpreter->SaveTerminalState(input_fd);
Greg Clayton99208582011-02-07 19:04:58 +0000578
Caroline Tice202f6b82011-01-17 21:55:19 +0000579 if (!CurrentThreadHasPythonLock())
580 {
581 while (!GetPythonLock(1))
582 {
Greg Clayton58928562011-02-09 01:08:52 +0000583 out_file.Printf ("Python interpreter locked on another thread; waiting to acquire lock...\n");
Caroline Tice202f6b82011-01-17 21:55:19 +0000584 }
585 script_interpreter->EnterSession ();
586 ReleasePythonLock();
587 }
588 else
589 script_interpreter->EnterSession ();
590
Caroline Tice2ade6112010-11-10 19:18:14 +0000591 char error_str[1024];
592 if (script_interpreter->m_embedded_python_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, error_str,
593 sizeof(error_str)))
594 {
595 if (log)
596 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in opening master pty (fd = %d).",
597 script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor());
598 embedded_interpreter_thread = Host::ThreadCreate ("<lldb.script-interpreter.embedded-python-loop>",
599 ScriptInterpreterPython::RunEmbeddedPythonInterpreter,
600 script_interpreter, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +0000601 if (IS_VALID_LLDB_HOST_THREAD(embedded_interpreter_thread))
Caroline Tice2ade6112010-11-10 19:18:14 +0000602 {
603 if (log)
604 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in creating thread (thread = %d)", embedded_interpreter_thread);
605 Error detach_error;
606 Host::ThreadDetach (embedded_interpreter_thread, &detach_error);
607 }
608 else
609 {
610 if (log)
611 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed in creating thread");
612 reader.SetIsDone (true);
613 }
614 }
615 else
616 {
617 if (log)
618 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed to open master pty ");
619 reader.SetIsDone (true);
620 }
Chris Lattner24943d22010-06-08 16:52:24 +0000621 }
622 break;
623
624 case eInputReaderDeactivate:
Caroline Tice0aa2e552011-01-14 00:29:16 +0000625 script_interpreter->LeaveSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000626 break;
627
628 case eInputReaderReactivate:
Caroline Tice202f6b82011-01-17 21:55:19 +0000629 if (!CurrentThreadHasPythonLock())
630 {
631 while (!GetPythonLock(1))
632 {
633 // Wait until lock is acquired.
634 }
635 script_interpreter->EnterSession ();
636 ReleasePythonLock();
637 }
638 else
639 script_interpreter->EnterSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000640 break;
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000641
642 case eInputReaderInterrupt:
643 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "raise KeyboardInterrupt\n", 24);
644 break;
645
646 case eInputReaderEndOfFile:
647 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()\n", 7);
648 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000649
650 case eInputReaderGotToken:
Caroline Tice2ade6112010-11-10 19:18:14 +0000651 if (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor() != -1)
Chris Lattner24943d22010-06-08 16:52:24 +0000652 {
Caroline Tice2ade6112010-11-10 19:18:14 +0000653 if (log)
654 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %d", bytes,
655 bytes_len);
656 if (bytes && bytes_len)
657 {
658 if ((int) bytes[0] == 4)
659 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()", 6);
660 else
661 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), bytes, bytes_len);
662 }
663 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "\n", 1);
Chris Lattner24943d22010-06-08 16:52:24 +0000664 }
Caroline Tice2ade6112010-11-10 19:18:14 +0000665 else
666 {
667 if (log)
668 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %d, Master File Descriptor is bad.",
669 bytes,
670 bytes_len);
671 reader.SetIsDone (true);
672 }
673
Chris Lattner24943d22010-06-08 16:52:24 +0000674 break;
675
676 case eInputReaderDone:
Caroline Tice0aa2e552011-01-14 00:29:16 +0000677 script_interpreter->LeaveSession ();
678
Chris Lattner24943d22010-06-08 16:52:24 +0000679 // Restore terminal settings if they were validly saved
Caroline Tice2ade6112010-11-10 19:18:14 +0000680 if (log)
681 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Done, closing down input reader.");
Caroline Ticec95c6d12010-09-14 22:49:06 +0000682
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000683 script_interpreter->RestoreTerminalState ();
684
Caroline Tice2ade6112010-11-10 19:18:14 +0000685 script_interpreter->m_embedded_python_pty.CloseMasterFileDescriptor();
Chris Lattner24943d22010-06-08 16:52:24 +0000686 break;
687 }
688
689 return bytes_len;
690}
691
692
693void
Greg Clayton238c0a12010-09-18 01:14:36 +0000694ScriptInterpreterPython::ExecuteInterpreterLoop ()
Chris Lattner24943d22010-06-08 16:52:24 +0000695{
696 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
697
Caroline Tice0aa2e552011-01-14 00:29:16 +0000698 Debugger &debugger = GetCommandInterpreter().GetDebugger();
Caroline Ticec95c6d12010-09-14 22:49:06 +0000699
700 // At the moment, the only time the debugger does not have an input file handle is when this is called
701 // directly from Python, in which case it is both dangerous and unnecessary (not to mention confusing) to
702 // try to embed a running interpreter loop inside the already running Python interpreter loop, so we won't
703 // do it.
704
Greg Clayton58928562011-02-09 01:08:52 +0000705 if (!debugger.GetInputFile().IsValid())
Caroline Ticec95c6d12010-09-14 22:49:06 +0000706 return;
707
Greg Clayton63094e02010-06-23 01:19:29 +0000708 InputReaderSP reader_sp (new InputReader(debugger));
Chris Lattner24943d22010-06-08 16:52:24 +0000709 if (reader_sp)
710 {
711 Error error (reader_sp->Initialize (ScriptInterpreterPython::InputReaderCallback,
712 this, // baton
713 eInputReaderGranularityLine, // token size, to pass to callback function
714 NULL, // end token
715 NULL, // prompt
716 true)); // echo input
717
718 if (error.Success())
719 {
Greg Clayton63094e02010-06-23 01:19:29 +0000720 debugger.PushInputReader (reader_sp);
Caroline Tice2ade6112010-11-10 19:18:14 +0000721 m_embedded_thread_input_reader_sp = reader_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000722 }
723 }
724}
725
726bool
727ScriptInterpreterPython::ExecuteOneLineWithReturn (const char *in_string,
728 ScriptInterpreter::ReturnType return_type,
729 void *ret_value)
730{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000731
Caroline Tice202f6b82011-01-17 21:55:19 +0000732 bool need_to_release_lock = true;
733
734 if (CurrentThreadHasPythonLock())
735 need_to_release_lock = false;
736 else if (!GetPythonLock (1))
737 {
738 fprintf ((m_dbg_stdout ? m_dbg_stdout : stdout),
739 "Python interpreter is currently locked by another thread; unable to process command.\n");
740 return false;
741 }
742
743 EnterSession ();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000744
Chris Lattner24943d22010-06-08 16:52:24 +0000745 PyObject *py_return = NULL;
746 PyObject *mainmod = PyImport_AddModule ("__main__");
747 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000748 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000749 PyObject *py_error = NULL;
750 bool ret_success;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000751 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000752 int success;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000753
754 if (PyDict_Check (globals))
755 {
756 PyObject *key, *value;
757 Py_ssize_t pos = 0;
758
759 int i = 0;
760 while (PyDict_Next (globals, &pos, &key, &value))
761 {
762 // We have stolen references to the key and value objects in the dictionary; we need to increment them now
763 // so that Python's garbage collector doesn't collect them out from under us.
764 Py_INCREF (key);
765 Py_INCREF (value);
766 char *c_str = PyString_AsString (key);
767 if (strcmp (c_str, m_dictionary_name.c_str()) == 0)
768 locals = value;
769 ++i;
770 }
771 }
Chris Lattner24943d22010-06-08 16:52:24 +0000772
Caroline Tice0aa2e552011-01-14 00:29:16 +0000773 if (locals == NULL)
774 {
775 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
776 should_decrement_locals = true;
777 }
778
779 if (locals == NULL)
780 {
781 locals = globals;
782 should_decrement_locals = false;
783 }
784
785 py_error = PyErr_Occurred();
786 if (py_error != NULL)
787 PyErr_Clear();
788
Chris Lattner24943d22010-06-08 16:52:24 +0000789 if (in_string != NULL)
790 {
791 py_return = PyRun_String (in_string, Py_eval_input, globals, locals);
792 if (py_return == NULL)
793 {
794 py_error = PyErr_Occurred ();
795 if (py_error != NULL)
796 PyErr_Clear ();
797
798 py_return = PyRun_String (in_string, Py_single_input, globals, locals);
799 }
800
Caroline Tice0aa2e552011-01-14 00:29:16 +0000801 if (locals != NULL
802 && should_decrement_locals)
803 Py_DECREF (locals);
804
Chris Lattner24943d22010-06-08 16:52:24 +0000805 if (py_return != NULL)
806 {
807 switch (return_type)
808 {
809 case eCharPtr: // "char *"
810 {
811 const char format[3] = "s#";
812 success = PyArg_Parse (py_return, format, (char **) &ret_value);
813 break;
814 }
815 case eBool:
816 {
817 const char format[2] = "b";
818 success = PyArg_Parse (py_return, format, (bool *) ret_value);
819 break;
820 }
821 case eShortInt:
822 {
823 const char format[2] = "h";
824 success = PyArg_Parse (py_return, format, (short *) ret_value);
825 break;
826 }
827 case eShortIntUnsigned:
828 {
829 const char format[2] = "H";
830 success = PyArg_Parse (py_return, format, (unsigned short *) ret_value);
831 break;
832 }
833 case eInt:
834 {
835 const char format[2] = "i";
836 success = PyArg_Parse (py_return, format, (int *) ret_value);
837 break;
838 }
839 case eIntUnsigned:
840 {
841 const char format[2] = "I";
842 success = PyArg_Parse (py_return, format, (unsigned int *) ret_value);
843 break;
844 }
845 case eLongInt:
846 {
847 const char format[2] = "l";
848 success = PyArg_Parse (py_return, format, (long *) ret_value);
849 break;
850 }
851 case eLongIntUnsigned:
852 {
853 const char format[2] = "k";
854 success = PyArg_Parse (py_return, format, (unsigned long *) ret_value);
855 break;
856 }
857 case eLongLong:
858 {
859 const char format[2] = "L";
860 success = PyArg_Parse (py_return, format, (long long *) ret_value);
861 break;
862 }
863 case eLongLongUnsigned:
864 {
865 const char format[2] = "K";
866 success = PyArg_Parse (py_return, format, (unsigned long long *) ret_value);
867 break;
868 }
869 case eFloat:
870 {
871 const char format[2] = "f";
872 success = PyArg_Parse (py_return, format, (float *) ret_value);
873 break;
874 }
875 case eDouble:
876 {
877 const char format[2] = "d";
878 success = PyArg_Parse (py_return, format, (double *) ret_value);
879 break;
880 }
881 case eChar:
882 {
883 const char format[2] = "c";
884 success = PyArg_Parse (py_return, format, (char *) ret_value);
885 break;
886 }
887 default:
888 {}
889 }
890 Py_DECREF (py_return);
891 if (success)
892 ret_success = true;
893 else
894 ret_success = false;
895 }
896 }
897
898 py_error = PyErr_Occurred();
899 if (py_error != NULL)
900 {
901 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
902 PyErr_Print ();
903 PyErr_Clear();
904 ret_success = false;
905 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000906
907 LeaveSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000908
Caroline Tice202f6b82011-01-17 21:55:19 +0000909 if (need_to_release_lock)
910 ReleasePythonLock();
911
Chris Lattner24943d22010-06-08 16:52:24 +0000912 return ret_success;
913}
914
915bool
916ScriptInterpreterPython::ExecuteMultipleLines (const char *in_string)
917{
Caroline Tice202f6b82011-01-17 21:55:19 +0000918 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
919 bool need_to_release_lock = true;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000920
Caroline Tice202f6b82011-01-17 21:55:19 +0000921 if (CurrentThreadHasPythonLock())
922 need_to_release_lock = false;
923 else
924 {
925 while (!GetPythonLock (1))
926 fprintf (tmp_fh, "Python interpreter locked on another thread; waiting to acquire lock...\n");
927 }
928
929 EnterSession ();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000930
Chris Lattner24943d22010-06-08 16:52:24 +0000931 bool success = false;
932 PyObject *py_return = NULL;
933 PyObject *mainmod = PyImport_AddModule ("__main__");
934 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000935 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000936 PyObject *py_error = NULL;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000937 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000938
Caroline Tice0aa2e552011-01-14 00:29:16 +0000939 if (PyDict_Check (globals))
940 {
941 PyObject *key, *value;
942 Py_ssize_t pos = 0;
943
944 while (PyDict_Next (globals, &pos, &key, &value))
945 {
946 // We have stolen references to the key and value objects in the dictionary; we need to increment them now
947 // so that Python's garbage collector doesn't collect them out from under us.
948 Py_INCREF (key);
949 Py_INCREF (value);
950 if (strcmp (PyString_AsString (key), m_dictionary_name.c_str()) == 0)
951 locals = value;
952 }
953 }
954
955 if (locals == NULL)
956 {
957 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
958 should_decrement_locals = true;
959 }
960
961 if (locals == NULL)
962 {
963 locals = globals;
964 should_decrement_locals = false;
965 }
966
967 py_error = PyErr_Occurred();
968 if (py_error != NULL)
969 PyErr_Clear();
970
Chris Lattner24943d22010-06-08 16:52:24 +0000971 if (in_string != NULL)
972 {
973 struct _node *compiled_node = PyParser_SimpleParseString (in_string, Py_file_input);
974 if (compiled_node)
975 {
976 PyCodeObject *compiled_code = PyNode_Compile (compiled_node, "temp.py");
977 if (compiled_code)
978 {
979 py_return = PyEval_EvalCode (compiled_code, globals, locals);
980 if (py_return != NULL)
981 {
982 success = true;
983 Py_DECREF (py_return);
984 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000985 if (locals && should_decrement_locals)
986 Py_DECREF (locals);
Chris Lattner24943d22010-06-08 16:52:24 +0000987 }
988 }
989 }
990
991 py_error = PyErr_Occurred ();
992 if (py_error != NULL)
993 {
994 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
995 PyErr_Print ();
996 PyErr_Clear();
997 success = false;
998 }
999
Caroline Tice0aa2e552011-01-14 00:29:16 +00001000 LeaveSession ();
1001
Caroline Tice202f6b82011-01-17 21:55:19 +00001002 if (need_to_release_lock)
1003 ReleasePythonLock();
1004
Chris Lattner24943d22010-06-08 16:52:24 +00001005 return success;
1006}
1007
1008static const char *g_reader_instructions = "Enter your Python command(s). Type 'DONE' to end.";
1009
1010size_t
1011ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback
1012(
1013 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +00001014 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +00001015 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +00001016 const char *bytes,
1017 size_t bytes_len
1018)
1019{
1020 static StringList commands_in_progress;
1021
Greg Clayton58928562011-02-09 01:08:52 +00001022 File &out_file = reader.GetDebugger().GetOutputFile();
Caroline Ticec95c6d12010-09-14 22:49:06 +00001023
Chris Lattner24943d22010-06-08 16:52:24 +00001024 switch (notification)
1025 {
1026 case eInputReaderActivate:
1027 {
1028 commands_in_progress.Clear();
Greg Clayton58928562011-02-09 01:08:52 +00001029 if (out_file.IsValid())
Chris Lattner24943d22010-06-08 16:52:24 +00001030 {
Greg Clayton58928562011-02-09 01:08:52 +00001031 out_file.Printf ("%s\n", g_reader_instructions);
Greg Clayton63094e02010-06-23 01:19:29 +00001032 if (reader.GetPrompt())
Greg Clayton58928562011-02-09 01:08:52 +00001033 out_file.Printf ("%s", reader.GetPrompt());
1034 out_file.Flush ();
Chris Lattner24943d22010-06-08 16:52:24 +00001035 }
1036 }
1037 break;
1038
1039 case eInputReaderDeactivate:
1040 break;
1041
1042 case eInputReaderReactivate:
Greg Clayton58928562011-02-09 01:08:52 +00001043 if (reader.GetPrompt() && out_file.IsValid())
Caroline Ticef81b4c52010-10-27 18:34:42 +00001044 {
Greg Clayton58928562011-02-09 01:08:52 +00001045 out_file.Printf ("%s", reader.GetPrompt());
1046 out_file.Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +00001047 }
Chris Lattner24943d22010-06-08 16:52:24 +00001048 break;
1049
1050 case eInputReaderGotToken:
1051 {
1052 std::string temp_string (bytes, bytes_len);
1053 commands_in_progress.AppendString (temp_string.c_str());
Greg Clayton58928562011-02-09 01:08:52 +00001054 if (out_file.IsValid() && !reader.IsDone() && reader.GetPrompt())
Caroline Ticef81b4c52010-10-27 18:34:42 +00001055 {
Greg Clayton58928562011-02-09 01:08:52 +00001056 out_file.Printf ("%s", reader.GetPrompt());
1057 out_file.Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +00001058 }
Chris Lattner24943d22010-06-08 16:52:24 +00001059 }
1060 break;
1061
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001062 case eInputReaderEndOfFile:
1063 case eInputReaderInterrupt:
1064 // Control-c (SIGINT) & control-d both mean finish & exit.
1065 reader.SetIsDone(true);
1066
1067 // Control-c (SIGINT) ALSO means cancel; do NOT create a breakpoint command.
1068 if (notification == eInputReaderInterrupt)
1069 commands_in_progress.Clear();
1070
1071 // Fall through here...
1072
Chris Lattner24943d22010-06-08 16:52:24 +00001073 case eInputReaderDone:
1074 {
1075 BreakpointOptions *bp_options = (BreakpointOptions *)baton;
1076 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1077 data_ap->user_source.AppendList (commands_in_progress);
1078 if (data_ap.get())
1079 {
Greg Clayton63094e02010-06-23 01:19:29 +00001080 ScriptInterpreter *interpreter = reader.GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
Chris Lattner24943d22010-06-08 16:52:24 +00001081 if (interpreter)
1082 {
1083 if (interpreter->GenerateBreakpointCommandCallbackData (data_ap->user_source,
1084 data_ap->script_source))
1085 {
1086 if (data_ap->script_source.GetSize() == 1)
1087 {
1088 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1089 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
1090 }
1091 }
Caroline Ticeb447e842010-09-21 19:25:28 +00001092 else
Greg Clayton58928562011-02-09 01:08:52 +00001093 out_file.Printf ("Warning: No command attached to breakpoint.\n");
Chris Lattner24943d22010-06-08 16:52:24 +00001094 }
1095 else
1096 {
1097 // FIXME: Error processing.
1098 }
1099 }
1100 }
1101 break;
1102
1103 }
1104
1105 return bytes_len;
1106}
1107
1108void
Greg Clayton238c0a12010-09-18 01:14:36 +00001109ScriptInterpreterPython::CollectDataForBreakpointCommandCallback (BreakpointOptions *bp_options,
Chris Lattner24943d22010-06-08 16:52:24 +00001110 CommandReturnObject &result)
1111{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001112 Debugger &debugger = GetCommandInterpreter().GetDebugger();
1113
Greg Clayton63094e02010-06-23 01:19:29 +00001114 InputReaderSP reader_sp (new InputReader (debugger));
Chris Lattner24943d22010-06-08 16:52:24 +00001115
1116 if (reader_sp)
1117 {
1118 Error err = reader_sp->Initialize (
1119 ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback,
1120 bp_options, // baton
1121 eInputReaderGranularityLine, // token size, for feeding data to callback function
1122 "DONE", // end token
1123 "> ", // prompt
1124 true); // echo input
1125
1126 if (err.Success())
Greg Clayton63094e02010-06-23 01:19:29 +00001127 debugger.PushInputReader (reader_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001128 else
1129 {
1130 result.AppendError (err.AsCString());
1131 result.SetStatus (eReturnStatusFailed);
1132 }
1133 }
1134 else
1135 {
1136 result.AppendError("out of memory");
1137 result.SetStatus (eReturnStatusFailed);
1138 }
1139}
1140
Johnny Chen3e0571b2010-09-11 00:23:59 +00001141// Set a Python one-liner as the callback for the breakpoint.
Johnny Chend1c2dca2010-09-10 18:21:10 +00001142void
Greg Clayton238c0a12010-09-18 01:14:36 +00001143ScriptInterpreterPython::SetBreakpointCommandCallback (BreakpointOptions *bp_options,
Johnny Chend1c2dca2010-09-10 18:21:10 +00001144 const char *oneliner)
1145{
1146 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1147
1148 // It's necessary to set both user_source and script_source to the oneliner.
1149 // The former is used to generate callback description (as in breakpoint command list)
1150 // while the latter is used for Python to interpret during the actual callback.
Caroline Tice5136f942010-09-27 21:35:15 +00001151
Johnny Chend1c2dca2010-09-10 18:21:10 +00001152 data_ap->user_source.AppendString (oneliner);
Johnny Chend1c2dca2010-09-10 18:21:10 +00001153
Caroline Tice5136f942010-09-27 21:35:15 +00001154 if (GenerateBreakpointCommandCallbackData (data_ap->user_source, data_ap->script_source))
1155 {
1156 if (data_ap->script_source.GetSize() == 1)
1157 {
1158 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1159 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
1160 }
1161 }
1162
Johnny Chend1c2dca2010-09-10 18:21:10 +00001163 return;
1164}
1165
Chris Lattner24943d22010-06-08 16:52:24 +00001166bool
1167ScriptInterpreterPython::ExportFunctionDefinitionToInterpreter (StringList &function_def)
1168{
1169 // Convert StringList to one long, newline delimited, const char *.
1170 std::string function_def_string;
1171
1172 int num_lines = function_def.GetSize();
1173
1174 for (int i = 0; i < num_lines; ++i)
1175 {
1176 function_def_string.append (function_def.GetStringAtIndex(i));
1177 if (function_def_string.at (function_def_string.length() - 1) != '\n')
1178 function_def_string.append ("\n");
1179
1180 }
1181
1182 return ExecuteMultipleLines (function_def_string.c_str());
1183}
1184
1185bool
1186ScriptInterpreterPython::GenerateBreakpointCommandCallbackData (StringList &user_input, StringList &callback_data)
1187{
1188 static int num_created_functions = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001189 user_input.RemoveBlankLines ();
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001190 int num_lines = user_input.GetSize ();
1191 StreamString sstr;
Chris Lattner24943d22010-06-08 16:52:24 +00001192
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001193 // Check to see if we have any data; if not, just return.
1194 if (user_input.GetSize() == 0)
1195 return false;
1196
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001197 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1198 // frame and breakpoint location as parameters to the function.
Caroline Ticeb447e842010-09-21 19:25:28 +00001199
Caroline Ticeb447e842010-09-21 19:25:28 +00001200
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001201 sstr.Printf ("lldb_autogen_python_bp_callback_func_%d", num_created_functions);
1202 ++num_created_functions;
1203 std::string auto_generated_function_name = sstr.GetData();
Caroline Ticeb447e842010-09-21 19:25:28 +00001204
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001205 sstr.Clear();
Caroline Ticeb447e842010-09-21 19:25:28 +00001206 StringList auto_generated_function;
Caroline Ticeb447e842010-09-21 19:25:28 +00001207
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001208 // Create the function name & definition string.
1209
Caroline Tice0aa2e552011-01-14 00:29:16 +00001210 sstr.Printf ("def %s (frame, bp_loc, dict):", auto_generated_function_name.c_str());
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001211 auto_generated_function.AppendString (sstr.GetData());
Caroline Tice0aa2e552011-01-14 00:29:16 +00001212
1213 // Pre-pend code for setting up the session dictionary.
1214
1215 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1216 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1217 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1218 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1219 // global dictionary.
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001220
1221 // Wrap everything up inside the function, increasing the indentation.
Chris Lattner24943d22010-06-08 16:52:24 +00001222
1223 for (int i = 0; i < num_lines; ++i)
1224 {
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001225 sstr.Clear ();
1226 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1227 auto_generated_function.AppendString (sstr.GetData());
Caroline Ticeb447e842010-09-21 19:25:28 +00001228 }
Chris Lattner24943d22010-06-08 16:52:24 +00001229
Caroline Tice0aa2e552011-01-14 00:29:16 +00001230 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1231 // got written to the values in the global dictionary, not the session dictionary).
1232
1233 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1234 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1235 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1236 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1237
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001238 // Verify that the results are valid Python.
Chris Lattner24943d22010-06-08 16:52:24 +00001239
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001240 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
Caroline Ticeb447e842010-09-21 19:25:28 +00001241 {
Caroline Ticeb447e842010-09-21 19:25:28 +00001242 return false;
Chris Lattner24943d22010-06-08 16:52:24 +00001243 }
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001244
1245 // Store the name of the auto-generated function to be called.
1246
1247 callback_data.AppendString (auto_generated_function_name.c_str());
1248 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001249}
1250
Greg Clayton5144f382010-10-07 17:14:24 +00001251bool
1252ScriptInterpreterPython::BreakpointCallbackFunction
1253(
1254 void *baton,
1255 StoppointCallbackContext *context,
1256 user_id_t break_id,
1257 user_id_t break_loc_id
1258)
1259{
1260 BreakpointOptions::CommandData *bp_option_data = (BreakpointOptions::CommandData *) baton;
1261 const char *python_function_name = bp_option_data->script_source.GetStringAtIndex (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001262
1263 if (!context)
1264 return true;
1265
1266 Target *target = context->exe_ctx.target;
1267
1268 if (!target)
1269 return true;
1270
1271 Debugger &debugger = target->GetDebugger();
1272 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1273 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1274
1275 if (!script_interpreter)
1276 return true;
Greg Clayton5144f382010-10-07 17:14:24 +00001277
1278 if (python_function_name != NULL
1279 && python_function_name[0] != '\0')
1280 {
1281 Thread *thread = context->exe_ctx.thread;
Greg Claytone86cbb92011-03-22 01:14:58 +00001282 const StackFrameSP stop_frame_sp (thread->GetStackFrameSPForStackFramePtr (context->exe_ctx.frame));
Greg Clayton5144f382010-10-07 17:14:24 +00001283 BreakpointSP breakpoint_sp = target->GetBreakpointByID (break_id);
Greg Claytone86cbb92011-03-22 01:14:58 +00001284 if (breakpoint_sp)
Caroline Tice0aa2e552011-01-14 00:29:16 +00001285 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001286 const BreakpointLocationSP bp_loc_sp (breakpoint_sp->FindLocationByID (break_loc_id));
1287
1288 if (stop_frame_sp && bp_loc_sp)
Caroline Tice202f6b82011-01-17 21:55:19 +00001289 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001290 bool ret_val = true;
1291 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
1292 if (CurrentThreadHasPythonLock())
1293 {
1294 python_interpreter->EnterSession ();
1295 ret_val = g_swig_breakpoint_callback (python_function_name,
1296 python_interpreter->m_dictionary_name.c_str(),
1297 stop_frame_sp,
1298 bp_loc_sp);
1299 python_interpreter->LeaveSession ();
1300 }
1301 else
1302 {
1303 while (!GetPythonLock (1))
1304 fprintf (tmp_fh,
1305 "Python interpreter locked on another thread; waiting to acquire lock...\n");
1306 python_interpreter->EnterSession ();
1307 ret_val = g_swig_breakpoint_callback (python_function_name,
1308 python_interpreter->m_dictionary_name.c_str(),
1309 stop_frame_sp,
1310 bp_loc_sp);
1311 python_interpreter->LeaveSession ();
1312 ReleasePythonLock ();
1313 }
1314 return ret_val;
Caroline Tice202f6b82011-01-17 21:55:19 +00001315 }
Caroline Tice0aa2e552011-01-14 00:29:16 +00001316 }
Greg Clayton5144f382010-10-07 17:14:24 +00001317 }
1318 // We currently always true so we stop in case anything goes wrong when
1319 // trying to call the script function
1320 return true;
1321}
Caroline Tice2ade6112010-11-10 19:18:14 +00001322
1323lldb::thread_result_t
1324ScriptInterpreterPython::RunEmbeddedPythonInterpreter (lldb::thread_arg_t baton)
1325{
1326 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
1327
1328 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
1329
1330 if (log)
1331 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread starting...", baton);
1332
1333 char error_str[1024];
1334 const char *pty_slave_name = script_interpreter->m_embedded_python_pty.GetSlaveName (error_str, sizeof (error_str));
Caroline Tice202f6b82011-01-17 21:55:19 +00001335 bool need_to_release_lock = true;
1336 bool safe_to_run = false;
Caroline Tice0aa2e552011-01-14 00:29:16 +00001337
Caroline Tice202f6b82011-01-17 21:55:19 +00001338 if (CurrentThreadHasPythonLock())
1339 {
1340 safe_to_run = true;
1341 need_to_release_lock = false;
1342 }
1343 else
1344 {
1345 int interval = 1;
1346 safe_to_run = GetPythonLock (interval);
1347 while (!safe_to_run)
1348 {
1349 interval = interval * 2;
1350 safe_to_run = GetPythonLock (interval);
1351 }
1352 }
1353
1354 if (pty_slave_name != NULL && safe_to_run)
1355 {
Caroline Tice2ade6112010-11-10 19:18:14 +00001356 StreamString run_string;
Caroline Tice2ade6112010-11-10 19:18:14 +00001357
Caroline Tice202f6b82011-01-17 21:55:19 +00001358 script_interpreter->EnterSession ();
1359
Caroline Tice0aa2e552011-01-14 00:29:16 +00001360 run_string.Printf ("run_one_line (%s, 'save_stderr = sys.stderr')", script_interpreter->m_dictionary_name.c_str());
1361 PyRun_SimpleString (run_string.GetData());
1362 run_string.Clear ();
1363
1364 run_string.Printf ("run_one_line (%s, 'sys.stderr = sys.stdout')", script_interpreter->m_dictionary_name.c_str());
1365 PyRun_SimpleString (run_string.GetData());
1366 run_string.Clear ();
1367
1368 run_string.Printf ("run_one_line (%s, 'save_stdin = sys.stdin')", script_interpreter->m_dictionary_name.c_str());
1369 PyRun_SimpleString (run_string.GetData());
1370 run_string.Clear ();
1371
1372 run_string.Printf ("run_one_line (%s, \"sys.stdin = open ('%s', 'r')\")", script_interpreter->m_dictionary_name.c_str(),
1373 pty_slave_name);
1374 PyRun_SimpleString (run_string.GetData());
1375 run_string.Clear ();
1376
Johnny Chen8054ba32011-03-11 00:28:50 +00001377 // The following call drops into the embedded interpreter loop and stays there until the
1378 // user chooses to exit from the Python interpreter.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001379
Caroline Ticece207c12011-03-11 00:21:55 +00001380 // When in the embedded interpreter, the user can call arbitrary system and Python stuff, which may require
Johnny Chen8054ba32011-03-11 00:28:50 +00001381 // the ability to run multi-threaded stuff, so we need to surround the call to the embedded interpreter with
Caroline Ticece207c12011-03-11 00:21:55 +00001382 // calls to Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS.
1383
1384 // We ALSO need to surround the call to the embedded interpreter with calls to PyGILState_Ensure and
1385 // PyGILState_Release. This is because this embedded interpreter is being run on a DIFFERENT THREAD than
1386 // the thread on which the call to Py_Initialize (and PyEval_InitThreads) was called. Those initializations
1387 // called PyGILState_Ensure on *that* thread, but it also needs to be called on *this* thread. Otherwise,
1388 // if the user calls Python code that does threading stuff, the interpreter state will be off, and things could
1389 // hang (it's happened before).
1390
Caroline Tice9d352ce2011-03-07 23:24:28 +00001391 Py_BEGIN_ALLOW_THREADS
1392 PyGILState_STATE gstate = PyGILState_Ensure();
1393
Caroline Tice0aa2e552011-01-14 00:29:16 +00001394 run_string.Printf ("run_python_interpreter (%s)", script_interpreter->m_dictionary_name.c_str());
1395 PyRun_SimpleString (run_string.GetData());
1396 run_string.Clear ();
Caroline Tice2ade6112010-11-10 19:18:14 +00001397
Caroline Tice9d352ce2011-03-07 23:24:28 +00001398 PyGILState_Release (gstate);
1399 Py_END_ALLOW_THREADS
1400
Caroline Tice0aa2e552011-01-14 00:29:16 +00001401 run_string.Printf ("run_one_line (%s, 'sys.stdin = save_stdin')", script_interpreter->m_dictionary_name.c_str());
1402 PyRun_SimpleString (run_string.GetData());
1403 run_string.Clear();
1404
1405 run_string.Printf ("run_one_line (%s, 'sys.stderr = save_stderr')", script_interpreter->m_dictionary_name.c_str());
1406 PyRun_SimpleString (run_string.GetData());
1407 run_string.Clear();
Caroline Tice202f6b82011-01-17 21:55:19 +00001408
1409 script_interpreter->LeaveSession ();
1410
Caroline Tice2ade6112010-11-10 19:18:14 +00001411 }
1412
Caroline Tice202f6b82011-01-17 21:55:19 +00001413 if (!safe_to_run)
1414 fprintf ((script_interpreter->m_dbg_stdout ? script_interpreter->m_dbg_stdout : stdout),
1415 "Python interpreter locked on another thread; unable to acquire lock.\n");
1416
1417 if (need_to_release_lock)
1418 ReleasePythonLock ();
1419
Caroline Tice2ade6112010-11-10 19:18:14 +00001420 if (script_interpreter->m_embedded_thread_input_reader_sp)
1421 script_interpreter->m_embedded_thread_input_reader_sp->SetIsDone (true);
1422
1423 script_interpreter->m_embedded_python_pty.CloseSlaveFileDescriptor();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001424
1425 script_interpreter->m_pty_slave_is_open = false;
Caroline Tice2ade6112010-11-10 19:18:14 +00001426
1427 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT);
1428 if (log)
1429 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread exiting...", baton);
1430
1431
Johnny Chen8054ba32011-03-11 00:28:50 +00001432 // Clean up the input reader and make the debugger pop it off the stack.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001433 Debugger &debugger = script_interpreter->GetCommandInterpreter().GetDebugger();
Caroline Tice2ade6112010-11-10 19:18:14 +00001434 const InputReaderSP reader_sp = script_interpreter->m_embedded_thread_input_reader_sp;
1435 script_interpreter->m_embedded_thread_input_reader_sp.reset();
1436 debugger.PopInputReader (reader_sp);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001437
Caroline Tice2ade6112010-11-10 19:18:14 +00001438 return NULL;
1439}
1440
1441
Caroline Tice0aa2e552011-01-14 00:29:16 +00001442void
Greg Claytone86cbb92011-03-22 01:14:58 +00001443ScriptInterpreterPython::InitializeInterpreter (SWIGInitCallback python_swig_init_callback,
1444 SWIGBreakpointCallbackFunction python_swig_breakpoint_callback)
1445{
1446 g_swig_init_callback = python_swig_init_callback;
1447 g_swig_breakpoint_callback = python_swig_breakpoint_callback;
1448}
1449
1450void
1451ScriptInterpreterPython::InitializePrivate ()
Caroline Tice0aa2e552011-01-14 00:29:16 +00001452{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001453 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
1454
Greg Clayton0fdd4a02011-02-07 23:24:47 +00001455 // Python will muck with STDIN terminal state, so save off any current TTY
1456 // settings so we can restore them.
1457 TerminalState stdin_tty_state;
1458 stdin_tty_state.Save(STDIN_FILENO, false);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001459
1460 // Find the module that owns this code and use that path we get to
1461 // set the PYTHONPATH appropriately.
1462
1463 FileSpec file_spec;
1464 char python_dir_path[PATH_MAX];
1465 if (Host::GetLLDBPath (ePathTypePythonDir, file_spec))
1466 {
1467 std::string python_path;
1468 const char *curr_python_path = ::getenv ("PYTHONPATH");
1469 if (curr_python_path)
1470 {
1471 // We have a current value for PYTHONPATH, so lets append to it
1472 python_path.append (curr_python_path);
1473 }
1474
1475 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
1476 {
1477 if (!python_path.empty())
1478 python_path.append (1, ':');
1479 python_path.append (python_dir_path);
1480 }
1481
1482 if (Host::GetLLDBPath (ePathTypeLLDBShlibDir, file_spec))
1483 {
1484 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
1485 {
1486 if (!python_path.empty())
1487 python_path.append (1, ':');
1488 python_path.append (python_dir_path);
1489 }
1490 }
1491 const char *pathon_path_env_cstr = python_path.c_str();
1492 ::setenv ("PYTHONPATH", pathon_path_env_cstr, 1);
1493 }
1494
Caroline Tice9d352ce2011-03-07 23:24:28 +00001495 PyEval_InitThreads ();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001496 Py_Initialize ();
1497
1498 PyObject *compiled_module = Py_CompileString (embedded_interpreter_string,
1499 "embedded_interpreter.py",
1500 Py_file_input);
1501
1502 PyObject *py_error = PyErr_Occurred ();
1503 if (py_error != NULL)
1504 {
1505 PyErr_Print();
1506 PyErr_Clear();
1507 }
1508
1509
Greg Claytone86cbb92011-03-22 01:14:58 +00001510 // Initialize SWIG after setting up python
1511 assert (g_swig_init_callback != NULL);
1512 g_swig_init_callback ();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001513
1514 // Update the path python uses to search for modules to include the current directory.
1515
1516 int success = PyRun_SimpleString ("import sys");
1517 success = PyRun_SimpleString ("sys.path.append ('.')");
1518
1519 PyObject *pmod = NULL;
1520
1521 if (compiled_module)
1522 {
1523 pmod = PyImport_ExecCodeModule (const_cast<char*> ("embedded_interpreter"),
1524 compiled_module);
1525 Py_DECREF (compiled_module);
1526 }
1527
1528 if (pmod != NULL)
1529 {
1530 PyRun_SimpleString ("from embedded_interpreter import run_python_interpreter");
1531 PyRun_SimpleString ("from embedded_interpreter import run_one_line");
1532 PyRun_SimpleString ("import sys");
1533 PyRun_SimpleString ("from termios import *");
1534 Py_DECREF (pmod);
1535 }
Greg Clayton99208582011-02-07 19:04:58 +00001536
Greg Clayton0fdd4a02011-02-07 23:24:47 +00001537 stdin_tty_state.Restore();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001538}
1539
Greg Claytone86cbb92011-03-22 01:14:58 +00001540//void
1541//ScriptInterpreterPython::Terminate ()
1542//{
1543// // We are intentionally NOT calling Py_Finalize here (this would be the logical place to call it). Calling
1544// // Py_Finalize here causes test suite runs to seg fault: The test suite runs in Python. It registers
1545// // SBDebugger::Terminate to be called 'at_exit'. When the test suite Python harness finishes up, it calls
1546// // Py_Finalize, which calls all the 'at_exit' registered functions. SBDebugger::Terminate calls Debugger::Terminate,
1547// // which calls lldb::Terminate, which calls ScriptInterpreter::Terminate, which calls
1548// // ScriptInterpreterPython::Terminate. So if we call Py_Finalize here, we end up with Py_Finalize being called from
1549// // within Py_Finalize, which results in a seg fault.
1550// //
1551// // Since this function only gets called when lldb is shutting down and going away anyway, the fact that we don't
1552// // actually call Py_Finalize should not cause any problems (everything should shut down/go away anyway when the
1553// // process exits).
1554// //
1555//// Py_Finalize ();
1556//}