blob: 91fb9273b156a7455a0191c717cc0bff72e106f7 [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
Enrico Granata91544802011-09-06 19:20:51 +000021#include "lldb/API/SBValue.h"
Greg Clayton987c7eb2011-09-17 08:33:22 +000022#include "lldb/Breakpoint/BreakpointLocation.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;
Enrico Granataf7a9b142011-07-15 02:26:42 +000037static ScriptInterpreter::SWIGPythonTypeScriptCallbackFunction g_swig_typescript_callback = NULL;
Enrico Granata9ae7cef2011-07-24 00:14:56 +000038static ScriptInterpreter::SWIGPythonCreateSyntheticProvider g_swig_synthetic_script = NULL;
39static ScriptInterpreter::SWIGPythonCalculateNumChildren g_swig_calc_children = NULL;
40static ScriptInterpreter::SWIGPythonGetChildAtIndex g_swig_get_child_index = NULL;
41static ScriptInterpreter::SWIGPythonGetIndexOfChildWithName g_swig_get_index_child = NULL;
42static ScriptInterpreter::SWIGPythonCastPyObjectToSBValue g_swig_cast_to_sbvalue = NULL;
Enrico Granata979e20d2011-07-29 19:53:35 +000043static ScriptInterpreter::SWIGPythonUpdateSynthProviderInstance g_swig_update_provider = NULL;
Enrico Granatac2a28252011-08-16 16:49:25 +000044static ScriptInterpreter::SWIGPythonCallCommand g_swig_call_command = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +000045
46static int
47_check_and_flush (FILE *stream)
48{
49 int prev_fail = ferror (stream);
50 return fflush (stream) || prev_fail ? EOF : 0;
51}
52
Caroline Tice202f6b82011-01-17 21:55:19 +000053static Predicate<lldb::tid_t> &
54PythonMutexPredicate ()
Caroline Tice0aa2e552011-01-14 00:29:16 +000055{
Caroline Tice202f6b82011-01-17 21:55:19 +000056 static lldb_private::Predicate<lldb::tid_t> g_interpreter_is_running (LLDB_INVALID_THREAD_ID);
57 return g_interpreter_is_running;
58}
59
60static bool
61CurrentThreadHasPythonLock ()
62{
63 TimeValue timeout;
64
65 timeout = TimeValue::Now(); // Don't wait any time.
66
67 return PythonMutexPredicate().WaitForValueEqualTo (Host::GetCurrentThreadID(), &timeout, NULL);
68}
69
70static bool
71GetPythonLock (uint32_t seconds_to_wait)
72{
73
74 TimeValue timeout;
75
76 if (seconds_to_wait != UINT32_MAX)
77 {
78 timeout = TimeValue::Now();
79 timeout.OffsetWithSeconds (seconds_to_wait);
80 }
81
82 return PythonMutexPredicate().WaitForValueEqualToAndSetValueTo (LLDB_INVALID_THREAD_ID,
83 Host::GetCurrentThreadID(), &timeout, NULL);
84}
85
86static void
87ReleasePythonLock ()
88{
89 PythonMutexPredicate().SetValue (LLDB_INVALID_THREAD_ID, eBroadcastAlways);
Caroline Tice0aa2e552011-01-14 00:29:16 +000090}
91
Enrico Granata91544802011-09-06 19:20:51 +000092ScriptInterpreterPython::Locker::Locker (ScriptInterpreterPython *pi,
93 FILE* tmp_fh,
94 bool ns) :
95 m_need_session(ns),
96 m_release_lock(false),
97 m_python_interpreter(pi),
98 m_tmp_fh(tmp_fh)
99{
100 // if Enter/LeaveSession() must be called, then m_python_interpreter must be != NULL
101 assert(m_need_session && m_python_interpreter);
102 if (!CurrentThreadHasPythonLock())
103 {
104 while (!GetPythonLock (1))
105 if (tmp_fh)
106 fprintf (tmp_fh,
107 "Python interpreter locked on another thread; waiting to acquire lock...\n");
108 m_release_lock = true;
109 }
110 if (m_need_session)
111 m_python_interpreter->EnterSession ();
112}
113
114ScriptInterpreterPython::Locker::~Locker()
115{
116 if (m_need_session)
117 m_python_interpreter->LeaveSession ();
118 if (m_release_lock)
119 ReleasePythonLock ();
120}
121
Greg Clayton63094e02010-06-23 01:19:29 +0000122ScriptInterpreterPython::ScriptInterpreterPython (CommandInterpreter &interpreter) :
Greg Clayton238c0a12010-09-18 01:14:36 +0000123 ScriptInterpreter (interpreter, eScriptLanguagePython),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000124 m_embedded_python_pty (),
125 m_embedded_thread_input_reader_sp (),
Greg Clayton58928562011-02-09 01:08:52 +0000126 m_dbg_stdout (interpreter.GetDebugger().GetOutputFile().GetStream()),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000127 m_new_sysout (NULL),
128 m_dictionary_name (interpreter.GetDebugger().GetInstanceName().AsCString()),
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000129 m_terminal_state (),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000130 m_session_is_active (false),
131 m_pty_slave_is_open (false),
132 m_valid_session (true)
Chris Lattner24943d22010-06-08 16:52:24 +0000133{
134
Greg Clayton7c330d62011-01-27 01:01:10 +0000135 static int g_initialized = false;
136
137 if (!g_initialized)
138 {
139 g_initialized = true;
Greg Claytone86cbb92011-03-22 01:14:58 +0000140 ScriptInterpreterPython::InitializePrivate ();
Greg Clayton7c330d62011-01-27 01:01:10 +0000141 }
142
Caroline Tice202f6b82011-01-17 21:55:19 +0000143 bool safe_to_run = false;
144 bool need_to_release_lock = true;
145 int interval = 5; // Number of seconds to try getting the Python lock before timing out.
146
147 // We don't dare exit this function without finishing setting up the script interpreter, so we must wait until
148 // we can get the Python lock.
149
150 if (CurrentThreadHasPythonLock())
151 {
152 safe_to_run = true;
153 need_to_release_lock = false;
154 }
155
156 while (!safe_to_run)
157 {
158 safe_to_run = GetPythonLock (interval);
159 if (!safe_to_run)
160 {
161 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
162 fprintf (tmp_fh,
163 "Python interpreter is locked on another thread; "
164 "please release interpreter in order to continue.\n");
165 interval = interval * 2;
166 }
167 }
168
Caroline Tice0aa2e552011-01-14 00:29:16 +0000169 m_dictionary_name.append("_dict");
170 StreamString run_string;
171 run_string.Printf ("%s = dict()", m_dictionary_name.c_str());
172 PyRun_SimpleString (run_string.GetData());
Caroline Tice5867f6b2010-10-18 18:24:17 +0000173
Caroline Tice0aa2e552011-01-14 00:29:16 +0000174 run_string.Clear();
175 run_string.Printf ("run_one_line (%s, 'import sys')", m_dictionary_name.c_str());
176 PyRun_SimpleString (run_string.GetData());
177
178 // Importing 'lldb' module calls SBDebugger::Initialize, which calls Debugger::Initialize, which increments a
179 // global debugger ref-count; therefore we need to check the ref-count before and after importing lldb, and if the
180 // ref-count increased we need to call Debugger::Terminate here to decrement the ref-count so that when the final
181 // call to Debugger::Terminate is made, the ref-count has the correct value.
182 //
183 // Bonus question: Why doesn't the ref-count always increase? Because sometimes lldb has already been imported, in
184 // which case the code inside it, including the call to SBDebugger::Initialize(), does not get executed.
Caroline Tice5867f6b2010-10-18 18:24:17 +0000185
Caroline Tice0aa2e552011-01-14 00:29:16 +0000186 int old_count = Debugger::TestDebuggerRefCount();
Chris Lattner24943d22010-06-08 16:52:24 +0000187
Caroline Tice0aa2e552011-01-14 00:29:16 +0000188 run_string.Clear();
189 run_string.Printf ("run_one_line (%s, 'import lldb')", m_dictionary_name.c_str());
190 PyRun_SimpleString (run_string.GetData());
Greg Clayton24b48ff2010-10-17 22:03:32 +0000191
Caroline Tice0aa2e552011-01-14 00:29:16 +0000192 int new_count = Debugger::TestDebuggerRefCount();
Chris Lattner24943d22010-06-08 16:52:24 +0000193
Caroline Tice0aa2e552011-01-14 00:29:16 +0000194 if (new_count > old_count)
195 Debugger::Terminate();
Caroline Tice5867f6b2010-10-18 18:24:17 +0000196
Caroline Tice0aa2e552011-01-14 00:29:16 +0000197 run_string.Clear();
198 run_string.Printf ("run_one_line (%s, 'import copy')", m_dictionary_name.c_str());
199 PyRun_SimpleString (run_string.GetData());
200
201 run_string.Clear();
202 run_string.Printf ("run_one_line (%s, 'lldb.debugger_unique_id = %d')", m_dictionary_name.c_str(),
203 interpreter.GetDebugger().GetID());
204 PyRun_SimpleString (run_string.GetData());
205
Enrico Granata074e3b62011-08-17 19:07:52 +0000206 run_string.Clear();
Enrico Granata960691f2011-08-22 17:34:47 +0000207 run_string.Printf ("run_one_line (%s, 'import gnu_libstdcpp')", m_dictionary_name.c_str(),
Enrico Granata074e3b62011-08-17 19:07:52 +0000208 interpreter.GetDebugger().GetID());
209 PyRun_SimpleString (run_string.GetData());
210
Caroline Tice0aa2e552011-01-14 00:29:16 +0000211 if (m_dbg_stdout != NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000212 {
Caroline Tice0aa2e552011-01-14 00:29:16 +0000213 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
Caroline Tice5867f6b2010-10-18 18:24:17 +0000214 }
Caroline Tice202f6b82011-01-17 21:55:19 +0000215
216 if (need_to_release_lock)
217 ReleasePythonLock();
Chris Lattner24943d22010-06-08 16:52:24 +0000218}
219
220ScriptInterpreterPython::~ScriptInterpreterPython ()
221{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000222 Debugger &debugger = GetCommandInterpreter().GetDebugger();
223
224 if (m_embedded_thread_input_reader_sp.get() != NULL)
225 {
226 m_embedded_thread_input_reader_sp->SetIsDone (true);
227 m_embedded_python_pty.CloseSlaveFileDescriptor();
228 m_pty_slave_is_open = false;
229 const InputReaderSP reader_sp = m_embedded_thread_input_reader_sp;
230 m_embedded_thread_input_reader_sp.reset();
231 debugger.PopInputReader (reader_sp);
232 }
233
234 if (m_new_sysout)
235 {
Caroline Tice202f6b82011-01-17 21:55:19 +0000236 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
237 if (!CurrentThreadHasPythonLock ())
238 {
239 while (!GetPythonLock (1))
240 fprintf (tmp_fh, "Python interpreter locked on another thread; waiting to acquire lock...\n");
241 Py_DECREF (m_new_sysout);
242 ReleasePythonLock ();
243 }
244 else
245 Py_DECREF (m_new_sysout);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000246 }
Chris Lattner24943d22010-06-08 16:52:24 +0000247}
248
Caroline Tice0aa2e552011-01-14 00:29:16 +0000249void
250ScriptInterpreterPython::ResetOutputFileHandle (FILE *fh)
251{
252 if (fh == NULL)
253 return;
254
255 m_dbg_stdout = fh;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000256
Caroline Tice202f6b82011-01-17 21:55:19 +0000257 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
Enrico Granata91544802011-09-06 19:20:51 +0000258
259 Locker py_lock(this, tmp_fh);
260
261 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000262}
263
264void
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000265ScriptInterpreterPython::SaveTerminalState (int fd)
266{
267 // Python mucks with the terminal state of STDIN. If we can possibly avoid
268 // this by setting the file handles up correctly prior to entering the
269 // interpreter we should. For now we save and restore the terminal state
270 // on the input file handle.
271 m_terminal_state.Save (fd, false);
272}
273
274void
275ScriptInterpreterPython::RestoreTerminalState ()
276{
277 // Python mucks with the terminal state of STDIN. If we can possibly avoid
278 // this by setting the file handles up correctly prior to entering the
279 // interpreter we should. For now we save and restore the terminal state
280 // on the input file handle.
281 m_terminal_state.Restore();
282}
283
284
285
286void
Caroline Tice0aa2e552011-01-14 00:29:16 +0000287ScriptInterpreterPython::LeaveSession ()
288{
289 m_session_is_active = false;
290}
291
292void
293ScriptInterpreterPython::EnterSession ()
294{
295 // If we have already entered the session, without having officially 'left' it, then there is no need to
296 // 'enter' it again.
297
298 if (m_session_is_active)
299 return;
300
301 m_session_is_active = true;
302
Caroline Tice202f6b82011-01-17 21:55:19 +0000303 StreamString run_string;
304
305 run_string.Printf ("run_one_line (%s, 'lldb.debugger_unique_id = %d')", m_dictionary_name.c_str(),
306 GetCommandInterpreter().GetDebugger().GetID());
307 PyRun_SimpleString (run_string.GetData());
Caroline Tice6af65cb2011-05-03 21:21:50 +0000308 run_string.Clear();
Caroline Tice202f6b82011-01-17 21:55:19 +0000309
Caroline Tice0aa2e552011-01-14 00:29:16 +0000310
Caroline Tice6af65cb2011-05-03 21:21:50 +0000311 run_string.Printf ("run_one_line (%s, 'lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%d)')",
312 m_dictionary_name.c_str(),
313 GetCommandInterpreter().GetDebugger().GetID());
314 PyRun_SimpleString (run_string.GetData());
315 run_string.Clear();
316
317
318 ExecutionContext exe_ctx = m_interpreter.GetDebugger().GetSelectedExecutionContext();
319
320 if (exe_ctx.target)
321 run_string.Printf ("run_one_line (%s, 'lldb.target = lldb.debugger.GetSelectedTarget()')",
322 m_dictionary_name.c_str());
323 else
324 run_string.Printf ("run_one_line (%s, 'lldb.target = None')", m_dictionary_name.c_str());
325 PyRun_SimpleString (run_string.GetData());
326 run_string.Clear();
327
328 if (exe_ctx.process)
329 run_string.Printf ("run_one_line (%s, 'lldb.process = lldb.target.GetProcess()')", m_dictionary_name.c_str());
330 else
331 run_string.Printf ("run_one_line (%s, 'lldb.process = None')", m_dictionary_name.c_str());
332 PyRun_SimpleString (run_string.GetData());
333 run_string.Clear();
334
335 if (exe_ctx.thread)
336 run_string.Printf ("run_one_line (%s, 'lldb.thread = lldb.process.GetSelectedThread ()')",
337 m_dictionary_name.c_str());
338 else
339 run_string.Printf ("run_one_line (%s, 'lldb.thread = None')", m_dictionary_name.c_str());
340 PyRun_SimpleString (run_string.GetData());
341 run_string.Clear();
342
343 if (exe_ctx.frame)
344 run_string.Printf ("run_one_line (%s, 'lldb.frame = lldb.thread.GetSelectedFrame ()')",
345 m_dictionary_name.c_str());
346 else
347 run_string.Printf ("run_one_line (%s, 'lldb.frame = None')", m_dictionary_name.c_str());
348 PyRun_SimpleString (run_string.GetData());
349 run_string.Clear();
350
Caroline Tice0aa2e552011-01-14 00:29:16 +0000351 PyObject *sysmod = PyImport_AddModule ("sys");
352 PyObject *sysdict = PyModule_GetDict (sysmod);
353
354 if ((m_new_sysout != NULL)
355 && (sysmod != NULL)
356 && (sysdict != NULL))
357 PyDict_SetItemString (sysdict, "stdout", m_new_sysout);
358
359 if (PyErr_Occurred())
360 PyErr_Clear ();
361
Caroline Tice0aa2e552011-01-14 00:29:16 +0000362 if (!m_pty_slave_is_open)
363 {
Caroline Tice202f6b82011-01-17 21:55:19 +0000364 run_string.Clear();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000365 run_string.Printf ("run_one_line (%s, \"new_stdin = open('%s', 'r')\")", m_dictionary_name.c_str(),
366 m_pty_slave_name.c_str());
367 PyRun_SimpleString (run_string.GetData());
368 m_pty_slave_is_open = true;
369
370 run_string.Clear();
371 run_string.Printf ("run_one_line (%s, 'sys.stdin = new_stdin')", m_dictionary_name.c_str());
372 PyRun_SimpleString (run_string.GetData());
373 }
374}
375
376
Johnny Chen60dde642010-07-30 22:33:14 +0000377bool
Greg Clayton238c0a12010-09-18 01:14:36 +0000378ScriptInterpreterPython::ExecuteOneLine (const char *command, CommandReturnObject *result)
Chris Lattner24943d22010-06-08 16:52:24 +0000379{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000380 if (!m_valid_session)
381 return false;
382
Caroline Tice0aa2e552011-01-14 00:29:16 +0000383
Caroline Tice0aa2e552011-01-14 00:29:16 +0000384
Caroline Tice4a461da2011-01-14 21:09:29 +0000385 // We want to call run_one_line, passing in the dictionary and the command string. We cannot do this through
386 // PyRun_SimpleString here because the command string may contain escaped characters, and putting it inside
387 // another string to pass to PyRun_SimpleString messes up the escaping. So we use the following more complicated
388 // method to pass the command string directly down to Python.
389
390
Caroline Tice202f6b82011-01-17 21:55:19 +0000391 bool need_to_release_lock = true;
392
393 if (CurrentThreadHasPythonLock())
394 need_to_release_lock = false;
395 else if (!GetPythonLock (1))
396 {
397 fprintf ((m_dbg_stdout ? m_dbg_stdout : stdout),
398 "Python interpreter is currently locked by another thread; unable to process command.\n");
399 return false;
400 }
401
402 EnterSession ();
Caroline Tice4a461da2011-01-14 21:09:29 +0000403 bool success = false;
404
Greg Clayton63094e02010-06-23 01:19:29 +0000405 if (command)
Chris Lattner24943d22010-06-08 16:52:24 +0000406 {
Caroline Tice4a461da2011-01-14 21:09:29 +0000407 // Find the correct script interpreter dictionary in the main module.
408 PyObject *main_mod = PyImport_AddModule ("__main__");
409 PyObject *script_interpreter_dict = NULL;
410 if (main_mod != NULL)
411 {
412 PyObject *main_dict = PyModule_GetDict (main_mod);
413 if ((main_dict != NULL)
414 && PyDict_Check (main_dict))
415 {
416 // Go through the main dictionary looking for the correct python script interpreter dictionary
417 PyObject *key, *value;
418 Py_ssize_t pos = 0;
419
420 while (PyDict_Next (main_dict, &pos, &key, &value))
421 {
422 // We have stolen references to the key and value objects in the dictionary; we need to increment
423 // them now so that Python's garbage collector doesn't collect them out from under us.
424 Py_INCREF (key);
425 Py_INCREF (value);
426 if (strcmp (PyString_AsString (key), m_dictionary_name.c_str()) == 0)
427 {
428 script_interpreter_dict = value;
429 break;
430 }
431 }
432 }
433
434 if (script_interpreter_dict != NULL)
435 {
436 PyObject *pfunc = NULL;
437 PyObject *pmod = PyImport_AddModule ("embedded_interpreter");
438 if (pmod != NULL)
439 {
440 PyObject *pmod_dict = PyModule_GetDict (pmod);
441 if ((pmod_dict != NULL)
442 && PyDict_Check (pmod_dict))
443 {
444 PyObject *key, *value;
445 Py_ssize_t pos = 0;
446
447 while (PyDict_Next (pmod_dict, &pos, &key, &value))
448 {
449 Py_INCREF (key);
450 Py_INCREF (value);
451 if (strcmp (PyString_AsString (key), "run_one_line") == 0)
452 {
453 pfunc = value;
454 break;
455 }
456 }
457
458 PyObject *string_arg = PyString_FromString (command);
459 if (pfunc && string_arg && PyCallable_Check (pfunc))
460 {
461 PyObject *pargs = PyTuple_New (2);
462 if (pargs != NULL)
463 {
464 PyTuple_SetItem (pargs, 0, script_interpreter_dict);
465 PyTuple_SetItem (pargs, 1, string_arg);
466 PyObject *pvalue = PyObject_CallObject (pfunc, pargs);
467 Py_DECREF (pargs);
468 if (pvalue != NULL)
469 {
470 Py_DECREF (pvalue);
471 success = true;
472 }
473 else if (PyErr_Occurred ())
474 {
475 PyErr_Print();
476 PyErr_Clear();
477 }
478 }
479 }
480 }
481 }
482 Py_INCREF (script_interpreter_dict);
483 }
484 }
Greg Clayton63094e02010-06-23 01:19:29 +0000485
Caroline Tice0aa2e552011-01-14 00:29:16 +0000486 LeaveSession ();
487
Caroline Tice202f6b82011-01-17 21:55:19 +0000488 if (need_to_release_lock)
489 ReleasePythonLock();
490
Caroline Tice4a461da2011-01-14 21:09:29 +0000491 if (success)
Johnny Chen60dde642010-07-30 22:33:14 +0000492 return true;
493
494 // The one-liner failed. Append the error message.
495 if (result)
496 result->AppendErrorWithFormat ("python failed attempting to evaluate '%s'\n", command);
497 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000498 }
Johnny Chen60dde642010-07-30 22:33:14 +0000499
Caroline Tice0aa2e552011-01-14 00:29:16 +0000500 LeaveSession ();
Caroline Tice202f6b82011-01-17 21:55:19 +0000501
502 if (need_to_release_lock)
503 ReleasePythonLock ();
504
Johnny Chen60dde642010-07-30 22:33:14 +0000505 if (result)
506 result->AppendError ("empty command passed to python\n");
507 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000508}
509
510
511
512size_t
513ScriptInterpreterPython::InputReaderCallback
514(
515 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000516 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000517 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000518 const char *bytes,
519 size_t bytes_len
520)
521{
Caroline Tice2ade6112010-11-10 19:18:14 +0000522 lldb::thread_t embedded_interpreter_thread;
523 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
524
Chris Lattner24943d22010-06-08 16:52:24 +0000525 if (baton == NULL)
526 return 0;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000527
528 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
529
530 if (script_interpreter->m_script_lang != eScriptLanguagePython)
531 return 0;
532
Caroline Tice892fadd2011-06-16 16:27:19 +0000533 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
534 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
535
Chris Lattner24943d22010-06-08 16:52:24 +0000536 switch (notification)
537 {
538 case eInputReaderActivate:
539 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000540 if (!batch_mode)
541 {
542 out_stream->Printf ("Python Interactive Interpreter. To exit, type 'quit()', 'exit()' or Ctrl-D.\n");
543 out_stream->Flush();
544 }
Greg Clayton58928562011-02-09 01:08:52 +0000545
Chris Lattner24943d22010-06-08 16:52:24 +0000546 // Save terminal settings if we can
Greg Clayton58928562011-02-09 01:08:52 +0000547 int input_fd = reader.GetDebugger().GetInputFile().GetDescriptor();
548 if (input_fd == File::kInvalidDescriptor)
Greg Clayton24b48ff2010-10-17 22:03:32 +0000549 input_fd = STDIN_FILENO;
Caroline Ticec95c6d12010-09-14 22:49:06 +0000550
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000551 script_interpreter->SaveTerminalState(input_fd);
Greg Clayton99208582011-02-07 19:04:58 +0000552
Caroline Tice202f6b82011-01-17 21:55:19 +0000553 if (!CurrentThreadHasPythonLock())
554 {
555 while (!GetPythonLock(1))
556 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000557 out_stream->Printf ("Python interpreter locked on another thread; waiting to acquire lock...\n");
558 out_stream->Flush();
Caroline Tice202f6b82011-01-17 21:55:19 +0000559 }
560 script_interpreter->EnterSession ();
561 ReleasePythonLock();
562 }
563 else
564 script_interpreter->EnterSession ();
565
Caroline Tice2ade6112010-11-10 19:18:14 +0000566 char error_str[1024];
567 if (script_interpreter->m_embedded_python_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, error_str,
568 sizeof(error_str)))
569 {
570 if (log)
571 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in opening master pty (fd = %d).",
572 script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor());
573 embedded_interpreter_thread = Host::ThreadCreate ("<lldb.script-interpreter.embedded-python-loop>",
574 ScriptInterpreterPython::RunEmbeddedPythonInterpreter,
575 script_interpreter, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +0000576 if (IS_VALID_LLDB_HOST_THREAD(embedded_interpreter_thread))
Caroline Tice2ade6112010-11-10 19:18:14 +0000577 {
578 if (log)
579 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in creating thread (thread = %d)", embedded_interpreter_thread);
580 Error detach_error;
581 Host::ThreadDetach (embedded_interpreter_thread, &detach_error);
582 }
583 else
584 {
585 if (log)
586 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed in creating thread");
587 reader.SetIsDone (true);
588 }
589 }
590 else
591 {
592 if (log)
593 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed to open master pty ");
594 reader.SetIsDone (true);
595 }
Chris Lattner24943d22010-06-08 16:52:24 +0000596 }
597 break;
598
599 case eInputReaderDeactivate:
Caroline Tice0aa2e552011-01-14 00:29:16 +0000600 script_interpreter->LeaveSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000601 break;
602
603 case eInputReaderReactivate:
Caroline Tice202f6b82011-01-17 21:55:19 +0000604 if (!CurrentThreadHasPythonLock())
605 {
606 while (!GetPythonLock(1))
607 {
608 // Wait until lock is acquired.
609 }
610 script_interpreter->EnterSession ();
611 ReleasePythonLock();
612 }
613 else
614 script_interpreter->EnterSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000615 break;
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000616
Caroline Tice4a348082011-05-02 20:41:46 +0000617 case eInputReaderAsynchronousOutputWritten:
618 break;
619
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000620 case eInputReaderInterrupt:
621 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "raise KeyboardInterrupt\n", 24);
622 break;
623
624 case eInputReaderEndOfFile:
625 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()\n", 7);
626 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000627
628 case eInputReaderGotToken:
Caroline Tice2ade6112010-11-10 19:18:14 +0000629 if (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor() != -1)
Chris Lattner24943d22010-06-08 16:52:24 +0000630 {
Caroline Tice2ade6112010-11-10 19:18:14 +0000631 if (log)
632 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %d", bytes,
633 bytes_len);
634 if (bytes && bytes_len)
635 {
636 if ((int) bytes[0] == 4)
637 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()", 6);
638 else
639 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), bytes, bytes_len);
640 }
641 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "\n", 1);
Chris Lattner24943d22010-06-08 16:52:24 +0000642 }
Caroline Tice2ade6112010-11-10 19:18:14 +0000643 else
644 {
645 if (log)
646 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %d, Master File Descriptor is bad.",
647 bytes,
648 bytes_len);
649 reader.SetIsDone (true);
650 }
651
Chris Lattner24943d22010-06-08 16:52:24 +0000652 break;
653
654 case eInputReaderDone:
Caroline Tice0aa2e552011-01-14 00:29:16 +0000655 script_interpreter->LeaveSession ();
656
Chris Lattner24943d22010-06-08 16:52:24 +0000657 // Restore terminal settings if they were validly saved
Caroline Tice2ade6112010-11-10 19:18:14 +0000658 if (log)
659 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Done, closing down input reader.");
Caroline Ticec95c6d12010-09-14 22:49:06 +0000660
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000661 script_interpreter->RestoreTerminalState ();
662
Caroline Tice2ade6112010-11-10 19:18:14 +0000663 script_interpreter->m_embedded_python_pty.CloseMasterFileDescriptor();
Chris Lattner24943d22010-06-08 16:52:24 +0000664 break;
665 }
666
667 return bytes_len;
668}
669
670
671void
Greg Clayton238c0a12010-09-18 01:14:36 +0000672ScriptInterpreterPython::ExecuteInterpreterLoop ()
Chris Lattner24943d22010-06-08 16:52:24 +0000673{
674 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
675
Caroline Tice0aa2e552011-01-14 00:29:16 +0000676 Debugger &debugger = GetCommandInterpreter().GetDebugger();
Caroline Ticec95c6d12010-09-14 22:49:06 +0000677
678 // At the moment, the only time the debugger does not have an input file handle is when this is called
679 // directly from Python, in which case it is both dangerous and unnecessary (not to mention confusing) to
680 // try to embed a running interpreter loop inside the already running Python interpreter loop, so we won't
681 // do it.
682
Greg Clayton58928562011-02-09 01:08:52 +0000683 if (!debugger.GetInputFile().IsValid())
Caroline Ticec95c6d12010-09-14 22:49:06 +0000684 return;
685
Greg Clayton63094e02010-06-23 01:19:29 +0000686 InputReaderSP reader_sp (new InputReader(debugger));
Chris Lattner24943d22010-06-08 16:52:24 +0000687 if (reader_sp)
688 {
689 Error error (reader_sp->Initialize (ScriptInterpreterPython::InputReaderCallback,
690 this, // baton
691 eInputReaderGranularityLine, // token size, to pass to callback function
692 NULL, // end token
693 NULL, // prompt
694 true)); // echo input
695
696 if (error.Success())
697 {
Greg Clayton63094e02010-06-23 01:19:29 +0000698 debugger.PushInputReader (reader_sp);
Caroline Tice2ade6112010-11-10 19:18:14 +0000699 m_embedded_thread_input_reader_sp = reader_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000700 }
701 }
702}
703
704bool
705ScriptInterpreterPython::ExecuteOneLineWithReturn (const char *in_string,
706 ScriptInterpreter::ReturnType return_type,
707 void *ret_value)
708{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000709
Caroline Tice202f6b82011-01-17 21:55:19 +0000710 bool need_to_release_lock = true;
711
712 if (CurrentThreadHasPythonLock())
713 need_to_release_lock = false;
714 else if (!GetPythonLock (1))
715 {
716 fprintf ((m_dbg_stdout ? m_dbg_stdout : stdout),
717 "Python interpreter is currently locked by another thread; unable to process command.\n");
718 return false;
719 }
720
721 EnterSession ();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000722
Chris Lattner24943d22010-06-08 16:52:24 +0000723 PyObject *py_return = NULL;
724 PyObject *mainmod = PyImport_AddModule ("__main__");
725 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000726 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000727 PyObject *py_error = NULL;
Johnny Chen60a7df52011-08-11 19:17:45 +0000728 bool ret_success = false;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000729 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000730 int success;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000731
732 if (PyDict_Check (globals))
733 {
734 PyObject *key, *value;
735 Py_ssize_t pos = 0;
736
737 int i = 0;
738 while (PyDict_Next (globals, &pos, &key, &value))
739 {
740 // We have stolen references to the key and value objects in the dictionary; we need to increment them now
741 // so that Python's garbage collector doesn't collect them out from under us.
742 Py_INCREF (key);
743 Py_INCREF (value);
744 char *c_str = PyString_AsString (key);
745 if (strcmp (c_str, m_dictionary_name.c_str()) == 0)
746 locals = value;
747 ++i;
748 }
749 }
Chris Lattner24943d22010-06-08 16:52:24 +0000750
Caroline Tice0aa2e552011-01-14 00:29:16 +0000751 if (locals == NULL)
752 {
753 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
754 should_decrement_locals = true;
755 }
756
757 if (locals == NULL)
758 {
759 locals = globals;
760 should_decrement_locals = false;
761 }
762
763 py_error = PyErr_Occurred();
764 if (py_error != NULL)
765 PyErr_Clear();
766
Chris Lattner24943d22010-06-08 16:52:24 +0000767 if (in_string != NULL)
768 {
769 py_return = PyRun_String (in_string, Py_eval_input, globals, locals);
770 if (py_return == NULL)
771 {
772 py_error = PyErr_Occurred ();
773 if (py_error != NULL)
774 PyErr_Clear ();
775
776 py_return = PyRun_String (in_string, Py_single_input, globals, locals);
777 }
778
Caroline Tice0aa2e552011-01-14 00:29:16 +0000779 if (locals != NULL
780 && should_decrement_locals)
781 Py_DECREF (locals);
782
Chris Lattner24943d22010-06-08 16:52:24 +0000783 if (py_return != NULL)
784 {
785 switch (return_type)
786 {
787 case eCharPtr: // "char *"
788 {
789 const char format[3] = "s#";
Enrico Granatae5e34cb2011-08-17 01:30:04 +0000790 success = PyArg_Parse (py_return, format, (char **) ret_value);
Chris Lattner24943d22010-06-08 16:52:24 +0000791 break;
792 }
Enrico Granatac2a28252011-08-16 16:49:25 +0000793 case eCharStrOrNone: // char* or NULL if py_return == Py_None
794 {
795 const char format[3] = "z";
Enrico Granatae5e34cb2011-08-17 01:30:04 +0000796 success = PyArg_Parse (py_return, format, (char **) ret_value);
Enrico Granatac2a28252011-08-16 16:49:25 +0000797 break;
798 }
Chris Lattner24943d22010-06-08 16:52:24 +0000799 case eBool:
800 {
801 const char format[2] = "b";
802 success = PyArg_Parse (py_return, format, (bool *) ret_value);
803 break;
804 }
805 case eShortInt:
806 {
807 const char format[2] = "h";
808 success = PyArg_Parse (py_return, format, (short *) ret_value);
809 break;
810 }
811 case eShortIntUnsigned:
812 {
813 const char format[2] = "H";
814 success = PyArg_Parse (py_return, format, (unsigned short *) ret_value);
815 break;
816 }
817 case eInt:
818 {
819 const char format[2] = "i";
820 success = PyArg_Parse (py_return, format, (int *) ret_value);
821 break;
822 }
823 case eIntUnsigned:
824 {
825 const char format[2] = "I";
826 success = PyArg_Parse (py_return, format, (unsigned int *) ret_value);
827 break;
828 }
829 case eLongInt:
830 {
831 const char format[2] = "l";
832 success = PyArg_Parse (py_return, format, (long *) ret_value);
833 break;
834 }
835 case eLongIntUnsigned:
836 {
837 const char format[2] = "k";
838 success = PyArg_Parse (py_return, format, (unsigned long *) ret_value);
839 break;
840 }
841 case eLongLong:
842 {
843 const char format[2] = "L";
844 success = PyArg_Parse (py_return, format, (long long *) ret_value);
845 break;
846 }
847 case eLongLongUnsigned:
848 {
849 const char format[2] = "K";
850 success = PyArg_Parse (py_return, format, (unsigned long long *) ret_value);
851 break;
852 }
853 case eFloat:
854 {
855 const char format[2] = "f";
856 success = PyArg_Parse (py_return, format, (float *) ret_value);
857 break;
858 }
859 case eDouble:
860 {
861 const char format[2] = "d";
862 success = PyArg_Parse (py_return, format, (double *) ret_value);
863 break;
864 }
865 case eChar:
866 {
867 const char format[2] = "c";
868 success = PyArg_Parse (py_return, format, (char *) ret_value);
869 break;
870 }
871 default:
872 {}
873 }
874 Py_DECREF (py_return);
875 if (success)
876 ret_success = true;
877 else
878 ret_success = false;
879 }
880 }
881
882 py_error = PyErr_Occurred();
883 if (py_error != NULL)
884 {
885 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
886 PyErr_Print ();
887 PyErr_Clear();
888 ret_success = false;
889 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000890
891 LeaveSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000892
Caroline Tice202f6b82011-01-17 21:55:19 +0000893 if (need_to_release_lock)
894 ReleasePythonLock();
895
Chris Lattner24943d22010-06-08 16:52:24 +0000896 return ret_success;
897}
898
899bool
900ScriptInterpreterPython::ExecuteMultipleLines (const char *in_string)
901{
Caroline Tice202f6b82011-01-17 21:55:19 +0000902 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
903 bool need_to_release_lock = true;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000904
Caroline Tice202f6b82011-01-17 21:55:19 +0000905 if (CurrentThreadHasPythonLock())
906 need_to_release_lock = false;
907 else
908 {
909 while (!GetPythonLock (1))
910 fprintf (tmp_fh, "Python interpreter locked on another thread; waiting to acquire lock...\n");
911 }
912
913 EnterSession ();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000914
Chris Lattner24943d22010-06-08 16:52:24 +0000915 bool success = false;
916 PyObject *py_return = NULL;
917 PyObject *mainmod = PyImport_AddModule ("__main__");
918 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000919 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000920 PyObject *py_error = NULL;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000921 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000922
Caroline Tice0aa2e552011-01-14 00:29:16 +0000923 if (PyDict_Check (globals))
924 {
925 PyObject *key, *value;
926 Py_ssize_t pos = 0;
927
928 while (PyDict_Next (globals, &pos, &key, &value))
929 {
930 // We have stolen references to the key and value objects in the dictionary; we need to increment them now
931 // so that Python's garbage collector doesn't collect them out from under us.
932 Py_INCREF (key);
933 Py_INCREF (value);
934 if (strcmp (PyString_AsString (key), m_dictionary_name.c_str()) == 0)
935 locals = value;
936 }
937 }
938
939 if (locals == NULL)
940 {
941 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
942 should_decrement_locals = true;
943 }
944
945 if (locals == NULL)
946 {
947 locals = globals;
948 should_decrement_locals = false;
949 }
950
951 py_error = PyErr_Occurred();
952 if (py_error != NULL)
953 PyErr_Clear();
954
Chris Lattner24943d22010-06-08 16:52:24 +0000955 if (in_string != NULL)
956 {
957 struct _node *compiled_node = PyParser_SimpleParseString (in_string, Py_file_input);
958 if (compiled_node)
959 {
960 PyCodeObject *compiled_code = PyNode_Compile (compiled_node, "temp.py");
961 if (compiled_code)
962 {
963 py_return = PyEval_EvalCode (compiled_code, globals, locals);
964 if (py_return != NULL)
965 {
966 success = true;
967 Py_DECREF (py_return);
968 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000969 if (locals && should_decrement_locals)
970 Py_DECREF (locals);
Chris Lattner24943d22010-06-08 16:52:24 +0000971 }
972 }
973 }
974
975 py_error = PyErr_Occurred ();
976 if (py_error != NULL)
977 {
978 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
979 PyErr_Print ();
980 PyErr_Clear();
981 success = false;
982 }
983
Caroline Tice0aa2e552011-01-14 00:29:16 +0000984 LeaveSession ();
985
Caroline Tice202f6b82011-01-17 21:55:19 +0000986 if (need_to_release_lock)
987 ReleasePythonLock();
988
Chris Lattner24943d22010-06-08 16:52:24 +0000989 return success;
990}
991
992static const char *g_reader_instructions = "Enter your Python command(s). Type 'DONE' to end.";
993
994size_t
995ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback
996(
997 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000998 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000999 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +00001000 const char *bytes,
1001 size_t bytes_len
1002)
1003{
Caroline Tice892fadd2011-06-16 16:27:19 +00001004 static StringList commands_in_progress;
1005
1006 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
1007 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
1008
Chris Lattner24943d22010-06-08 16:52:24 +00001009 switch (notification)
1010 {
1011 case eInputReaderActivate:
1012 {
1013 commands_in_progress.Clear();
Caroline Tice892fadd2011-06-16 16:27:19 +00001014 if (!batch_mode)
Chris Lattner24943d22010-06-08 16:52:24 +00001015 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001016 out_stream->Printf ("%s\n", g_reader_instructions);
Greg Clayton63094e02010-06-23 01:19:29 +00001017 if (reader.GetPrompt())
Caroline Tice892fadd2011-06-16 16:27:19 +00001018 out_stream->Printf ("%s", reader.GetPrompt());
1019 out_stream->Flush ();
Chris Lattner24943d22010-06-08 16:52:24 +00001020 }
1021 }
1022 break;
1023
1024 case eInputReaderDeactivate:
1025 break;
1026
1027 case eInputReaderReactivate:
Caroline Tice892fadd2011-06-16 16:27:19 +00001028 if (reader.GetPrompt() && !batch_mode)
Caroline Ticef81b4c52010-10-27 18:34:42 +00001029 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001030 out_stream->Printf ("%s", reader.GetPrompt());
1031 out_stream->Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +00001032 }
Chris Lattner24943d22010-06-08 16:52:24 +00001033 break;
1034
Caroline Tice4a348082011-05-02 20:41:46 +00001035 case eInputReaderAsynchronousOutputWritten:
1036 break;
1037
Chris Lattner24943d22010-06-08 16:52:24 +00001038 case eInputReaderGotToken:
1039 {
1040 std::string temp_string (bytes, bytes_len);
1041 commands_in_progress.AppendString (temp_string.c_str());
Caroline Tice892fadd2011-06-16 16:27:19 +00001042 if (!reader.IsDone() && reader.GetPrompt() && !batch_mode)
Caroline Ticef81b4c52010-10-27 18:34:42 +00001043 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001044 out_stream->Printf ("%s", reader.GetPrompt());
1045 out_stream->Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +00001046 }
Chris Lattner24943d22010-06-08 16:52:24 +00001047 }
1048 break;
1049
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001050 case eInputReaderEndOfFile:
1051 case eInputReaderInterrupt:
1052 // Control-c (SIGINT) & control-d both mean finish & exit.
1053 reader.SetIsDone(true);
1054
1055 // Control-c (SIGINT) ALSO means cancel; do NOT create a breakpoint command.
1056 if (notification == eInputReaderInterrupt)
1057 commands_in_progress.Clear();
1058
1059 // Fall through here...
1060
Chris Lattner24943d22010-06-08 16:52:24 +00001061 case eInputReaderDone:
1062 {
1063 BreakpointOptions *bp_options = (BreakpointOptions *)baton;
1064 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1065 data_ap->user_source.AppendList (commands_in_progress);
1066 if (data_ap.get())
1067 {
Greg Clayton63094e02010-06-23 01:19:29 +00001068 ScriptInterpreter *interpreter = reader.GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
Chris Lattner24943d22010-06-08 16:52:24 +00001069 if (interpreter)
1070 {
1071 if (interpreter->GenerateBreakpointCommandCallbackData (data_ap->user_source,
1072 data_ap->script_source))
1073 {
1074 if (data_ap->script_source.GetSize() == 1)
1075 {
1076 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1077 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
1078 }
1079 }
Caroline Tice892fadd2011-06-16 16:27:19 +00001080 else if (!batch_mode)
1081 {
1082 out_stream->Printf ("Warning: No command attached to breakpoint.\n");
1083 out_stream->Flush();
1084 }
Chris Lattner24943d22010-06-08 16:52:24 +00001085 }
1086 else
1087 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001088 if (!batch_mode)
1089 {
1090 out_stream->Printf ("Warning: Unable to find script intepreter; no command attached to breakpoint.\n");
1091 out_stream->Flush();
1092 }
Chris Lattner24943d22010-06-08 16:52:24 +00001093 }
1094 }
1095 }
1096 break;
1097
1098 }
1099
1100 return bytes_len;
1101}
1102
1103void
Greg Clayton238c0a12010-09-18 01:14:36 +00001104ScriptInterpreterPython::CollectDataForBreakpointCommandCallback (BreakpointOptions *bp_options,
Chris Lattner24943d22010-06-08 16:52:24 +00001105 CommandReturnObject &result)
1106{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001107 Debugger &debugger = GetCommandInterpreter().GetDebugger();
1108
Greg Clayton63094e02010-06-23 01:19:29 +00001109 InputReaderSP reader_sp (new InputReader (debugger));
Chris Lattner24943d22010-06-08 16:52:24 +00001110
1111 if (reader_sp)
1112 {
1113 Error err = reader_sp->Initialize (
1114 ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback,
1115 bp_options, // baton
1116 eInputReaderGranularityLine, // token size, for feeding data to callback function
1117 "DONE", // end token
1118 "> ", // prompt
1119 true); // echo input
1120
1121 if (err.Success())
Greg Clayton63094e02010-06-23 01:19:29 +00001122 debugger.PushInputReader (reader_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001123 else
1124 {
1125 result.AppendError (err.AsCString());
1126 result.SetStatus (eReturnStatusFailed);
1127 }
1128 }
1129 else
1130 {
1131 result.AppendError("out of memory");
1132 result.SetStatus (eReturnStatusFailed);
1133 }
1134}
1135
Johnny Chen3e0571b2010-09-11 00:23:59 +00001136// Set a Python one-liner as the callback for the breakpoint.
Johnny Chend1c2dca2010-09-10 18:21:10 +00001137void
Greg Clayton238c0a12010-09-18 01:14:36 +00001138ScriptInterpreterPython::SetBreakpointCommandCallback (BreakpointOptions *bp_options,
Johnny Chend1c2dca2010-09-10 18:21:10 +00001139 const char *oneliner)
1140{
1141 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1142
1143 // It's necessary to set both user_source and script_source to the oneliner.
1144 // The former is used to generate callback description (as in breakpoint command list)
1145 // while the latter is used for Python to interpret during the actual callback.
Caroline Tice5136f942010-09-27 21:35:15 +00001146
Johnny Chend1c2dca2010-09-10 18:21:10 +00001147 data_ap->user_source.AppendString (oneliner);
Johnny Chend1c2dca2010-09-10 18:21:10 +00001148
Caroline Tice5136f942010-09-27 21:35:15 +00001149 if (GenerateBreakpointCommandCallbackData (data_ap->user_source, data_ap->script_source))
1150 {
1151 if (data_ap->script_source.GetSize() == 1)
1152 {
1153 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1154 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
1155 }
1156 }
1157
Johnny Chend1c2dca2010-09-10 18:21:10 +00001158 return;
1159}
1160
Chris Lattner24943d22010-06-08 16:52:24 +00001161bool
1162ScriptInterpreterPython::ExportFunctionDefinitionToInterpreter (StringList &function_def)
1163{
1164 // Convert StringList to one long, newline delimited, const char *.
1165 std::string function_def_string;
1166
1167 int num_lines = function_def.GetSize();
1168
1169 for (int i = 0; i < num_lines; ++i)
1170 {
1171 function_def_string.append (function_def.GetStringAtIndex(i));
1172 if (function_def_string.at (function_def_string.length() - 1) != '\n')
1173 function_def_string.append ("\n");
1174
1175 }
1176
1177 return ExecuteMultipleLines (function_def_string.c_str());
1178}
1179
Enrico Granataf7a9b142011-07-15 02:26:42 +00001180// TODO move both GenerateTypeScriptFunction and GenerateBreakpointCommandCallbackData to actually
1181// use this code to generate their functions
1182bool
1183ScriptInterpreterPython::GenerateFunction(std::string& signature, StringList &input, StringList &output)
1184{
1185 int num_lines = input.GetSize ();
1186 if (num_lines == 0)
1187 return false;
1188 StreamString sstr;
1189 StringList auto_generated_function;
1190 auto_generated_function.AppendString (signature.c_str());
1191 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1192 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1193 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1194 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1195 // global dictionary.
1196
1197 // Wrap everything up inside the function, increasing the indentation.
1198
1199 for (int i = 0; i < num_lines; ++i)
1200 {
1201 sstr.Clear ();
1202 sstr.Printf (" %s", input.GetStringAtIndex (i));
1203 auto_generated_function.AppendString (sstr.GetData());
1204 }
1205 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1206 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1207 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1208 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1209
1210 // Verify that the results are valid Python.
1211
1212 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1213 return false;
1214
1215 return true;
1216
1217}
1218
1219// this implementation is identical to GenerateBreakpointCommandCallbackData (apart from the name
1220// given to generated functions, of course)
1221bool
1222ScriptInterpreterPython::GenerateTypeScriptFunction (StringList &user_input, StringList &output)
1223{
1224 static int num_created_functions = 0;
1225 user_input.RemoveBlankLines ();
1226 int num_lines = user_input.GetSize ();
1227 StreamString sstr;
1228
1229 // Check to see if we have any data; if not, just return.
1230 if (user_input.GetSize() == 0)
1231 return false;
1232
1233 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1234 // ValueObject as parameter to the function.
1235
1236 sstr.Printf ("lldb_autogen_python_type_print_func_%d", num_created_functions);
1237 ++num_created_functions;
1238 std::string auto_generated_function_name = sstr.GetData();
1239
1240 sstr.Clear();
1241 StringList auto_generated_function;
1242
1243 // Create the function name & definition string.
1244
1245 sstr.Printf ("def %s (valobj, dict):", auto_generated_function_name.c_str());
1246 auto_generated_function.AppendString (sstr.GetData());
1247
1248 // Pre-pend code for setting up the session dictionary.
1249
1250 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1251 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1252 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1253 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1254 // global dictionary.
1255
1256 // Wrap everything up inside the function, increasing the indentation.
1257
1258 for (int i = 0; i < num_lines; ++i)
1259 {
1260 sstr.Clear ();
1261 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1262 auto_generated_function.AppendString (sstr.GetData());
1263 }
1264
1265 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1266 // got written to the values in the global dictionary, not the session dictionary).
1267
1268 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1269 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1270 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1271 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1272
1273 // Verify that the results are valid Python.
1274
1275 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1276 return false;
1277
1278 // Store the name of the auto-generated function to be called.
1279
1280 output.AppendString (auto_generated_function_name.c_str());
1281 return true;
1282}
1283
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001284bool
Enrico Granatac2a28252011-08-16 16:49:25 +00001285ScriptInterpreterPython::GenerateScriptAliasFunction (StringList &user_input, StringList &output)
1286{
1287 static int num_created_functions = 0;
1288 user_input.RemoveBlankLines ();
1289 int num_lines = user_input.GetSize ();
1290 StreamString sstr;
1291
1292 // Check to see if we have any data; if not, just return.
1293 if (user_input.GetSize() == 0)
1294 return false;
1295
1296 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1297 // ValueObject as parameter to the function.
1298
1299 sstr.Printf ("lldb_autogen_python_cmd_alias_func_%d", num_created_functions);
1300 ++num_created_functions;
1301 std::string auto_generated_function_name = sstr.GetData();
1302
1303 sstr.Clear();
1304 StringList auto_generated_function;
1305
1306 // Create the function name & definition string.
1307
Enrico Granata271568f2011-09-09 01:41:30 +00001308 sstr.Printf ("def %s (debugger, args, result, dict):", auto_generated_function_name.c_str());
Enrico Granatac2a28252011-08-16 16:49:25 +00001309 auto_generated_function.AppendString (sstr.GetData());
1310
1311 // Pre-pend code for setting up the session dictionary.
1312
1313 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1314 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1315 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1316 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1317 // global dictionary.
1318
1319 // Wrap everything up inside the function, increasing the indentation.
1320
1321 for (int i = 0; i < num_lines; ++i)
1322 {
1323 sstr.Clear ();
1324 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1325 auto_generated_function.AppendString (sstr.GetData());
1326 }
1327
1328 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1329 // got written to the values in the global dictionary, not the session dictionary).
1330
1331 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1332 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1333 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1334 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1335
1336 // Verify that the results are valid Python.
1337
1338 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1339 return false;
1340
1341 // Store the name of the auto-generated function to be called.
1342
1343 output.AppendString (auto_generated_function_name.c_str());
1344 return true;
1345}
1346
1347
1348bool
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001349ScriptInterpreterPython::GenerateTypeSynthClass (StringList &user_input, StringList &output)
1350{
1351 static int num_created_classes = 0;
1352 user_input.RemoveBlankLines ();
1353 int num_lines = user_input.GetSize ();
1354 StreamString sstr;
1355
1356 // Check to see if we have any data; if not, just return.
1357 if (user_input.GetSize() == 0)
1358 return false;
1359
1360 // Wrap all user input into a Python class
1361
1362 sstr.Printf ("lldb_autogen_python_type_synth_class_%d", num_created_classes);
1363 ++num_created_classes;
1364 std::string auto_generated_class_name = sstr.GetData();
1365
1366 sstr.Clear();
1367 StringList auto_generated_class;
1368
1369 // Create the function name & definition string.
1370
1371 sstr.Printf ("class %s:", auto_generated_class_name.c_str());
1372 auto_generated_class.AppendString (sstr.GetData());
1373
1374 // Wrap everything up inside the class, increasing the indentation.
1375
1376 for (int i = 0; i < num_lines; ++i)
1377 {
1378 sstr.Clear ();
1379 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1380 auto_generated_class.AppendString (sstr.GetData());
1381 }
1382
1383
1384 // Verify that the results are valid Python.
1385 // (even though the method is ExportFunctionDefinitionToInterpreter, a class will actually be exported)
1386 // (TODO: rename that method to ExportDefinitionToInterpreter)
1387 if (!ExportFunctionDefinitionToInterpreter (auto_generated_class))
1388 return false;
1389
1390 // Store the name of the auto-generated class
1391
1392 output.AppendString (auto_generated_class_name.c_str());
1393 return true;
1394}
1395
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001396void*
1397ScriptInterpreterPython::CreateSyntheticScriptedProvider (std::string class_name,
1398 lldb::ValueObjectSP valobj)
1399{
1400 if (class_name.empty())
1401 return NULL;
1402
1403 if (!valobj.get())
1404 return NULL;
1405
Enrico Granata979e20d2011-07-29 19:53:35 +00001406 Target *target = valobj->GetUpdatePoint().GetTargetSP().get();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001407
1408 if (!target)
1409 return NULL;
1410
1411 Debugger &debugger = target->GetDebugger();
1412 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1413 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1414
1415 if (!script_interpreter)
1416 return NULL;
1417
1418 void* ret_val;
1419
1420 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
Enrico Granata91544802011-09-06 19:20:51 +00001421
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001422 {
Enrico Granata91544802011-09-06 19:20:51 +00001423 Locker py_lock(this, tmp_fh);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001424 ret_val = g_swig_synthetic_script (class_name,
1425 python_interpreter->m_dictionary_name.c_str(),
1426 valobj);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001427 }
1428
1429 return ret_val;
1430}
1431
Enrico Granataf7a9b142011-07-15 02:26:42 +00001432bool
1433ScriptInterpreterPython::GenerateTypeScriptFunction (const char* oneliner, StringList &output)
1434{
1435 StringList input(oneliner);
1436 return GenerateTypeScriptFunction(input, output);
1437}
1438
Chris Lattner24943d22010-06-08 16:52:24 +00001439bool
1440ScriptInterpreterPython::GenerateBreakpointCommandCallbackData (StringList &user_input, StringList &callback_data)
1441{
1442 static int num_created_functions = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001443 user_input.RemoveBlankLines ();
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001444 int num_lines = user_input.GetSize ();
1445 StreamString sstr;
Chris Lattner24943d22010-06-08 16:52:24 +00001446
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001447 // Check to see if we have any data; if not, just return.
1448 if (user_input.GetSize() == 0)
1449 return false;
1450
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001451 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1452 // frame and breakpoint location as parameters to the function.
Caroline Ticeb447e842010-09-21 19:25:28 +00001453
Caroline Ticeb447e842010-09-21 19:25:28 +00001454
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001455 sstr.Printf ("lldb_autogen_python_bp_callback_func_%d", num_created_functions);
1456 ++num_created_functions;
1457 std::string auto_generated_function_name = sstr.GetData();
Caroline Ticeb447e842010-09-21 19:25:28 +00001458
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001459 sstr.Clear();
Caroline Ticeb447e842010-09-21 19:25:28 +00001460 StringList auto_generated_function;
Caroline Ticeb447e842010-09-21 19:25:28 +00001461
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001462 // Create the function name & definition string.
1463
Caroline Tice0aa2e552011-01-14 00:29:16 +00001464 sstr.Printf ("def %s (frame, bp_loc, dict):", auto_generated_function_name.c_str());
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001465 auto_generated_function.AppendString (sstr.GetData());
Caroline Tice0aa2e552011-01-14 00:29:16 +00001466
1467 // Pre-pend code for setting up the session dictionary.
1468
1469 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1470 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1471 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1472 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1473 // global dictionary.
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001474
1475 // Wrap everything up inside the function, increasing the indentation.
Chris Lattner24943d22010-06-08 16:52:24 +00001476
1477 for (int i = 0; i < num_lines; ++i)
1478 {
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001479 sstr.Clear ();
1480 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1481 auto_generated_function.AppendString (sstr.GetData());
Caroline Ticeb447e842010-09-21 19:25:28 +00001482 }
Chris Lattner24943d22010-06-08 16:52:24 +00001483
Caroline Tice0aa2e552011-01-14 00:29:16 +00001484 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1485 // got written to the values in the global dictionary, not the session dictionary).
1486
1487 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1488 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1489 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1490 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1491
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001492 // Verify that the results are valid Python.
Chris Lattner24943d22010-06-08 16:52:24 +00001493
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001494 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
Caroline Ticeb447e842010-09-21 19:25:28 +00001495 {
Caroline Ticeb447e842010-09-21 19:25:28 +00001496 return false;
Chris Lattner24943d22010-06-08 16:52:24 +00001497 }
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001498
1499 // Store the name of the auto-generated function to be called.
1500
1501 callback_data.AppendString (auto_generated_function_name.c_str());
1502 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001503}
1504
Enrico Granataf7a9b142011-07-15 02:26:42 +00001505std::string
1506ScriptInterpreterPython::CallPythonScriptFunction (const char *python_function_name,
1507 lldb::ValueObjectSP valobj)
1508{
1509
1510 if (!python_function_name || !(*python_function_name))
1511 return "<no function>";
1512
1513 if (!valobj.get())
1514 return "<no object>";
1515
Enrico Granata979e20d2011-07-29 19:53:35 +00001516 Target *target = valobj->GetUpdatePoint().GetTargetSP().get();
Enrico Granataf7a9b142011-07-15 02:26:42 +00001517
1518 if (!target)
1519 return "<no target>";
1520
1521 Debugger &debugger = target->GetDebugger();
1522 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1523 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1524
1525 if (!script_interpreter)
1526 return "<no python>";
1527
1528 std::string ret_val;
1529
1530 if (python_function_name
1531 && *python_function_name)
1532 {
1533 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
Enrico Granata91544802011-09-06 19:20:51 +00001534
Enrico Granataf7a9b142011-07-15 02:26:42 +00001535 {
Enrico Granata91544802011-09-06 19:20:51 +00001536 Locker py_lock(python_interpreter, tmp_fh);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001537 ret_val = g_swig_typescript_callback (python_function_name,
1538 python_interpreter->m_dictionary_name.c_str(),
1539 valobj);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001540 }
1541 }
1542 else
1543 return "<no function name>";
1544
1545 return ret_val;
1546
1547}
1548
Greg Clayton5144f382010-10-07 17:14:24 +00001549bool
1550ScriptInterpreterPython::BreakpointCallbackFunction
1551(
1552 void *baton,
1553 StoppointCallbackContext *context,
1554 user_id_t break_id,
1555 user_id_t break_loc_id
1556)
1557{
1558 BreakpointOptions::CommandData *bp_option_data = (BreakpointOptions::CommandData *) baton;
1559 const char *python_function_name = bp_option_data->script_source.GetStringAtIndex (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001560
1561 if (!context)
1562 return true;
1563
1564 Target *target = context->exe_ctx.target;
1565
1566 if (!target)
1567 return true;
1568
1569 Debugger &debugger = target->GetDebugger();
1570 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1571 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1572
1573 if (!script_interpreter)
1574 return true;
Greg Clayton5144f382010-10-07 17:14:24 +00001575
1576 if (python_function_name != NULL
1577 && python_function_name[0] != '\0')
1578 {
1579 Thread *thread = context->exe_ctx.thread;
Greg Claytone86cbb92011-03-22 01:14:58 +00001580 const StackFrameSP stop_frame_sp (thread->GetStackFrameSPForStackFramePtr (context->exe_ctx.frame));
Greg Clayton5144f382010-10-07 17:14:24 +00001581 BreakpointSP breakpoint_sp = target->GetBreakpointByID (break_id);
Greg Claytone86cbb92011-03-22 01:14:58 +00001582 if (breakpoint_sp)
Caroline Tice0aa2e552011-01-14 00:29:16 +00001583 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001584 const BreakpointLocationSP bp_loc_sp (breakpoint_sp->FindLocationByID (break_loc_id));
1585
1586 if (stop_frame_sp && bp_loc_sp)
Caroline Tice202f6b82011-01-17 21:55:19 +00001587 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001588 bool ret_val = true;
1589 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
Enrico Granata91544802011-09-06 19:20:51 +00001590
Greg Claytone86cbb92011-03-22 01:14:58 +00001591 {
Enrico Granata91544802011-09-06 19:20:51 +00001592 Locker py_lock(python_interpreter, tmp_fh);
Greg Claytone86cbb92011-03-22 01:14:58 +00001593 ret_val = g_swig_breakpoint_callback (python_function_name,
1594 python_interpreter->m_dictionary_name.c_str(),
1595 stop_frame_sp,
1596 bp_loc_sp);
Greg Claytone86cbb92011-03-22 01:14:58 +00001597 }
1598 return ret_val;
Caroline Tice202f6b82011-01-17 21:55:19 +00001599 }
Caroline Tice0aa2e552011-01-14 00:29:16 +00001600 }
Greg Clayton5144f382010-10-07 17:14:24 +00001601 }
1602 // We currently always true so we stop in case anything goes wrong when
1603 // trying to call the script function
1604 return true;
1605}
Caroline Tice2ade6112010-11-10 19:18:14 +00001606
1607lldb::thread_result_t
1608ScriptInterpreterPython::RunEmbeddedPythonInterpreter (lldb::thread_arg_t baton)
1609{
1610 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
1611
1612 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
1613
1614 if (log)
1615 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread starting...", baton);
1616
1617 char error_str[1024];
1618 const char *pty_slave_name = script_interpreter->m_embedded_python_pty.GetSlaveName (error_str, sizeof (error_str));
Caroline Tice202f6b82011-01-17 21:55:19 +00001619 bool need_to_release_lock = true;
1620 bool safe_to_run = false;
Caroline Tice0aa2e552011-01-14 00:29:16 +00001621
Caroline Tice202f6b82011-01-17 21:55:19 +00001622 if (CurrentThreadHasPythonLock())
1623 {
1624 safe_to_run = true;
1625 need_to_release_lock = false;
1626 }
1627 else
1628 {
1629 int interval = 1;
1630 safe_to_run = GetPythonLock (interval);
1631 while (!safe_to_run)
1632 {
1633 interval = interval * 2;
1634 safe_to_run = GetPythonLock (interval);
1635 }
1636 }
1637
1638 if (pty_slave_name != NULL && safe_to_run)
1639 {
Caroline Tice2ade6112010-11-10 19:18:14 +00001640 StreamString run_string;
Caroline Tice2ade6112010-11-10 19:18:14 +00001641
Caroline Tice202f6b82011-01-17 21:55:19 +00001642 script_interpreter->EnterSession ();
1643
Caroline Tice0aa2e552011-01-14 00:29:16 +00001644 run_string.Printf ("run_one_line (%s, 'save_stderr = sys.stderr')", script_interpreter->m_dictionary_name.c_str());
1645 PyRun_SimpleString (run_string.GetData());
1646 run_string.Clear ();
1647
1648 run_string.Printf ("run_one_line (%s, 'sys.stderr = sys.stdout')", script_interpreter->m_dictionary_name.c_str());
1649 PyRun_SimpleString (run_string.GetData());
1650 run_string.Clear ();
1651
1652 run_string.Printf ("run_one_line (%s, 'save_stdin = sys.stdin')", script_interpreter->m_dictionary_name.c_str());
1653 PyRun_SimpleString (run_string.GetData());
1654 run_string.Clear ();
1655
1656 run_string.Printf ("run_one_line (%s, \"sys.stdin = open ('%s', 'r')\")", script_interpreter->m_dictionary_name.c_str(),
1657 pty_slave_name);
1658 PyRun_SimpleString (run_string.GetData());
1659 run_string.Clear ();
1660
Johnny Chen8054ba32011-03-11 00:28:50 +00001661 // The following call drops into the embedded interpreter loop and stays there until the
1662 // user chooses to exit from the Python interpreter.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001663
Caroline Ticece207c12011-03-11 00:21:55 +00001664 // When in the embedded interpreter, the user can call arbitrary system and Python stuff, which may require
Johnny Chen8054ba32011-03-11 00:28:50 +00001665 // 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 +00001666 // calls to Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS.
1667
1668 // We ALSO need to surround the call to the embedded interpreter with calls to PyGILState_Ensure and
1669 // PyGILState_Release. This is because this embedded interpreter is being run on a DIFFERENT THREAD than
1670 // the thread on which the call to Py_Initialize (and PyEval_InitThreads) was called. Those initializations
1671 // called PyGILState_Ensure on *that* thread, but it also needs to be called on *this* thread. Otherwise,
1672 // if the user calls Python code that does threading stuff, the interpreter state will be off, and things could
1673 // hang (it's happened before).
1674
Caroline Tice9d352ce2011-03-07 23:24:28 +00001675 Py_BEGIN_ALLOW_THREADS
1676 PyGILState_STATE gstate = PyGILState_Ensure();
1677
Caroline Tice0aa2e552011-01-14 00:29:16 +00001678 run_string.Printf ("run_python_interpreter (%s)", script_interpreter->m_dictionary_name.c_str());
1679 PyRun_SimpleString (run_string.GetData());
1680 run_string.Clear ();
Caroline Tice2ade6112010-11-10 19:18:14 +00001681
Caroline Tice9d352ce2011-03-07 23:24:28 +00001682 PyGILState_Release (gstate);
1683 Py_END_ALLOW_THREADS
1684
Caroline Tice0aa2e552011-01-14 00:29:16 +00001685 run_string.Printf ("run_one_line (%s, 'sys.stdin = save_stdin')", script_interpreter->m_dictionary_name.c_str());
1686 PyRun_SimpleString (run_string.GetData());
1687 run_string.Clear();
1688
1689 run_string.Printf ("run_one_line (%s, 'sys.stderr = save_stderr')", script_interpreter->m_dictionary_name.c_str());
1690 PyRun_SimpleString (run_string.GetData());
1691 run_string.Clear();
Caroline Tice202f6b82011-01-17 21:55:19 +00001692
1693 script_interpreter->LeaveSession ();
1694
Caroline Tice2ade6112010-11-10 19:18:14 +00001695 }
1696
Caroline Tice202f6b82011-01-17 21:55:19 +00001697 if (!safe_to_run)
1698 fprintf ((script_interpreter->m_dbg_stdout ? script_interpreter->m_dbg_stdout : stdout),
1699 "Python interpreter locked on another thread; unable to acquire lock.\n");
1700
1701 if (need_to_release_lock)
1702 ReleasePythonLock ();
1703
Caroline Tice2ade6112010-11-10 19:18:14 +00001704 if (script_interpreter->m_embedded_thread_input_reader_sp)
1705 script_interpreter->m_embedded_thread_input_reader_sp->SetIsDone (true);
1706
1707 script_interpreter->m_embedded_python_pty.CloseSlaveFileDescriptor();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001708
1709 script_interpreter->m_pty_slave_is_open = false;
Caroline Tice2ade6112010-11-10 19:18:14 +00001710
1711 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT);
1712 if (log)
1713 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread exiting...", baton);
1714
1715
Johnny Chen8054ba32011-03-11 00:28:50 +00001716 // Clean up the input reader and make the debugger pop it off the stack.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001717 Debugger &debugger = script_interpreter->GetCommandInterpreter().GetDebugger();
Caroline Tice2ade6112010-11-10 19:18:14 +00001718 const InputReaderSP reader_sp = script_interpreter->m_embedded_thread_input_reader_sp;
1719 script_interpreter->m_embedded_thread_input_reader_sp.reset();
1720 debugger.PopInputReader (reader_sp);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001721
Caroline Tice2ade6112010-11-10 19:18:14 +00001722 return NULL;
1723}
1724
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001725uint32_t
1726ScriptInterpreterPython::CalculateNumChildren (void *implementor)
1727{
1728 if (!implementor)
1729 return 0;
1730
1731 if (!g_swig_calc_children)
1732 return 0;
1733
1734 ScriptInterpreterPython *python_interpreter = this;
1735
1736 uint32_t ret_val = 0;
1737
1738 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
Enrico Granata91544802011-09-06 19:20:51 +00001739
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001740 {
Enrico Granata91544802011-09-06 19:20:51 +00001741 Locker py_lock(python_interpreter, tmp_fh);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001742 ret_val = g_swig_calc_children (implementor);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001743 }
1744
1745 return ret_val;
1746}
1747
Enrico Granata91544802011-09-06 19:20:51 +00001748lldb::ValueObjectSP
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001749ScriptInterpreterPython::GetChildAtIndex (void *implementor, uint32_t idx)
1750{
1751 if (!implementor)
Enrico Granata91544802011-09-06 19:20:51 +00001752 return lldb::ValueObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001753
Enrico Granata91544802011-09-06 19:20:51 +00001754 if (!g_swig_get_child_index || !g_swig_cast_to_sbvalue)
1755 return lldb::ValueObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001756
1757 ScriptInterpreterPython *python_interpreter = this;
1758
Enrico Granata91544802011-09-06 19:20:51 +00001759 void* child_ptr = NULL;
1760 lldb::SBValue* value_sb = NULL;
1761 lldb::ValueObjectSP ret_val;
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001762
1763 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
Enrico Granata91544802011-09-06 19:20:51 +00001764
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001765 {
Enrico Granata91544802011-09-06 19:20:51 +00001766 Locker py_lock(python_interpreter, tmp_fh);
1767 child_ptr = g_swig_get_child_index (implementor,idx);
1768 if (child_ptr != NULL && child_ptr != Py_None)
1769 {
1770 value_sb = (lldb::SBValue*)g_swig_cast_to_sbvalue(child_ptr);
1771 if (value_sb == NULL)
1772 Py_XDECREF(child_ptr);
1773 else
1774 ret_val = value_sb->get_sp();
1775 }
1776 else
1777 {
1778 Py_XDECREF(child_ptr);
1779 }
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001780 }
1781
1782 return ret_val;
1783}
1784
1785int
1786ScriptInterpreterPython::GetIndexOfChildWithName (void *implementor, const char* child_name)
1787{
1788 if (!implementor)
1789 return UINT32_MAX;
1790
1791 if (!g_swig_get_index_child)
1792 return UINT32_MAX;
1793
1794 ScriptInterpreterPython *python_interpreter = this;
1795
1796 int ret_val = UINT32_MAX;
1797
1798 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
Enrico Granata91544802011-09-06 19:20:51 +00001799
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001800 {
Enrico Granata91544802011-09-06 19:20:51 +00001801 Locker py_lock(python_interpreter, tmp_fh);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001802 ret_val = g_swig_get_index_child (implementor, child_name);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001803 }
1804
1805 return ret_val;
1806}
1807
Enrico Granata979e20d2011-07-29 19:53:35 +00001808void
1809ScriptInterpreterPython::UpdateSynthProviderInstance (void* implementor)
1810{
1811 if (!implementor)
1812 return;
1813
1814 if (!g_swig_update_provider)
1815 return;
1816
1817 ScriptInterpreterPython *python_interpreter = this;
1818
1819 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
Enrico Granata91544802011-09-06 19:20:51 +00001820
Enrico Granata979e20d2011-07-29 19:53:35 +00001821 {
Enrico Granata91544802011-09-06 19:20:51 +00001822 Locker py_lock(python_interpreter, tmp_fh);
Enrico Granata979e20d2011-07-29 19:53:35 +00001823 g_swig_update_provider (implementor);
Enrico Granata979e20d2011-07-29 19:53:35 +00001824 }
1825
1826 return;
1827}
1828
Enrico Granatac2a28252011-08-16 16:49:25 +00001829bool
1830ScriptInterpreterPython::RunScriptBasedCommand(const char* impl_function,
1831 const char* args,
Enrico Granata6b1596d2011-08-16 23:24:13 +00001832 lldb_private::CommandReturnObject& cmd_retobj,
Enrico Granatac2a28252011-08-16 16:49:25 +00001833 Error& error)
1834{
1835 if (!impl_function)
1836 {
1837 error.SetErrorString("no function to execute");
1838 return false;
1839 }
1840
1841 if (!g_swig_call_command)
1842 {
1843 error.SetErrorString("no helper function to run scripted commands");
1844 return false;
1845 }
1846
1847 ScriptInterpreterPython *python_interpreter = this;
Enrico Granata3370f0c2011-08-19 23:56:34 +00001848
Enrico Granatac2a28252011-08-16 16:49:25 +00001849 lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().GetSP();
1850
1851 bool ret_val;
1852
1853 std::string err_msg;
1854
1855 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
Enrico Granata91544802011-09-06 19:20:51 +00001856
Enrico Granatac2a28252011-08-16 16:49:25 +00001857 {
Enrico Granata91544802011-09-06 19:20:51 +00001858 Locker py_lock(python_interpreter, tmp_fh);
Enrico Granatac2a28252011-08-16 16:49:25 +00001859 ret_val = g_swig_call_command (impl_function,
1860 python_interpreter->m_dictionary_name.c_str(),
1861 debugger_sp,
1862 args,
1863 err_msg,
Enrico Granata3370f0c2011-08-19 23:56:34 +00001864 cmd_retobj);
Enrico Granatac2a28252011-08-16 16:49:25 +00001865 }
1866
1867 if (!ret_val)
1868 error.SetErrorString(err_msg.c_str());
1869 else
1870 error.Clear();
Enrico Granata3370f0c2011-08-19 23:56:34 +00001871
Enrico Granatac2a28252011-08-16 16:49:25 +00001872 return ret_val;
1873
1874
1875 return true;
1876
1877}
1878
Enrico Granatae5e34cb2011-08-17 01:30:04 +00001879// in Python, a special attribute __doc__ contains the docstring
1880// for an object (function, method, class, ...) if any is defined
1881// Otherwise, the attribute's value is None
1882std::string
1883ScriptInterpreterPython::GetDocumentationForItem(const char* item)
1884{
1885 std::string command(item);
1886 command += ".__doc__";
1887
1888 char* result_ptr = NULL; // Python is going to point this to valid data if ExecuteOneLineWithReturn returns successfully
1889
1890 if (ExecuteOneLineWithReturn (command.c_str(),
1891 ScriptInterpreter::eCharStrOrNone,
1892 &result_ptr) && result_ptr)
1893 {
1894 return std::string(result_ptr);
1895 }
1896 else
1897 return std::string("");
1898}
Caroline Tice2ade6112010-11-10 19:18:14 +00001899
Caroline Tice0aa2e552011-01-14 00:29:16 +00001900void
Greg Claytone86cbb92011-03-22 01:14:58 +00001901ScriptInterpreterPython::InitializeInterpreter (SWIGInitCallback python_swig_init_callback,
Enrico Granataf7a9b142011-07-15 02:26:42 +00001902 SWIGBreakpointCallbackFunction python_swig_breakpoint_callback,
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001903 SWIGPythonTypeScriptCallbackFunction python_swig_typescript_callback,
1904 SWIGPythonCreateSyntheticProvider python_swig_synthetic_script,
1905 SWIGPythonCalculateNumChildren python_swig_calc_children,
1906 SWIGPythonGetChildAtIndex python_swig_get_child_index,
1907 SWIGPythonGetIndexOfChildWithName python_swig_get_index_child,
Enrico Granata979e20d2011-07-29 19:53:35 +00001908 SWIGPythonCastPyObjectToSBValue python_swig_cast_to_sbvalue,
Enrico Granatac2a28252011-08-16 16:49:25 +00001909 SWIGPythonUpdateSynthProviderInstance python_swig_update_provider,
1910 SWIGPythonCallCommand python_swig_call_command)
Greg Claytone86cbb92011-03-22 01:14:58 +00001911{
1912 g_swig_init_callback = python_swig_init_callback;
Enrico Granataf7a9b142011-07-15 02:26:42 +00001913 g_swig_breakpoint_callback = python_swig_breakpoint_callback;
1914 g_swig_typescript_callback = python_swig_typescript_callback;
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001915 g_swig_synthetic_script = python_swig_synthetic_script;
1916 g_swig_calc_children = python_swig_calc_children;
1917 g_swig_get_child_index = python_swig_get_child_index;
1918 g_swig_get_index_child = python_swig_get_index_child;
1919 g_swig_cast_to_sbvalue = python_swig_cast_to_sbvalue;
Enrico Granata979e20d2011-07-29 19:53:35 +00001920 g_swig_update_provider = python_swig_update_provider;
Enrico Granatac2a28252011-08-16 16:49:25 +00001921 g_swig_call_command = python_swig_call_command;
Greg Claytone86cbb92011-03-22 01:14:58 +00001922}
1923
1924void
1925ScriptInterpreterPython::InitializePrivate ()
Caroline Tice0aa2e552011-01-14 00:29:16 +00001926{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001927 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
1928
Greg Clayton0fdd4a02011-02-07 23:24:47 +00001929 // Python will muck with STDIN terminal state, so save off any current TTY
1930 // settings so we can restore them.
1931 TerminalState stdin_tty_state;
1932 stdin_tty_state.Save(STDIN_FILENO, false);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001933
Caroline Tice9d352ce2011-03-07 23:24:28 +00001934 PyEval_InitThreads ();
Caroline Ticea54461d2011-06-02 22:09:43 +00001935 Py_InitializeEx (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001936
Greg Claytone86cbb92011-03-22 01:14:58 +00001937 // Initialize SWIG after setting up python
1938 assert (g_swig_init_callback != NULL);
1939 g_swig_init_callback ();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001940
1941 // Update the path python uses to search for modules to include the current directory.
1942
Caroline Ticed4d92832011-06-13 21:33:00 +00001943 PyRun_SimpleString ("import sys");
1944 PyRun_SimpleString ("sys.path.append ('.')");
Jim Ingham2a19ef92011-08-27 01:24:08 +00001945
1946 // Find the module that owns this code and use that path we get to
1947 // set the sys.path appropriately.
1948
1949 FileSpec file_spec;
1950 char python_dir_path[PATH_MAX];
1951 if (Host::GetLLDBPath (ePathTypePythonDir, file_spec))
1952 {
1953 std::string python_path("sys.path.insert(0,\"");
1954 size_t orig_len = python_path.length();
1955 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
1956 {
1957 python_path.append (python_dir_path);
1958 python_path.append ("\")");
1959 PyRun_SimpleString (python_path.c_str());
1960 python_path.resize (orig_len);
1961 }
1962
1963 if (Host::GetLLDBPath (ePathTypeLLDBShlibDir, file_spec))
1964 {
1965 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
1966 {
1967 python_path.append (python_dir_path);
1968 python_path.append ("\")");
1969 PyRun_SimpleString (python_path.c_str());
1970 python_path.resize (orig_len);
1971 }
1972 }
1973 }
1974
Jim Ingham4dfa5112011-08-22 19:10:09 +00001975 PyRun_SimpleString ("sys.dont_write_bytecode = 1");
Caroline Tice0aa2e552011-01-14 00:29:16 +00001976
Caroline Ticed4d92832011-06-13 21:33:00 +00001977 PyRun_SimpleString ("import embedded_interpreter");
Caroline Tice0aa2e552011-01-14 00:29:16 +00001978
Caroline Ticed4d92832011-06-13 21:33:00 +00001979 PyRun_SimpleString ("from embedded_interpreter import run_python_interpreter");
1980 PyRun_SimpleString ("from embedded_interpreter import run_one_line");
Caroline Ticed4d92832011-06-13 21:33:00 +00001981 PyRun_SimpleString ("from termios import *");
Greg Clayton99208582011-02-07 19:04:58 +00001982
Greg Clayton0fdd4a02011-02-07 23:24:47 +00001983 stdin_tty_state.Restore();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001984}
1985
Greg Claytone86cbb92011-03-22 01:14:58 +00001986//void
1987//ScriptInterpreterPython::Terminate ()
1988//{
1989// // We are intentionally NOT calling Py_Finalize here (this would be the logical place to call it). Calling
1990// // Py_Finalize here causes test suite runs to seg fault: The test suite runs in Python. It registers
1991// // SBDebugger::Terminate to be called 'at_exit'. When the test suite Python harness finishes up, it calls
1992// // Py_Finalize, which calls all the 'at_exit' registered functions. SBDebugger::Terminate calls Debugger::Terminate,
1993// // which calls lldb::Terminate, which calls ScriptInterpreter::Terminate, which calls
1994// // ScriptInterpreterPython::Terminate. So if we call Py_Finalize here, we end up with Py_Finalize being called from
1995// // within Py_Finalize, which results in a seg fault.
1996// //
1997// // Since this function only gets called when lldb is shutting down and going away anyway, the fact that we don't
1998// // actually call Py_Finalize should not cause any problems (everything should shut down/go away anyway when the
1999// // process exits).
2000// //
2001//// Py_Finalize ();
2002//}