blob: 47302be0ee4aad12d46ca0ba9737022cb76ad5e9 [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
Caroline Tice4a348082011-05-02 20:41:46 +0000642 case eInputReaderAsynchronousOutputWritten:
643 break;
644
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000645 case eInputReaderInterrupt:
646 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "raise KeyboardInterrupt\n", 24);
647 break;
648
649 case eInputReaderEndOfFile:
650 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()\n", 7);
651 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000652
653 case eInputReaderGotToken:
Caroline Tice2ade6112010-11-10 19:18:14 +0000654 if (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor() != -1)
Chris Lattner24943d22010-06-08 16:52:24 +0000655 {
Caroline Tice2ade6112010-11-10 19:18:14 +0000656 if (log)
657 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %d", bytes,
658 bytes_len);
659 if (bytes && bytes_len)
660 {
661 if ((int) bytes[0] == 4)
662 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()", 6);
663 else
664 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), bytes, bytes_len);
665 }
666 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "\n", 1);
Chris Lattner24943d22010-06-08 16:52:24 +0000667 }
Caroline Tice2ade6112010-11-10 19:18:14 +0000668 else
669 {
670 if (log)
671 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %d, Master File Descriptor is bad.",
672 bytes,
673 bytes_len);
674 reader.SetIsDone (true);
675 }
676
Chris Lattner24943d22010-06-08 16:52:24 +0000677 break;
678
679 case eInputReaderDone:
Caroline Tice0aa2e552011-01-14 00:29:16 +0000680 script_interpreter->LeaveSession ();
681
Chris Lattner24943d22010-06-08 16:52:24 +0000682 // Restore terminal settings if they were validly saved
Caroline Tice2ade6112010-11-10 19:18:14 +0000683 if (log)
684 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Done, closing down input reader.");
Caroline Ticec95c6d12010-09-14 22:49:06 +0000685
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000686 script_interpreter->RestoreTerminalState ();
687
Caroline Tice2ade6112010-11-10 19:18:14 +0000688 script_interpreter->m_embedded_python_pty.CloseMasterFileDescriptor();
Chris Lattner24943d22010-06-08 16:52:24 +0000689 break;
690 }
691
692 return bytes_len;
693}
694
695
696void
Greg Clayton238c0a12010-09-18 01:14:36 +0000697ScriptInterpreterPython::ExecuteInterpreterLoop ()
Chris Lattner24943d22010-06-08 16:52:24 +0000698{
699 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
700
Caroline Tice0aa2e552011-01-14 00:29:16 +0000701 Debugger &debugger = GetCommandInterpreter().GetDebugger();
Caroline Ticec95c6d12010-09-14 22:49:06 +0000702
703 // At the moment, the only time the debugger does not have an input file handle is when this is called
704 // directly from Python, in which case it is both dangerous and unnecessary (not to mention confusing) to
705 // try to embed a running interpreter loop inside the already running Python interpreter loop, so we won't
706 // do it.
707
Greg Clayton58928562011-02-09 01:08:52 +0000708 if (!debugger.GetInputFile().IsValid())
Caroline Ticec95c6d12010-09-14 22:49:06 +0000709 return;
710
Greg Clayton63094e02010-06-23 01:19:29 +0000711 InputReaderSP reader_sp (new InputReader(debugger));
Chris Lattner24943d22010-06-08 16:52:24 +0000712 if (reader_sp)
713 {
714 Error error (reader_sp->Initialize (ScriptInterpreterPython::InputReaderCallback,
715 this, // baton
716 eInputReaderGranularityLine, // token size, to pass to callback function
717 NULL, // end token
718 NULL, // prompt
719 true)); // echo input
720
721 if (error.Success())
722 {
Greg Clayton63094e02010-06-23 01:19:29 +0000723 debugger.PushInputReader (reader_sp);
Caroline Tice2ade6112010-11-10 19:18:14 +0000724 m_embedded_thread_input_reader_sp = reader_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000725 }
726 }
727}
728
729bool
730ScriptInterpreterPython::ExecuteOneLineWithReturn (const char *in_string,
731 ScriptInterpreter::ReturnType return_type,
732 void *ret_value)
733{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000734
Caroline Tice202f6b82011-01-17 21:55:19 +0000735 bool need_to_release_lock = true;
736
737 if (CurrentThreadHasPythonLock())
738 need_to_release_lock = false;
739 else if (!GetPythonLock (1))
740 {
741 fprintf ((m_dbg_stdout ? m_dbg_stdout : stdout),
742 "Python interpreter is currently locked by another thread; unable to process command.\n");
743 return false;
744 }
745
746 EnterSession ();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000747
Chris Lattner24943d22010-06-08 16:52:24 +0000748 PyObject *py_return = NULL;
749 PyObject *mainmod = PyImport_AddModule ("__main__");
750 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000751 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000752 PyObject *py_error = NULL;
753 bool ret_success;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000754 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000755 int success;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000756
757 if (PyDict_Check (globals))
758 {
759 PyObject *key, *value;
760 Py_ssize_t pos = 0;
761
762 int i = 0;
763 while (PyDict_Next (globals, &pos, &key, &value))
764 {
765 // We have stolen references to the key and value objects in the dictionary; we need to increment them now
766 // so that Python's garbage collector doesn't collect them out from under us.
767 Py_INCREF (key);
768 Py_INCREF (value);
769 char *c_str = PyString_AsString (key);
770 if (strcmp (c_str, m_dictionary_name.c_str()) == 0)
771 locals = value;
772 ++i;
773 }
774 }
Chris Lattner24943d22010-06-08 16:52:24 +0000775
Caroline Tice0aa2e552011-01-14 00:29:16 +0000776 if (locals == NULL)
777 {
778 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
779 should_decrement_locals = true;
780 }
781
782 if (locals == NULL)
783 {
784 locals = globals;
785 should_decrement_locals = false;
786 }
787
788 py_error = PyErr_Occurred();
789 if (py_error != NULL)
790 PyErr_Clear();
791
Chris Lattner24943d22010-06-08 16:52:24 +0000792 if (in_string != NULL)
793 {
794 py_return = PyRun_String (in_string, Py_eval_input, globals, locals);
795 if (py_return == NULL)
796 {
797 py_error = PyErr_Occurred ();
798 if (py_error != NULL)
799 PyErr_Clear ();
800
801 py_return = PyRun_String (in_string, Py_single_input, globals, locals);
802 }
803
Caroline Tice0aa2e552011-01-14 00:29:16 +0000804 if (locals != NULL
805 && should_decrement_locals)
806 Py_DECREF (locals);
807
Chris Lattner24943d22010-06-08 16:52:24 +0000808 if (py_return != NULL)
809 {
810 switch (return_type)
811 {
812 case eCharPtr: // "char *"
813 {
814 const char format[3] = "s#";
815 success = PyArg_Parse (py_return, format, (char **) &ret_value);
816 break;
817 }
818 case eBool:
819 {
820 const char format[2] = "b";
821 success = PyArg_Parse (py_return, format, (bool *) ret_value);
822 break;
823 }
824 case eShortInt:
825 {
826 const char format[2] = "h";
827 success = PyArg_Parse (py_return, format, (short *) ret_value);
828 break;
829 }
830 case eShortIntUnsigned:
831 {
832 const char format[2] = "H";
833 success = PyArg_Parse (py_return, format, (unsigned short *) ret_value);
834 break;
835 }
836 case eInt:
837 {
838 const char format[2] = "i";
839 success = PyArg_Parse (py_return, format, (int *) ret_value);
840 break;
841 }
842 case eIntUnsigned:
843 {
844 const char format[2] = "I";
845 success = PyArg_Parse (py_return, format, (unsigned int *) ret_value);
846 break;
847 }
848 case eLongInt:
849 {
850 const char format[2] = "l";
851 success = PyArg_Parse (py_return, format, (long *) ret_value);
852 break;
853 }
854 case eLongIntUnsigned:
855 {
856 const char format[2] = "k";
857 success = PyArg_Parse (py_return, format, (unsigned long *) ret_value);
858 break;
859 }
860 case eLongLong:
861 {
862 const char format[2] = "L";
863 success = PyArg_Parse (py_return, format, (long long *) ret_value);
864 break;
865 }
866 case eLongLongUnsigned:
867 {
868 const char format[2] = "K";
869 success = PyArg_Parse (py_return, format, (unsigned long long *) ret_value);
870 break;
871 }
872 case eFloat:
873 {
874 const char format[2] = "f";
875 success = PyArg_Parse (py_return, format, (float *) ret_value);
876 break;
877 }
878 case eDouble:
879 {
880 const char format[2] = "d";
881 success = PyArg_Parse (py_return, format, (double *) ret_value);
882 break;
883 }
884 case eChar:
885 {
886 const char format[2] = "c";
887 success = PyArg_Parse (py_return, format, (char *) ret_value);
888 break;
889 }
890 default:
891 {}
892 }
893 Py_DECREF (py_return);
894 if (success)
895 ret_success = true;
896 else
897 ret_success = false;
898 }
899 }
900
901 py_error = PyErr_Occurred();
902 if (py_error != NULL)
903 {
904 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
905 PyErr_Print ();
906 PyErr_Clear();
907 ret_success = false;
908 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000909
910 LeaveSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000911
Caroline Tice202f6b82011-01-17 21:55:19 +0000912 if (need_to_release_lock)
913 ReleasePythonLock();
914
Chris Lattner24943d22010-06-08 16:52:24 +0000915 return ret_success;
916}
917
918bool
919ScriptInterpreterPython::ExecuteMultipleLines (const char *in_string)
920{
Caroline Tice202f6b82011-01-17 21:55:19 +0000921 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
922 bool need_to_release_lock = true;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000923
Caroline Tice202f6b82011-01-17 21:55:19 +0000924 if (CurrentThreadHasPythonLock())
925 need_to_release_lock = false;
926 else
927 {
928 while (!GetPythonLock (1))
929 fprintf (tmp_fh, "Python interpreter locked on another thread; waiting to acquire lock...\n");
930 }
931
932 EnterSession ();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000933
Chris Lattner24943d22010-06-08 16:52:24 +0000934 bool success = false;
935 PyObject *py_return = NULL;
936 PyObject *mainmod = PyImport_AddModule ("__main__");
937 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000938 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000939 PyObject *py_error = NULL;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000940 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000941
Caroline Tice0aa2e552011-01-14 00:29:16 +0000942 if (PyDict_Check (globals))
943 {
944 PyObject *key, *value;
945 Py_ssize_t pos = 0;
946
947 while (PyDict_Next (globals, &pos, &key, &value))
948 {
949 // We have stolen references to the key and value objects in the dictionary; we need to increment them now
950 // so that Python's garbage collector doesn't collect them out from under us.
951 Py_INCREF (key);
952 Py_INCREF (value);
953 if (strcmp (PyString_AsString (key), m_dictionary_name.c_str()) == 0)
954 locals = value;
955 }
956 }
957
958 if (locals == NULL)
959 {
960 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
961 should_decrement_locals = true;
962 }
963
964 if (locals == NULL)
965 {
966 locals = globals;
967 should_decrement_locals = false;
968 }
969
970 py_error = PyErr_Occurred();
971 if (py_error != NULL)
972 PyErr_Clear();
973
Chris Lattner24943d22010-06-08 16:52:24 +0000974 if (in_string != NULL)
975 {
976 struct _node *compiled_node = PyParser_SimpleParseString (in_string, Py_file_input);
977 if (compiled_node)
978 {
979 PyCodeObject *compiled_code = PyNode_Compile (compiled_node, "temp.py");
980 if (compiled_code)
981 {
982 py_return = PyEval_EvalCode (compiled_code, globals, locals);
983 if (py_return != NULL)
984 {
985 success = true;
986 Py_DECREF (py_return);
987 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000988 if (locals && should_decrement_locals)
989 Py_DECREF (locals);
Chris Lattner24943d22010-06-08 16:52:24 +0000990 }
991 }
992 }
993
994 py_error = PyErr_Occurred ();
995 if (py_error != NULL)
996 {
997 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
998 PyErr_Print ();
999 PyErr_Clear();
1000 success = false;
1001 }
1002
Caroline Tice0aa2e552011-01-14 00:29:16 +00001003 LeaveSession ();
1004
Caroline Tice202f6b82011-01-17 21:55:19 +00001005 if (need_to_release_lock)
1006 ReleasePythonLock();
1007
Chris Lattner24943d22010-06-08 16:52:24 +00001008 return success;
1009}
1010
1011static const char *g_reader_instructions = "Enter your Python command(s). Type 'DONE' to end.";
1012
1013size_t
1014ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback
1015(
1016 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +00001017 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +00001018 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +00001019 const char *bytes,
1020 size_t bytes_len
1021)
1022{
1023 static StringList commands_in_progress;
1024
Greg Clayton58928562011-02-09 01:08:52 +00001025 File &out_file = reader.GetDebugger().GetOutputFile();
Caroline Ticec95c6d12010-09-14 22:49:06 +00001026
Chris Lattner24943d22010-06-08 16:52:24 +00001027 switch (notification)
1028 {
1029 case eInputReaderActivate:
1030 {
1031 commands_in_progress.Clear();
Greg Clayton58928562011-02-09 01:08:52 +00001032 if (out_file.IsValid())
Chris Lattner24943d22010-06-08 16:52:24 +00001033 {
Greg Clayton58928562011-02-09 01:08:52 +00001034 out_file.Printf ("%s\n", g_reader_instructions);
Greg Clayton63094e02010-06-23 01:19:29 +00001035 if (reader.GetPrompt())
Greg Clayton58928562011-02-09 01:08:52 +00001036 out_file.Printf ("%s", reader.GetPrompt());
1037 out_file.Flush ();
Chris Lattner24943d22010-06-08 16:52:24 +00001038 }
1039 }
1040 break;
1041
1042 case eInputReaderDeactivate:
1043 break;
1044
1045 case eInputReaderReactivate:
Greg Clayton58928562011-02-09 01:08:52 +00001046 if (reader.GetPrompt() && out_file.IsValid())
Caroline Ticef81b4c52010-10-27 18:34:42 +00001047 {
Greg Clayton58928562011-02-09 01:08:52 +00001048 out_file.Printf ("%s", reader.GetPrompt());
1049 out_file.Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +00001050 }
Chris Lattner24943d22010-06-08 16:52:24 +00001051 break;
1052
Caroline Tice4a348082011-05-02 20:41:46 +00001053 case eInputReaderAsynchronousOutputWritten:
1054 break;
1055
Chris Lattner24943d22010-06-08 16:52:24 +00001056 case eInputReaderGotToken:
1057 {
1058 std::string temp_string (bytes, bytes_len);
1059 commands_in_progress.AppendString (temp_string.c_str());
Greg Clayton58928562011-02-09 01:08:52 +00001060 if (out_file.IsValid() && !reader.IsDone() && reader.GetPrompt())
Caroline Ticef81b4c52010-10-27 18:34:42 +00001061 {
Greg Clayton58928562011-02-09 01:08:52 +00001062 out_file.Printf ("%s", reader.GetPrompt());
1063 out_file.Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +00001064 }
Chris Lattner24943d22010-06-08 16:52:24 +00001065 }
1066 break;
1067
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001068 case eInputReaderEndOfFile:
1069 case eInputReaderInterrupt:
1070 // Control-c (SIGINT) & control-d both mean finish & exit.
1071 reader.SetIsDone(true);
1072
1073 // Control-c (SIGINT) ALSO means cancel; do NOT create a breakpoint command.
1074 if (notification == eInputReaderInterrupt)
1075 commands_in_progress.Clear();
1076
1077 // Fall through here...
1078
Chris Lattner24943d22010-06-08 16:52:24 +00001079 case eInputReaderDone:
1080 {
1081 BreakpointOptions *bp_options = (BreakpointOptions *)baton;
1082 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1083 data_ap->user_source.AppendList (commands_in_progress);
1084 if (data_ap.get())
1085 {
Greg Clayton63094e02010-06-23 01:19:29 +00001086 ScriptInterpreter *interpreter = reader.GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
Chris Lattner24943d22010-06-08 16:52:24 +00001087 if (interpreter)
1088 {
1089 if (interpreter->GenerateBreakpointCommandCallbackData (data_ap->user_source,
1090 data_ap->script_source))
1091 {
1092 if (data_ap->script_source.GetSize() == 1)
1093 {
1094 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1095 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
1096 }
1097 }
Caroline Ticeb447e842010-09-21 19:25:28 +00001098 else
Greg Clayton58928562011-02-09 01:08:52 +00001099 out_file.Printf ("Warning: No command attached to breakpoint.\n");
Chris Lattner24943d22010-06-08 16:52:24 +00001100 }
1101 else
1102 {
1103 // FIXME: Error processing.
1104 }
1105 }
1106 }
1107 break;
1108
1109 }
1110
1111 return bytes_len;
1112}
1113
1114void
Greg Clayton238c0a12010-09-18 01:14:36 +00001115ScriptInterpreterPython::CollectDataForBreakpointCommandCallback (BreakpointOptions *bp_options,
Chris Lattner24943d22010-06-08 16:52:24 +00001116 CommandReturnObject &result)
1117{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001118 Debugger &debugger = GetCommandInterpreter().GetDebugger();
1119
Greg Clayton63094e02010-06-23 01:19:29 +00001120 InputReaderSP reader_sp (new InputReader (debugger));
Chris Lattner24943d22010-06-08 16:52:24 +00001121
1122 if (reader_sp)
1123 {
1124 Error err = reader_sp->Initialize (
1125 ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback,
1126 bp_options, // baton
1127 eInputReaderGranularityLine, // token size, for feeding data to callback function
1128 "DONE", // end token
1129 "> ", // prompt
1130 true); // echo input
1131
1132 if (err.Success())
Greg Clayton63094e02010-06-23 01:19:29 +00001133 debugger.PushInputReader (reader_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001134 else
1135 {
1136 result.AppendError (err.AsCString());
1137 result.SetStatus (eReturnStatusFailed);
1138 }
1139 }
1140 else
1141 {
1142 result.AppendError("out of memory");
1143 result.SetStatus (eReturnStatusFailed);
1144 }
1145}
1146
Johnny Chen3e0571b2010-09-11 00:23:59 +00001147// Set a Python one-liner as the callback for the breakpoint.
Johnny Chend1c2dca2010-09-10 18:21:10 +00001148void
Greg Clayton238c0a12010-09-18 01:14:36 +00001149ScriptInterpreterPython::SetBreakpointCommandCallback (BreakpointOptions *bp_options,
Johnny Chend1c2dca2010-09-10 18:21:10 +00001150 const char *oneliner)
1151{
1152 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1153
1154 // It's necessary to set both user_source and script_source to the oneliner.
1155 // The former is used to generate callback description (as in breakpoint command list)
1156 // while the latter is used for Python to interpret during the actual callback.
Caroline Tice5136f942010-09-27 21:35:15 +00001157
Johnny Chend1c2dca2010-09-10 18:21:10 +00001158 data_ap->user_source.AppendString (oneliner);
Johnny Chend1c2dca2010-09-10 18:21:10 +00001159
Caroline Tice5136f942010-09-27 21:35:15 +00001160 if (GenerateBreakpointCommandCallbackData (data_ap->user_source, data_ap->script_source))
1161 {
1162 if (data_ap->script_source.GetSize() == 1)
1163 {
1164 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1165 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
1166 }
1167 }
1168
Johnny Chend1c2dca2010-09-10 18:21:10 +00001169 return;
1170}
1171
Chris Lattner24943d22010-06-08 16:52:24 +00001172bool
1173ScriptInterpreterPython::ExportFunctionDefinitionToInterpreter (StringList &function_def)
1174{
1175 // Convert StringList to one long, newline delimited, const char *.
1176 std::string function_def_string;
1177
1178 int num_lines = function_def.GetSize();
1179
1180 for (int i = 0; i < num_lines; ++i)
1181 {
1182 function_def_string.append (function_def.GetStringAtIndex(i));
1183 if (function_def_string.at (function_def_string.length() - 1) != '\n')
1184 function_def_string.append ("\n");
1185
1186 }
1187
1188 return ExecuteMultipleLines (function_def_string.c_str());
1189}
1190
1191bool
1192ScriptInterpreterPython::GenerateBreakpointCommandCallbackData (StringList &user_input, StringList &callback_data)
1193{
1194 static int num_created_functions = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001195 user_input.RemoveBlankLines ();
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001196 int num_lines = user_input.GetSize ();
1197 StreamString sstr;
Chris Lattner24943d22010-06-08 16:52:24 +00001198
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001199 // Check to see if we have any data; if not, just return.
1200 if (user_input.GetSize() == 0)
1201 return false;
1202
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001203 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1204 // frame and breakpoint location as parameters to the function.
Caroline Ticeb447e842010-09-21 19:25:28 +00001205
Caroline Ticeb447e842010-09-21 19:25:28 +00001206
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001207 sstr.Printf ("lldb_autogen_python_bp_callback_func_%d", num_created_functions);
1208 ++num_created_functions;
1209 std::string auto_generated_function_name = sstr.GetData();
Caroline Ticeb447e842010-09-21 19:25:28 +00001210
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001211 sstr.Clear();
Caroline Ticeb447e842010-09-21 19:25:28 +00001212 StringList auto_generated_function;
Caroline Ticeb447e842010-09-21 19:25:28 +00001213
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001214 // Create the function name & definition string.
1215
Caroline Tice0aa2e552011-01-14 00:29:16 +00001216 sstr.Printf ("def %s (frame, bp_loc, dict):", auto_generated_function_name.c_str());
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001217 auto_generated_function.AppendString (sstr.GetData());
Caroline Tice0aa2e552011-01-14 00:29:16 +00001218
1219 // Pre-pend code for setting up the session dictionary.
1220
1221 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1222 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1223 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1224 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1225 // global dictionary.
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001226
1227 // Wrap everything up inside the function, increasing the indentation.
Chris Lattner24943d22010-06-08 16:52:24 +00001228
1229 for (int i = 0; i < num_lines; ++i)
1230 {
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001231 sstr.Clear ();
1232 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1233 auto_generated_function.AppendString (sstr.GetData());
Caroline Ticeb447e842010-09-21 19:25:28 +00001234 }
Chris Lattner24943d22010-06-08 16:52:24 +00001235
Caroline Tice0aa2e552011-01-14 00:29:16 +00001236 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1237 // got written to the values in the global dictionary, not the session dictionary).
1238
1239 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1240 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1241 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1242 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1243
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001244 // Verify that the results are valid Python.
Chris Lattner24943d22010-06-08 16:52:24 +00001245
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001246 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
Caroline Ticeb447e842010-09-21 19:25:28 +00001247 {
Caroline Ticeb447e842010-09-21 19:25:28 +00001248 return false;
Chris Lattner24943d22010-06-08 16:52:24 +00001249 }
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001250
1251 // Store the name of the auto-generated function to be called.
1252
1253 callback_data.AppendString (auto_generated_function_name.c_str());
1254 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001255}
1256
Greg Clayton5144f382010-10-07 17:14:24 +00001257bool
1258ScriptInterpreterPython::BreakpointCallbackFunction
1259(
1260 void *baton,
1261 StoppointCallbackContext *context,
1262 user_id_t break_id,
1263 user_id_t break_loc_id
1264)
1265{
1266 BreakpointOptions::CommandData *bp_option_data = (BreakpointOptions::CommandData *) baton;
1267 const char *python_function_name = bp_option_data->script_source.GetStringAtIndex (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001268
1269 if (!context)
1270 return true;
1271
1272 Target *target = context->exe_ctx.target;
1273
1274 if (!target)
1275 return true;
1276
1277 Debugger &debugger = target->GetDebugger();
1278 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1279 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1280
1281 if (!script_interpreter)
1282 return true;
Greg Clayton5144f382010-10-07 17:14:24 +00001283
1284 if (python_function_name != NULL
1285 && python_function_name[0] != '\0')
1286 {
1287 Thread *thread = context->exe_ctx.thread;
Greg Claytone86cbb92011-03-22 01:14:58 +00001288 const StackFrameSP stop_frame_sp (thread->GetStackFrameSPForStackFramePtr (context->exe_ctx.frame));
Greg Clayton5144f382010-10-07 17:14:24 +00001289 BreakpointSP breakpoint_sp = target->GetBreakpointByID (break_id);
Greg Claytone86cbb92011-03-22 01:14:58 +00001290 if (breakpoint_sp)
Caroline Tice0aa2e552011-01-14 00:29:16 +00001291 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001292 const BreakpointLocationSP bp_loc_sp (breakpoint_sp->FindLocationByID (break_loc_id));
1293
1294 if (stop_frame_sp && bp_loc_sp)
Caroline Tice202f6b82011-01-17 21:55:19 +00001295 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001296 bool ret_val = true;
1297 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
1298 if (CurrentThreadHasPythonLock())
1299 {
1300 python_interpreter->EnterSession ();
1301 ret_val = g_swig_breakpoint_callback (python_function_name,
1302 python_interpreter->m_dictionary_name.c_str(),
1303 stop_frame_sp,
1304 bp_loc_sp);
1305 python_interpreter->LeaveSession ();
1306 }
1307 else
1308 {
1309 while (!GetPythonLock (1))
1310 fprintf (tmp_fh,
1311 "Python interpreter locked on another thread; waiting to acquire lock...\n");
1312 python_interpreter->EnterSession ();
1313 ret_val = g_swig_breakpoint_callback (python_function_name,
1314 python_interpreter->m_dictionary_name.c_str(),
1315 stop_frame_sp,
1316 bp_loc_sp);
1317 python_interpreter->LeaveSession ();
1318 ReleasePythonLock ();
1319 }
1320 return ret_val;
Caroline Tice202f6b82011-01-17 21:55:19 +00001321 }
Caroline Tice0aa2e552011-01-14 00:29:16 +00001322 }
Greg Clayton5144f382010-10-07 17:14:24 +00001323 }
1324 // We currently always true so we stop in case anything goes wrong when
1325 // trying to call the script function
1326 return true;
1327}
Caroline Tice2ade6112010-11-10 19:18:14 +00001328
1329lldb::thread_result_t
1330ScriptInterpreterPython::RunEmbeddedPythonInterpreter (lldb::thread_arg_t baton)
1331{
1332 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
1333
1334 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
1335
1336 if (log)
1337 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread starting...", baton);
1338
1339 char error_str[1024];
1340 const char *pty_slave_name = script_interpreter->m_embedded_python_pty.GetSlaveName (error_str, sizeof (error_str));
Caroline Tice202f6b82011-01-17 21:55:19 +00001341 bool need_to_release_lock = true;
1342 bool safe_to_run = false;
Caroline Tice0aa2e552011-01-14 00:29:16 +00001343
Caroline Tice202f6b82011-01-17 21:55:19 +00001344 if (CurrentThreadHasPythonLock())
1345 {
1346 safe_to_run = true;
1347 need_to_release_lock = false;
1348 }
1349 else
1350 {
1351 int interval = 1;
1352 safe_to_run = GetPythonLock (interval);
1353 while (!safe_to_run)
1354 {
1355 interval = interval * 2;
1356 safe_to_run = GetPythonLock (interval);
1357 }
1358 }
1359
1360 if (pty_slave_name != NULL && safe_to_run)
1361 {
Caroline Tice2ade6112010-11-10 19:18:14 +00001362 StreamString run_string;
Caroline Tice2ade6112010-11-10 19:18:14 +00001363
Caroline Tice202f6b82011-01-17 21:55:19 +00001364 script_interpreter->EnterSession ();
1365
Caroline Tice0aa2e552011-01-14 00:29:16 +00001366 run_string.Printf ("run_one_line (%s, 'save_stderr = sys.stderr')", script_interpreter->m_dictionary_name.c_str());
1367 PyRun_SimpleString (run_string.GetData());
1368 run_string.Clear ();
1369
1370 run_string.Printf ("run_one_line (%s, 'sys.stderr = sys.stdout')", script_interpreter->m_dictionary_name.c_str());
1371 PyRun_SimpleString (run_string.GetData());
1372 run_string.Clear ();
1373
1374 run_string.Printf ("run_one_line (%s, 'save_stdin = sys.stdin')", script_interpreter->m_dictionary_name.c_str());
1375 PyRun_SimpleString (run_string.GetData());
1376 run_string.Clear ();
1377
1378 run_string.Printf ("run_one_line (%s, \"sys.stdin = open ('%s', 'r')\")", script_interpreter->m_dictionary_name.c_str(),
1379 pty_slave_name);
1380 PyRun_SimpleString (run_string.GetData());
1381 run_string.Clear ();
1382
Johnny Chen8054ba32011-03-11 00:28:50 +00001383 // The following call drops into the embedded interpreter loop and stays there until the
1384 // user chooses to exit from the Python interpreter.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001385
Caroline Ticece207c12011-03-11 00:21:55 +00001386 // When in the embedded interpreter, the user can call arbitrary system and Python stuff, which may require
Johnny Chen8054ba32011-03-11 00:28:50 +00001387 // 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 +00001388 // calls to Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS.
1389
1390 // We ALSO need to surround the call to the embedded interpreter with calls to PyGILState_Ensure and
1391 // PyGILState_Release. This is because this embedded interpreter is being run on a DIFFERENT THREAD than
1392 // the thread on which the call to Py_Initialize (and PyEval_InitThreads) was called. Those initializations
1393 // called PyGILState_Ensure on *that* thread, but it also needs to be called on *this* thread. Otherwise,
1394 // if the user calls Python code that does threading stuff, the interpreter state will be off, and things could
1395 // hang (it's happened before).
1396
Caroline Tice9d352ce2011-03-07 23:24:28 +00001397 Py_BEGIN_ALLOW_THREADS
1398 PyGILState_STATE gstate = PyGILState_Ensure();
1399
Caroline Tice0aa2e552011-01-14 00:29:16 +00001400 run_string.Printf ("run_python_interpreter (%s)", script_interpreter->m_dictionary_name.c_str());
1401 PyRun_SimpleString (run_string.GetData());
1402 run_string.Clear ();
Caroline Tice2ade6112010-11-10 19:18:14 +00001403
Caroline Tice9d352ce2011-03-07 23:24:28 +00001404 PyGILState_Release (gstate);
1405 Py_END_ALLOW_THREADS
1406
Caroline Tice0aa2e552011-01-14 00:29:16 +00001407 run_string.Printf ("run_one_line (%s, 'sys.stdin = save_stdin')", script_interpreter->m_dictionary_name.c_str());
1408 PyRun_SimpleString (run_string.GetData());
1409 run_string.Clear();
1410
1411 run_string.Printf ("run_one_line (%s, 'sys.stderr = save_stderr')", script_interpreter->m_dictionary_name.c_str());
1412 PyRun_SimpleString (run_string.GetData());
1413 run_string.Clear();
Caroline Tice202f6b82011-01-17 21:55:19 +00001414
1415 script_interpreter->LeaveSession ();
1416
Caroline Tice2ade6112010-11-10 19:18:14 +00001417 }
1418
Caroline Tice202f6b82011-01-17 21:55:19 +00001419 if (!safe_to_run)
1420 fprintf ((script_interpreter->m_dbg_stdout ? script_interpreter->m_dbg_stdout : stdout),
1421 "Python interpreter locked on another thread; unable to acquire lock.\n");
1422
1423 if (need_to_release_lock)
1424 ReleasePythonLock ();
1425
Caroline Tice2ade6112010-11-10 19:18:14 +00001426 if (script_interpreter->m_embedded_thread_input_reader_sp)
1427 script_interpreter->m_embedded_thread_input_reader_sp->SetIsDone (true);
1428
1429 script_interpreter->m_embedded_python_pty.CloseSlaveFileDescriptor();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001430
1431 script_interpreter->m_pty_slave_is_open = false;
Caroline Tice2ade6112010-11-10 19:18:14 +00001432
1433 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT);
1434 if (log)
1435 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread exiting...", baton);
1436
1437
Johnny Chen8054ba32011-03-11 00:28:50 +00001438 // Clean up the input reader and make the debugger pop it off the stack.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001439 Debugger &debugger = script_interpreter->GetCommandInterpreter().GetDebugger();
Caroline Tice2ade6112010-11-10 19:18:14 +00001440 const InputReaderSP reader_sp = script_interpreter->m_embedded_thread_input_reader_sp;
1441 script_interpreter->m_embedded_thread_input_reader_sp.reset();
1442 debugger.PopInputReader (reader_sp);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001443
Caroline Tice2ade6112010-11-10 19:18:14 +00001444 return NULL;
1445}
1446
1447
Caroline Tice0aa2e552011-01-14 00:29:16 +00001448void
Greg Claytone86cbb92011-03-22 01:14:58 +00001449ScriptInterpreterPython::InitializeInterpreter (SWIGInitCallback python_swig_init_callback,
1450 SWIGBreakpointCallbackFunction python_swig_breakpoint_callback)
1451{
1452 g_swig_init_callback = python_swig_init_callback;
1453 g_swig_breakpoint_callback = python_swig_breakpoint_callback;
1454}
1455
1456void
1457ScriptInterpreterPython::InitializePrivate ()
Caroline Tice0aa2e552011-01-14 00:29:16 +00001458{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001459 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
1460
Greg Clayton0fdd4a02011-02-07 23:24:47 +00001461 // Python will muck with STDIN terminal state, so save off any current TTY
1462 // settings so we can restore them.
1463 TerminalState stdin_tty_state;
1464 stdin_tty_state.Save(STDIN_FILENO, false);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001465
1466 // Find the module that owns this code and use that path we get to
1467 // set the PYTHONPATH appropriately.
1468
1469 FileSpec file_spec;
1470 char python_dir_path[PATH_MAX];
1471 if (Host::GetLLDBPath (ePathTypePythonDir, file_spec))
1472 {
1473 std::string python_path;
1474 const char *curr_python_path = ::getenv ("PYTHONPATH");
1475 if (curr_python_path)
1476 {
1477 // We have a current value for PYTHONPATH, so lets append to it
1478 python_path.append (curr_python_path);
1479 }
1480
1481 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
1482 {
1483 if (!python_path.empty())
1484 python_path.append (1, ':');
1485 python_path.append (python_dir_path);
1486 }
1487
1488 if (Host::GetLLDBPath (ePathTypeLLDBShlibDir, file_spec))
1489 {
1490 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
1491 {
1492 if (!python_path.empty())
1493 python_path.append (1, ':');
1494 python_path.append (python_dir_path);
1495 }
1496 }
1497 const char *pathon_path_env_cstr = python_path.c_str();
1498 ::setenv ("PYTHONPATH", pathon_path_env_cstr, 1);
1499 }
1500
Caroline Tice9d352ce2011-03-07 23:24:28 +00001501 PyEval_InitThreads ();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001502 Py_Initialize ();
1503
1504 PyObject *compiled_module = Py_CompileString (embedded_interpreter_string,
1505 "embedded_interpreter.py",
1506 Py_file_input);
1507
1508 PyObject *py_error = PyErr_Occurred ();
1509 if (py_error != NULL)
1510 {
1511 PyErr_Print();
1512 PyErr_Clear();
1513 }
1514
1515
Greg Claytone86cbb92011-03-22 01:14:58 +00001516 // Initialize SWIG after setting up python
1517 assert (g_swig_init_callback != NULL);
1518 g_swig_init_callback ();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001519
1520 // Update the path python uses to search for modules to include the current directory.
1521
1522 int success = PyRun_SimpleString ("import sys");
1523 success = PyRun_SimpleString ("sys.path.append ('.')");
1524
1525 PyObject *pmod = NULL;
1526
1527 if (compiled_module)
1528 {
1529 pmod = PyImport_ExecCodeModule (const_cast<char*> ("embedded_interpreter"),
1530 compiled_module);
1531 Py_DECREF (compiled_module);
1532 }
1533
1534 if (pmod != NULL)
1535 {
1536 PyRun_SimpleString ("from embedded_interpreter import run_python_interpreter");
1537 PyRun_SimpleString ("from embedded_interpreter import run_one_line");
1538 PyRun_SimpleString ("import sys");
1539 PyRun_SimpleString ("from termios import *");
1540 Py_DECREF (pmod);
1541 }
Greg Clayton99208582011-02-07 19:04:58 +00001542
Greg Clayton0fdd4a02011-02-07 23:24:47 +00001543 stdin_tty_state.Restore();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001544}
1545
Greg Claytone86cbb92011-03-22 01:14:58 +00001546//void
1547//ScriptInterpreterPython::Terminate ()
1548//{
1549// // We are intentionally NOT calling Py_Finalize here (this would be the logical place to call it). Calling
1550// // Py_Finalize here causes test suite runs to seg fault: The test suite runs in Python. It registers
1551// // SBDebugger::Terminate to be called 'at_exit'. When the test suite Python harness finishes up, it calls
1552// // Py_Finalize, which calls all the 'at_exit' registered functions. SBDebugger::Terminate calls Debugger::Terminate,
1553// // which calls lldb::Terminate, which calls ScriptInterpreter::Terminate, which calls
1554// // ScriptInterpreterPython::Terminate. So if we call Py_Finalize here, we end up with Py_Finalize being called from
1555// // within Py_Finalize, which results in a seg fault.
1556// //
1557// // Since this function only gets called when lldb is shutting down and going away anyway, the fact that we don't
1558// // actually call Py_Finalize should not cause any problems (everything should shut down/go away anyway when the
1559// // process exits).
1560// //
1561//// Py_Finalize ();
1562//}