blob: 9ff176f42d40f20dcca5c487891e39b71d0a5d7e [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());
Caroline Tice6af65cb2011-05-03 21:21:50 +0000380 run_string.Clear();
Caroline Tice202f6b82011-01-17 21:55:19 +0000381
Caroline Tice0aa2e552011-01-14 00:29:16 +0000382
Caroline Tice6af65cb2011-05-03 21:21:50 +0000383 run_string.Printf ("run_one_line (%s, 'lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%d)')",
384 m_dictionary_name.c_str(),
385 GetCommandInterpreter().GetDebugger().GetID());
386 PyRun_SimpleString (run_string.GetData());
387 run_string.Clear();
388
389
390 ExecutionContext exe_ctx = m_interpreter.GetDebugger().GetSelectedExecutionContext();
391
392 if (exe_ctx.target)
393 run_string.Printf ("run_one_line (%s, 'lldb.target = lldb.debugger.GetSelectedTarget()')",
394 m_dictionary_name.c_str());
395 else
396 run_string.Printf ("run_one_line (%s, 'lldb.target = None')", m_dictionary_name.c_str());
397 PyRun_SimpleString (run_string.GetData());
398 run_string.Clear();
399
400 if (exe_ctx.process)
401 run_string.Printf ("run_one_line (%s, 'lldb.process = lldb.target.GetProcess()')", m_dictionary_name.c_str());
402 else
403 run_string.Printf ("run_one_line (%s, 'lldb.process = None')", m_dictionary_name.c_str());
404 PyRun_SimpleString (run_string.GetData());
405 run_string.Clear();
406
407 if (exe_ctx.thread)
408 run_string.Printf ("run_one_line (%s, 'lldb.thread = lldb.process.GetSelectedThread ()')",
409 m_dictionary_name.c_str());
410 else
411 run_string.Printf ("run_one_line (%s, 'lldb.thread = None')", m_dictionary_name.c_str());
412 PyRun_SimpleString (run_string.GetData());
413 run_string.Clear();
414
415 if (exe_ctx.frame)
416 run_string.Printf ("run_one_line (%s, 'lldb.frame = lldb.thread.GetSelectedFrame ()')",
417 m_dictionary_name.c_str());
418 else
419 run_string.Printf ("run_one_line (%s, 'lldb.frame = None')", m_dictionary_name.c_str());
420 PyRun_SimpleString (run_string.GetData());
421 run_string.Clear();
422
Caroline Tice0aa2e552011-01-14 00:29:16 +0000423 PyObject *sysmod = PyImport_AddModule ("sys");
424 PyObject *sysdict = PyModule_GetDict (sysmod);
425
426 if ((m_new_sysout != NULL)
427 && (sysmod != NULL)
428 && (sysdict != NULL))
429 PyDict_SetItemString (sysdict, "stdout", m_new_sysout);
430
431 if (PyErr_Occurred())
432 PyErr_Clear ();
433
Caroline Tice0aa2e552011-01-14 00:29:16 +0000434 if (!m_pty_slave_is_open)
435 {
Caroline Tice202f6b82011-01-17 21:55:19 +0000436 run_string.Clear();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000437 run_string.Printf ("run_one_line (%s, \"new_stdin = open('%s', 'r')\")", m_dictionary_name.c_str(),
438 m_pty_slave_name.c_str());
439 PyRun_SimpleString (run_string.GetData());
440 m_pty_slave_is_open = true;
441
442 run_string.Clear();
443 run_string.Printf ("run_one_line (%s, 'sys.stdin = new_stdin')", m_dictionary_name.c_str());
444 PyRun_SimpleString (run_string.GetData());
445 }
446}
447
448
Johnny Chen60dde642010-07-30 22:33:14 +0000449bool
Greg Clayton238c0a12010-09-18 01:14:36 +0000450ScriptInterpreterPython::ExecuteOneLine (const char *command, CommandReturnObject *result)
Chris Lattner24943d22010-06-08 16:52:24 +0000451{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000452 if (!m_valid_session)
453 return false;
454
Caroline Tice0aa2e552011-01-14 00:29:16 +0000455
Caroline Tice0aa2e552011-01-14 00:29:16 +0000456
Caroline Tice4a461da2011-01-14 21:09:29 +0000457 // We want to call run_one_line, passing in the dictionary and the command string. We cannot do this through
458 // PyRun_SimpleString here because the command string may contain escaped characters, and putting it inside
459 // another string to pass to PyRun_SimpleString messes up the escaping. So we use the following more complicated
460 // method to pass the command string directly down to Python.
461
462
Caroline Tice202f6b82011-01-17 21:55:19 +0000463 bool need_to_release_lock = true;
464
465 if (CurrentThreadHasPythonLock())
466 need_to_release_lock = false;
467 else if (!GetPythonLock (1))
468 {
469 fprintf ((m_dbg_stdout ? m_dbg_stdout : stdout),
470 "Python interpreter is currently locked by another thread; unable to process command.\n");
471 return false;
472 }
473
474 EnterSession ();
Caroline Tice4a461da2011-01-14 21:09:29 +0000475 bool success = false;
476
Greg Clayton63094e02010-06-23 01:19:29 +0000477 if (command)
Chris Lattner24943d22010-06-08 16:52:24 +0000478 {
Caroline Tice4a461da2011-01-14 21:09:29 +0000479 // Find the correct script interpreter dictionary in the main module.
480 PyObject *main_mod = PyImport_AddModule ("__main__");
481 PyObject *script_interpreter_dict = NULL;
482 if (main_mod != NULL)
483 {
484 PyObject *main_dict = PyModule_GetDict (main_mod);
485 if ((main_dict != NULL)
486 && PyDict_Check (main_dict))
487 {
488 // Go through the main dictionary looking for the correct python script interpreter dictionary
489 PyObject *key, *value;
490 Py_ssize_t pos = 0;
491
492 while (PyDict_Next (main_dict, &pos, &key, &value))
493 {
494 // We have stolen references to the key and value objects in the dictionary; we need to increment
495 // them now so that Python's garbage collector doesn't collect them out from under us.
496 Py_INCREF (key);
497 Py_INCREF (value);
498 if (strcmp (PyString_AsString (key), m_dictionary_name.c_str()) == 0)
499 {
500 script_interpreter_dict = value;
501 break;
502 }
503 }
504 }
505
506 if (script_interpreter_dict != NULL)
507 {
508 PyObject *pfunc = NULL;
509 PyObject *pmod = PyImport_AddModule ("embedded_interpreter");
510 if (pmod != NULL)
511 {
512 PyObject *pmod_dict = PyModule_GetDict (pmod);
513 if ((pmod_dict != NULL)
514 && PyDict_Check (pmod_dict))
515 {
516 PyObject *key, *value;
517 Py_ssize_t pos = 0;
518
519 while (PyDict_Next (pmod_dict, &pos, &key, &value))
520 {
521 Py_INCREF (key);
522 Py_INCREF (value);
523 if (strcmp (PyString_AsString (key), "run_one_line") == 0)
524 {
525 pfunc = value;
526 break;
527 }
528 }
529
530 PyObject *string_arg = PyString_FromString (command);
531 if (pfunc && string_arg && PyCallable_Check (pfunc))
532 {
533 PyObject *pargs = PyTuple_New (2);
534 if (pargs != NULL)
535 {
536 PyTuple_SetItem (pargs, 0, script_interpreter_dict);
537 PyTuple_SetItem (pargs, 1, string_arg);
538 PyObject *pvalue = PyObject_CallObject (pfunc, pargs);
539 Py_DECREF (pargs);
540 if (pvalue != NULL)
541 {
542 Py_DECREF (pvalue);
543 success = true;
544 }
545 else if (PyErr_Occurred ())
546 {
547 PyErr_Print();
548 PyErr_Clear();
549 }
550 }
551 }
552 }
553 }
554 Py_INCREF (script_interpreter_dict);
555 }
556 }
Greg Clayton63094e02010-06-23 01:19:29 +0000557
Caroline Tice0aa2e552011-01-14 00:29:16 +0000558 LeaveSession ();
559
Caroline Tice202f6b82011-01-17 21:55:19 +0000560 if (need_to_release_lock)
561 ReleasePythonLock();
562
Caroline Tice4a461da2011-01-14 21:09:29 +0000563 if (success)
Johnny Chen60dde642010-07-30 22:33:14 +0000564 return true;
565
566 // The one-liner failed. Append the error message.
567 if (result)
568 result->AppendErrorWithFormat ("python failed attempting to evaluate '%s'\n", command);
569 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000570 }
Johnny Chen60dde642010-07-30 22:33:14 +0000571
Caroline Tice0aa2e552011-01-14 00:29:16 +0000572 LeaveSession ();
Caroline Tice202f6b82011-01-17 21:55:19 +0000573
574 if (need_to_release_lock)
575 ReleasePythonLock ();
576
Johnny Chen60dde642010-07-30 22:33:14 +0000577 if (result)
578 result->AppendError ("empty command passed to python\n");
579 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000580}
581
582
583
584size_t
585ScriptInterpreterPython::InputReaderCallback
586(
587 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000588 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000589 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000590 const char *bytes,
591 size_t bytes_len
592)
593{
Caroline Tice2ade6112010-11-10 19:18:14 +0000594 lldb::thread_t embedded_interpreter_thread;
595 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
596
Chris Lattner24943d22010-06-08 16:52:24 +0000597 if (baton == NULL)
598 return 0;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000599
600 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
601
602 if (script_interpreter->m_script_lang != eScriptLanguagePython)
603 return 0;
604
Greg Clayton58928562011-02-09 01:08:52 +0000605 File &out_file = reader.GetDebugger().GetOutputFile();
Caroline Tice67637d82010-12-15 19:51:12 +0000606
Chris Lattner24943d22010-06-08 16:52:24 +0000607 switch (notification)
608 {
609 case eInputReaderActivate:
610 {
Greg Clayton58928562011-02-09 01:08:52 +0000611 out_file.Printf ("Python Interactive Interpreter. To exit, type 'quit()', 'exit()' or Ctrl-D.\n");
612
Chris Lattner24943d22010-06-08 16:52:24 +0000613 // Save terminal settings if we can
Greg Clayton58928562011-02-09 01:08:52 +0000614 int input_fd = reader.GetDebugger().GetInputFile().GetDescriptor();
615 if (input_fd == File::kInvalidDescriptor)
Greg Clayton24b48ff2010-10-17 22:03:32 +0000616 input_fd = STDIN_FILENO;
Caroline Ticec95c6d12010-09-14 22:49:06 +0000617
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000618 script_interpreter->SaveTerminalState(input_fd);
Greg Clayton99208582011-02-07 19:04:58 +0000619
Caroline Tice202f6b82011-01-17 21:55:19 +0000620 if (!CurrentThreadHasPythonLock())
621 {
622 while (!GetPythonLock(1))
623 {
Greg Clayton58928562011-02-09 01:08:52 +0000624 out_file.Printf ("Python interpreter locked on another thread; waiting to acquire lock...\n");
Caroline Tice202f6b82011-01-17 21:55:19 +0000625 }
626 script_interpreter->EnterSession ();
627 ReleasePythonLock();
628 }
629 else
630 script_interpreter->EnterSession ();
631
Caroline Tice2ade6112010-11-10 19:18:14 +0000632 char error_str[1024];
633 if (script_interpreter->m_embedded_python_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, error_str,
634 sizeof(error_str)))
635 {
636 if (log)
637 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in opening master pty (fd = %d).",
638 script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor());
639 embedded_interpreter_thread = Host::ThreadCreate ("<lldb.script-interpreter.embedded-python-loop>",
640 ScriptInterpreterPython::RunEmbeddedPythonInterpreter,
641 script_interpreter, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +0000642 if (IS_VALID_LLDB_HOST_THREAD(embedded_interpreter_thread))
Caroline Tice2ade6112010-11-10 19:18:14 +0000643 {
644 if (log)
645 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in creating thread (thread = %d)", embedded_interpreter_thread);
646 Error detach_error;
647 Host::ThreadDetach (embedded_interpreter_thread, &detach_error);
648 }
649 else
650 {
651 if (log)
652 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed in creating thread");
653 reader.SetIsDone (true);
654 }
655 }
656 else
657 {
658 if (log)
659 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed to open master pty ");
660 reader.SetIsDone (true);
661 }
Chris Lattner24943d22010-06-08 16:52:24 +0000662 }
663 break;
664
665 case eInputReaderDeactivate:
Caroline Tice0aa2e552011-01-14 00:29:16 +0000666 script_interpreter->LeaveSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000667 break;
668
669 case eInputReaderReactivate:
Caroline Tice202f6b82011-01-17 21:55:19 +0000670 if (!CurrentThreadHasPythonLock())
671 {
672 while (!GetPythonLock(1))
673 {
674 // Wait until lock is acquired.
675 }
676 script_interpreter->EnterSession ();
677 ReleasePythonLock();
678 }
679 else
680 script_interpreter->EnterSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000681 break;
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000682
Caroline Tice4a348082011-05-02 20:41:46 +0000683 case eInputReaderAsynchronousOutputWritten:
684 break;
685
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000686 case eInputReaderInterrupt:
687 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "raise KeyboardInterrupt\n", 24);
688 break;
689
690 case eInputReaderEndOfFile:
691 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()\n", 7);
692 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000693
694 case eInputReaderGotToken:
Caroline Tice2ade6112010-11-10 19:18:14 +0000695 if (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor() != -1)
Chris Lattner24943d22010-06-08 16:52:24 +0000696 {
Caroline Tice2ade6112010-11-10 19:18:14 +0000697 if (log)
698 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %d", bytes,
699 bytes_len);
700 if (bytes && bytes_len)
701 {
702 if ((int) bytes[0] == 4)
703 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()", 6);
704 else
705 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), bytes, bytes_len);
706 }
707 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "\n", 1);
Chris Lattner24943d22010-06-08 16:52:24 +0000708 }
Caroline Tice2ade6112010-11-10 19:18:14 +0000709 else
710 {
711 if (log)
712 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %d, Master File Descriptor is bad.",
713 bytes,
714 bytes_len);
715 reader.SetIsDone (true);
716 }
717
Chris Lattner24943d22010-06-08 16:52:24 +0000718 break;
719
720 case eInputReaderDone:
Caroline Tice0aa2e552011-01-14 00:29:16 +0000721 script_interpreter->LeaveSession ();
722
Chris Lattner24943d22010-06-08 16:52:24 +0000723 // Restore terminal settings if they were validly saved
Caroline Tice2ade6112010-11-10 19:18:14 +0000724 if (log)
725 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Done, closing down input reader.");
Caroline Ticec95c6d12010-09-14 22:49:06 +0000726
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000727 script_interpreter->RestoreTerminalState ();
728
Caroline Tice2ade6112010-11-10 19:18:14 +0000729 script_interpreter->m_embedded_python_pty.CloseMasterFileDescriptor();
Chris Lattner24943d22010-06-08 16:52:24 +0000730 break;
731 }
732
733 return bytes_len;
734}
735
736
737void
Greg Clayton238c0a12010-09-18 01:14:36 +0000738ScriptInterpreterPython::ExecuteInterpreterLoop ()
Chris Lattner24943d22010-06-08 16:52:24 +0000739{
740 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
741
Caroline Tice0aa2e552011-01-14 00:29:16 +0000742 Debugger &debugger = GetCommandInterpreter().GetDebugger();
Caroline Ticec95c6d12010-09-14 22:49:06 +0000743
744 // At the moment, the only time the debugger does not have an input file handle is when this is called
745 // directly from Python, in which case it is both dangerous and unnecessary (not to mention confusing) to
746 // try to embed a running interpreter loop inside the already running Python interpreter loop, so we won't
747 // do it.
748
Greg Clayton58928562011-02-09 01:08:52 +0000749 if (!debugger.GetInputFile().IsValid())
Caroline Ticec95c6d12010-09-14 22:49:06 +0000750 return;
751
Greg Clayton63094e02010-06-23 01:19:29 +0000752 InputReaderSP reader_sp (new InputReader(debugger));
Chris Lattner24943d22010-06-08 16:52:24 +0000753 if (reader_sp)
754 {
755 Error error (reader_sp->Initialize (ScriptInterpreterPython::InputReaderCallback,
756 this, // baton
757 eInputReaderGranularityLine, // token size, to pass to callback function
758 NULL, // end token
759 NULL, // prompt
760 true)); // echo input
761
762 if (error.Success())
763 {
Greg Clayton63094e02010-06-23 01:19:29 +0000764 debugger.PushInputReader (reader_sp);
Caroline Tice2ade6112010-11-10 19:18:14 +0000765 m_embedded_thread_input_reader_sp = reader_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000766 }
767 }
768}
769
770bool
771ScriptInterpreterPython::ExecuteOneLineWithReturn (const char *in_string,
772 ScriptInterpreter::ReturnType return_type,
773 void *ret_value)
774{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000775
Caroline Tice202f6b82011-01-17 21:55:19 +0000776 bool need_to_release_lock = true;
777
778 if (CurrentThreadHasPythonLock())
779 need_to_release_lock = false;
780 else if (!GetPythonLock (1))
781 {
782 fprintf ((m_dbg_stdout ? m_dbg_stdout : stdout),
783 "Python interpreter is currently locked by another thread; unable to process command.\n");
784 return false;
785 }
786
787 EnterSession ();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000788
Chris Lattner24943d22010-06-08 16:52:24 +0000789 PyObject *py_return = NULL;
790 PyObject *mainmod = PyImport_AddModule ("__main__");
791 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000792 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000793 PyObject *py_error = NULL;
794 bool ret_success;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000795 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000796 int success;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000797
798 if (PyDict_Check (globals))
799 {
800 PyObject *key, *value;
801 Py_ssize_t pos = 0;
802
803 int i = 0;
804 while (PyDict_Next (globals, &pos, &key, &value))
805 {
806 // We have stolen references to the key and value objects in the dictionary; we need to increment them now
807 // so that Python's garbage collector doesn't collect them out from under us.
808 Py_INCREF (key);
809 Py_INCREF (value);
810 char *c_str = PyString_AsString (key);
811 if (strcmp (c_str, m_dictionary_name.c_str()) == 0)
812 locals = value;
813 ++i;
814 }
815 }
Chris Lattner24943d22010-06-08 16:52:24 +0000816
Caroline Tice0aa2e552011-01-14 00:29:16 +0000817 if (locals == NULL)
818 {
819 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
820 should_decrement_locals = true;
821 }
822
823 if (locals == NULL)
824 {
825 locals = globals;
826 should_decrement_locals = false;
827 }
828
829 py_error = PyErr_Occurred();
830 if (py_error != NULL)
831 PyErr_Clear();
832
Chris Lattner24943d22010-06-08 16:52:24 +0000833 if (in_string != NULL)
834 {
835 py_return = PyRun_String (in_string, Py_eval_input, globals, locals);
836 if (py_return == NULL)
837 {
838 py_error = PyErr_Occurred ();
839 if (py_error != NULL)
840 PyErr_Clear ();
841
842 py_return = PyRun_String (in_string, Py_single_input, globals, locals);
843 }
844
Caroline Tice0aa2e552011-01-14 00:29:16 +0000845 if (locals != NULL
846 && should_decrement_locals)
847 Py_DECREF (locals);
848
Chris Lattner24943d22010-06-08 16:52:24 +0000849 if (py_return != NULL)
850 {
851 switch (return_type)
852 {
853 case eCharPtr: // "char *"
854 {
855 const char format[3] = "s#";
856 success = PyArg_Parse (py_return, format, (char **) &ret_value);
857 break;
858 }
859 case eBool:
860 {
861 const char format[2] = "b";
862 success = PyArg_Parse (py_return, format, (bool *) ret_value);
863 break;
864 }
865 case eShortInt:
866 {
867 const char format[2] = "h";
868 success = PyArg_Parse (py_return, format, (short *) ret_value);
869 break;
870 }
871 case eShortIntUnsigned:
872 {
873 const char format[2] = "H";
874 success = PyArg_Parse (py_return, format, (unsigned short *) ret_value);
875 break;
876 }
877 case eInt:
878 {
879 const char format[2] = "i";
880 success = PyArg_Parse (py_return, format, (int *) ret_value);
881 break;
882 }
883 case eIntUnsigned:
884 {
885 const char format[2] = "I";
886 success = PyArg_Parse (py_return, format, (unsigned int *) ret_value);
887 break;
888 }
889 case eLongInt:
890 {
891 const char format[2] = "l";
892 success = PyArg_Parse (py_return, format, (long *) ret_value);
893 break;
894 }
895 case eLongIntUnsigned:
896 {
897 const char format[2] = "k";
898 success = PyArg_Parse (py_return, format, (unsigned long *) ret_value);
899 break;
900 }
901 case eLongLong:
902 {
903 const char format[2] = "L";
904 success = PyArg_Parse (py_return, format, (long long *) ret_value);
905 break;
906 }
907 case eLongLongUnsigned:
908 {
909 const char format[2] = "K";
910 success = PyArg_Parse (py_return, format, (unsigned long long *) ret_value);
911 break;
912 }
913 case eFloat:
914 {
915 const char format[2] = "f";
916 success = PyArg_Parse (py_return, format, (float *) ret_value);
917 break;
918 }
919 case eDouble:
920 {
921 const char format[2] = "d";
922 success = PyArg_Parse (py_return, format, (double *) ret_value);
923 break;
924 }
925 case eChar:
926 {
927 const char format[2] = "c";
928 success = PyArg_Parse (py_return, format, (char *) ret_value);
929 break;
930 }
931 default:
932 {}
933 }
934 Py_DECREF (py_return);
935 if (success)
936 ret_success = true;
937 else
938 ret_success = false;
939 }
940 }
941
942 py_error = PyErr_Occurred();
943 if (py_error != NULL)
944 {
945 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
946 PyErr_Print ();
947 PyErr_Clear();
948 ret_success = false;
949 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000950
951 LeaveSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000952
Caroline Tice202f6b82011-01-17 21:55:19 +0000953 if (need_to_release_lock)
954 ReleasePythonLock();
955
Chris Lattner24943d22010-06-08 16:52:24 +0000956 return ret_success;
957}
958
959bool
960ScriptInterpreterPython::ExecuteMultipleLines (const char *in_string)
961{
Caroline Tice202f6b82011-01-17 21:55:19 +0000962 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
963 bool need_to_release_lock = true;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000964
Caroline Tice202f6b82011-01-17 21:55:19 +0000965 if (CurrentThreadHasPythonLock())
966 need_to_release_lock = false;
967 else
968 {
969 while (!GetPythonLock (1))
970 fprintf (tmp_fh, "Python interpreter locked on another thread; waiting to acquire lock...\n");
971 }
972
973 EnterSession ();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000974
Chris Lattner24943d22010-06-08 16:52:24 +0000975 bool success = false;
976 PyObject *py_return = NULL;
977 PyObject *mainmod = PyImport_AddModule ("__main__");
978 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000979 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000980 PyObject *py_error = NULL;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000981 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000982
Caroline Tice0aa2e552011-01-14 00:29:16 +0000983 if (PyDict_Check (globals))
984 {
985 PyObject *key, *value;
986 Py_ssize_t pos = 0;
987
988 while (PyDict_Next (globals, &pos, &key, &value))
989 {
990 // We have stolen references to the key and value objects in the dictionary; we need to increment them now
991 // so that Python's garbage collector doesn't collect them out from under us.
992 Py_INCREF (key);
993 Py_INCREF (value);
994 if (strcmp (PyString_AsString (key), m_dictionary_name.c_str()) == 0)
995 locals = value;
996 }
997 }
998
999 if (locals == NULL)
1000 {
1001 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
1002 should_decrement_locals = true;
1003 }
1004
1005 if (locals == NULL)
1006 {
1007 locals = globals;
1008 should_decrement_locals = false;
1009 }
1010
1011 py_error = PyErr_Occurred();
1012 if (py_error != NULL)
1013 PyErr_Clear();
1014
Chris Lattner24943d22010-06-08 16:52:24 +00001015 if (in_string != NULL)
1016 {
1017 struct _node *compiled_node = PyParser_SimpleParseString (in_string, Py_file_input);
1018 if (compiled_node)
1019 {
1020 PyCodeObject *compiled_code = PyNode_Compile (compiled_node, "temp.py");
1021 if (compiled_code)
1022 {
1023 py_return = PyEval_EvalCode (compiled_code, globals, locals);
1024 if (py_return != NULL)
1025 {
1026 success = true;
1027 Py_DECREF (py_return);
1028 }
Caroline Tice0aa2e552011-01-14 00:29:16 +00001029 if (locals && should_decrement_locals)
1030 Py_DECREF (locals);
Chris Lattner24943d22010-06-08 16:52:24 +00001031 }
1032 }
1033 }
1034
1035 py_error = PyErr_Occurred ();
1036 if (py_error != NULL)
1037 {
1038 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
1039 PyErr_Print ();
1040 PyErr_Clear();
1041 success = false;
1042 }
1043
Caroline Tice0aa2e552011-01-14 00:29:16 +00001044 LeaveSession ();
1045
Caroline Tice202f6b82011-01-17 21:55:19 +00001046 if (need_to_release_lock)
1047 ReleasePythonLock();
1048
Chris Lattner24943d22010-06-08 16:52:24 +00001049 return success;
1050}
1051
1052static const char *g_reader_instructions = "Enter your Python command(s). Type 'DONE' to end.";
1053
1054size_t
1055ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback
1056(
1057 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +00001058 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +00001059 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +00001060 const char *bytes,
1061 size_t bytes_len
1062)
1063{
1064 static StringList commands_in_progress;
1065
Greg Clayton58928562011-02-09 01:08:52 +00001066 File &out_file = reader.GetDebugger().GetOutputFile();
Caroline Ticec95c6d12010-09-14 22:49:06 +00001067
Chris Lattner24943d22010-06-08 16:52:24 +00001068 switch (notification)
1069 {
1070 case eInputReaderActivate:
1071 {
1072 commands_in_progress.Clear();
Greg Clayton58928562011-02-09 01:08:52 +00001073 if (out_file.IsValid())
Chris Lattner24943d22010-06-08 16:52:24 +00001074 {
Greg Clayton58928562011-02-09 01:08:52 +00001075 out_file.Printf ("%s\n", g_reader_instructions);
Greg Clayton63094e02010-06-23 01:19:29 +00001076 if (reader.GetPrompt())
Greg Clayton58928562011-02-09 01:08:52 +00001077 out_file.Printf ("%s", reader.GetPrompt());
1078 out_file.Flush ();
Chris Lattner24943d22010-06-08 16:52:24 +00001079 }
1080 }
1081 break;
1082
1083 case eInputReaderDeactivate:
1084 break;
1085
1086 case eInputReaderReactivate:
Greg Clayton58928562011-02-09 01:08:52 +00001087 if (reader.GetPrompt() && out_file.IsValid())
Caroline Ticef81b4c52010-10-27 18:34:42 +00001088 {
Greg Clayton58928562011-02-09 01:08:52 +00001089 out_file.Printf ("%s", reader.GetPrompt());
1090 out_file.Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +00001091 }
Chris Lattner24943d22010-06-08 16:52:24 +00001092 break;
1093
Caroline Tice4a348082011-05-02 20:41:46 +00001094 case eInputReaderAsynchronousOutputWritten:
1095 break;
1096
Chris Lattner24943d22010-06-08 16:52:24 +00001097 case eInputReaderGotToken:
1098 {
1099 std::string temp_string (bytes, bytes_len);
1100 commands_in_progress.AppendString (temp_string.c_str());
Greg Clayton58928562011-02-09 01:08:52 +00001101 if (out_file.IsValid() && !reader.IsDone() && reader.GetPrompt())
Caroline Ticef81b4c52010-10-27 18:34:42 +00001102 {
Greg Clayton58928562011-02-09 01:08:52 +00001103 out_file.Printf ("%s", reader.GetPrompt());
1104 out_file.Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +00001105 }
Chris Lattner24943d22010-06-08 16:52:24 +00001106 }
1107 break;
1108
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001109 case eInputReaderEndOfFile:
1110 case eInputReaderInterrupt:
1111 // Control-c (SIGINT) & control-d both mean finish & exit.
1112 reader.SetIsDone(true);
1113
1114 // Control-c (SIGINT) ALSO means cancel; do NOT create a breakpoint command.
1115 if (notification == eInputReaderInterrupt)
1116 commands_in_progress.Clear();
1117
1118 // Fall through here...
1119
Chris Lattner24943d22010-06-08 16:52:24 +00001120 case eInputReaderDone:
1121 {
1122 BreakpointOptions *bp_options = (BreakpointOptions *)baton;
1123 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1124 data_ap->user_source.AppendList (commands_in_progress);
1125 if (data_ap.get())
1126 {
Greg Clayton63094e02010-06-23 01:19:29 +00001127 ScriptInterpreter *interpreter = reader.GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
Chris Lattner24943d22010-06-08 16:52:24 +00001128 if (interpreter)
1129 {
1130 if (interpreter->GenerateBreakpointCommandCallbackData (data_ap->user_source,
1131 data_ap->script_source))
1132 {
1133 if (data_ap->script_source.GetSize() == 1)
1134 {
1135 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1136 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
1137 }
1138 }
Caroline Ticeb447e842010-09-21 19:25:28 +00001139 else
Greg Clayton58928562011-02-09 01:08:52 +00001140 out_file.Printf ("Warning: No command attached to breakpoint.\n");
Chris Lattner24943d22010-06-08 16:52:24 +00001141 }
1142 else
1143 {
1144 // FIXME: Error processing.
1145 }
1146 }
1147 }
1148 break;
1149
1150 }
1151
1152 return bytes_len;
1153}
1154
1155void
Greg Clayton238c0a12010-09-18 01:14:36 +00001156ScriptInterpreterPython::CollectDataForBreakpointCommandCallback (BreakpointOptions *bp_options,
Chris Lattner24943d22010-06-08 16:52:24 +00001157 CommandReturnObject &result)
1158{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001159 Debugger &debugger = GetCommandInterpreter().GetDebugger();
1160
Greg Clayton63094e02010-06-23 01:19:29 +00001161 InputReaderSP reader_sp (new InputReader (debugger));
Chris Lattner24943d22010-06-08 16:52:24 +00001162
1163 if (reader_sp)
1164 {
1165 Error err = reader_sp->Initialize (
1166 ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback,
1167 bp_options, // baton
1168 eInputReaderGranularityLine, // token size, for feeding data to callback function
1169 "DONE", // end token
1170 "> ", // prompt
1171 true); // echo input
1172
1173 if (err.Success())
Greg Clayton63094e02010-06-23 01:19:29 +00001174 debugger.PushInputReader (reader_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001175 else
1176 {
1177 result.AppendError (err.AsCString());
1178 result.SetStatus (eReturnStatusFailed);
1179 }
1180 }
1181 else
1182 {
1183 result.AppendError("out of memory");
1184 result.SetStatus (eReturnStatusFailed);
1185 }
1186}
1187
Johnny Chen3e0571b2010-09-11 00:23:59 +00001188// Set a Python one-liner as the callback for the breakpoint.
Johnny Chend1c2dca2010-09-10 18:21:10 +00001189void
Greg Clayton238c0a12010-09-18 01:14:36 +00001190ScriptInterpreterPython::SetBreakpointCommandCallback (BreakpointOptions *bp_options,
Johnny Chend1c2dca2010-09-10 18:21:10 +00001191 const char *oneliner)
1192{
1193 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1194
1195 // It's necessary to set both user_source and script_source to the oneliner.
1196 // The former is used to generate callback description (as in breakpoint command list)
1197 // while the latter is used for Python to interpret during the actual callback.
Caroline Tice5136f942010-09-27 21:35:15 +00001198
Johnny Chend1c2dca2010-09-10 18:21:10 +00001199 data_ap->user_source.AppendString (oneliner);
Johnny Chend1c2dca2010-09-10 18:21:10 +00001200
Caroline Tice5136f942010-09-27 21:35:15 +00001201 if (GenerateBreakpointCommandCallbackData (data_ap->user_source, data_ap->script_source))
1202 {
1203 if (data_ap->script_source.GetSize() == 1)
1204 {
1205 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1206 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
1207 }
1208 }
1209
Johnny Chend1c2dca2010-09-10 18:21:10 +00001210 return;
1211}
1212
Chris Lattner24943d22010-06-08 16:52:24 +00001213bool
1214ScriptInterpreterPython::ExportFunctionDefinitionToInterpreter (StringList &function_def)
1215{
1216 // Convert StringList to one long, newline delimited, const char *.
1217 std::string function_def_string;
1218
1219 int num_lines = function_def.GetSize();
1220
1221 for (int i = 0; i < num_lines; ++i)
1222 {
1223 function_def_string.append (function_def.GetStringAtIndex(i));
1224 if (function_def_string.at (function_def_string.length() - 1) != '\n')
1225 function_def_string.append ("\n");
1226
1227 }
1228
1229 return ExecuteMultipleLines (function_def_string.c_str());
1230}
1231
1232bool
1233ScriptInterpreterPython::GenerateBreakpointCommandCallbackData (StringList &user_input, StringList &callback_data)
1234{
1235 static int num_created_functions = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001236 user_input.RemoveBlankLines ();
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001237 int num_lines = user_input.GetSize ();
1238 StreamString sstr;
Chris Lattner24943d22010-06-08 16:52:24 +00001239
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001240 // Check to see if we have any data; if not, just return.
1241 if (user_input.GetSize() == 0)
1242 return false;
1243
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001244 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1245 // frame and breakpoint location as parameters to the function.
Caroline Ticeb447e842010-09-21 19:25:28 +00001246
Caroline Ticeb447e842010-09-21 19:25:28 +00001247
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001248 sstr.Printf ("lldb_autogen_python_bp_callback_func_%d", num_created_functions);
1249 ++num_created_functions;
1250 std::string auto_generated_function_name = sstr.GetData();
Caroline Ticeb447e842010-09-21 19:25:28 +00001251
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001252 sstr.Clear();
Caroline Ticeb447e842010-09-21 19:25:28 +00001253 StringList auto_generated_function;
Caroline Ticeb447e842010-09-21 19:25:28 +00001254
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001255 // Create the function name & definition string.
1256
Caroline Tice0aa2e552011-01-14 00:29:16 +00001257 sstr.Printf ("def %s (frame, bp_loc, dict):", auto_generated_function_name.c_str());
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001258 auto_generated_function.AppendString (sstr.GetData());
Caroline Tice0aa2e552011-01-14 00:29:16 +00001259
1260 // Pre-pend code for setting up the session dictionary.
1261
1262 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1263 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1264 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1265 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1266 // global dictionary.
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001267
1268 // Wrap everything up inside the function, increasing the indentation.
Chris Lattner24943d22010-06-08 16:52:24 +00001269
1270 for (int i = 0; i < num_lines; ++i)
1271 {
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001272 sstr.Clear ();
1273 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1274 auto_generated_function.AppendString (sstr.GetData());
Caroline Ticeb447e842010-09-21 19:25:28 +00001275 }
Chris Lattner24943d22010-06-08 16:52:24 +00001276
Caroline Tice0aa2e552011-01-14 00:29:16 +00001277 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1278 // got written to the values in the global dictionary, not the session dictionary).
1279
1280 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1281 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1282 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1283 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1284
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001285 // Verify that the results are valid Python.
Chris Lattner24943d22010-06-08 16:52:24 +00001286
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001287 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
Caroline Ticeb447e842010-09-21 19:25:28 +00001288 {
Caroline Ticeb447e842010-09-21 19:25:28 +00001289 return false;
Chris Lattner24943d22010-06-08 16:52:24 +00001290 }
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001291
1292 // Store the name of the auto-generated function to be called.
1293
1294 callback_data.AppendString (auto_generated_function_name.c_str());
1295 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001296}
1297
Greg Clayton5144f382010-10-07 17:14:24 +00001298bool
1299ScriptInterpreterPython::BreakpointCallbackFunction
1300(
1301 void *baton,
1302 StoppointCallbackContext *context,
1303 user_id_t break_id,
1304 user_id_t break_loc_id
1305)
1306{
1307 BreakpointOptions::CommandData *bp_option_data = (BreakpointOptions::CommandData *) baton;
1308 const char *python_function_name = bp_option_data->script_source.GetStringAtIndex (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001309
1310 if (!context)
1311 return true;
1312
1313 Target *target = context->exe_ctx.target;
1314
1315 if (!target)
1316 return true;
1317
1318 Debugger &debugger = target->GetDebugger();
1319 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1320 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1321
1322 if (!script_interpreter)
1323 return true;
Greg Clayton5144f382010-10-07 17:14:24 +00001324
1325 if (python_function_name != NULL
1326 && python_function_name[0] != '\0')
1327 {
1328 Thread *thread = context->exe_ctx.thread;
Greg Claytone86cbb92011-03-22 01:14:58 +00001329 const StackFrameSP stop_frame_sp (thread->GetStackFrameSPForStackFramePtr (context->exe_ctx.frame));
Greg Clayton5144f382010-10-07 17:14:24 +00001330 BreakpointSP breakpoint_sp = target->GetBreakpointByID (break_id);
Greg Claytone86cbb92011-03-22 01:14:58 +00001331 if (breakpoint_sp)
Caroline Tice0aa2e552011-01-14 00:29:16 +00001332 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001333 const BreakpointLocationSP bp_loc_sp (breakpoint_sp->FindLocationByID (break_loc_id));
1334
1335 if (stop_frame_sp && bp_loc_sp)
Caroline Tice202f6b82011-01-17 21:55:19 +00001336 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001337 bool ret_val = true;
1338 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
1339 if (CurrentThreadHasPythonLock())
1340 {
1341 python_interpreter->EnterSession ();
1342 ret_val = g_swig_breakpoint_callback (python_function_name,
1343 python_interpreter->m_dictionary_name.c_str(),
1344 stop_frame_sp,
1345 bp_loc_sp);
1346 python_interpreter->LeaveSession ();
1347 }
1348 else
1349 {
1350 while (!GetPythonLock (1))
1351 fprintf (tmp_fh,
1352 "Python interpreter locked on another thread; waiting to acquire lock...\n");
1353 python_interpreter->EnterSession ();
1354 ret_val = g_swig_breakpoint_callback (python_function_name,
1355 python_interpreter->m_dictionary_name.c_str(),
1356 stop_frame_sp,
1357 bp_loc_sp);
1358 python_interpreter->LeaveSession ();
1359 ReleasePythonLock ();
1360 }
1361 return ret_val;
Caroline Tice202f6b82011-01-17 21:55:19 +00001362 }
Caroline Tice0aa2e552011-01-14 00:29:16 +00001363 }
Greg Clayton5144f382010-10-07 17:14:24 +00001364 }
1365 // We currently always true so we stop in case anything goes wrong when
1366 // trying to call the script function
1367 return true;
1368}
Caroline Tice2ade6112010-11-10 19:18:14 +00001369
1370lldb::thread_result_t
1371ScriptInterpreterPython::RunEmbeddedPythonInterpreter (lldb::thread_arg_t baton)
1372{
1373 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
1374
1375 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
1376
1377 if (log)
1378 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread starting...", baton);
1379
1380 char error_str[1024];
1381 const char *pty_slave_name = script_interpreter->m_embedded_python_pty.GetSlaveName (error_str, sizeof (error_str));
Caroline Tice202f6b82011-01-17 21:55:19 +00001382 bool need_to_release_lock = true;
1383 bool safe_to_run = false;
Caroline Tice0aa2e552011-01-14 00:29:16 +00001384
Caroline Tice202f6b82011-01-17 21:55:19 +00001385 if (CurrentThreadHasPythonLock())
1386 {
1387 safe_to_run = true;
1388 need_to_release_lock = false;
1389 }
1390 else
1391 {
1392 int interval = 1;
1393 safe_to_run = GetPythonLock (interval);
1394 while (!safe_to_run)
1395 {
1396 interval = interval * 2;
1397 safe_to_run = GetPythonLock (interval);
1398 }
1399 }
1400
1401 if (pty_slave_name != NULL && safe_to_run)
1402 {
Caroline Tice2ade6112010-11-10 19:18:14 +00001403 StreamString run_string;
Caroline Tice2ade6112010-11-10 19:18:14 +00001404
Caroline Tice202f6b82011-01-17 21:55:19 +00001405 script_interpreter->EnterSession ();
1406
Caroline Tice0aa2e552011-01-14 00:29:16 +00001407 run_string.Printf ("run_one_line (%s, 'save_stderr = sys.stderr')", 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 = sys.stdout')", script_interpreter->m_dictionary_name.c_str());
1412 PyRun_SimpleString (run_string.GetData());
1413 run_string.Clear ();
1414
1415 run_string.Printf ("run_one_line (%s, 'save_stdin = sys.stdin')", script_interpreter->m_dictionary_name.c_str());
1416 PyRun_SimpleString (run_string.GetData());
1417 run_string.Clear ();
1418
1419 run_string.Printf ("run_one_line (%s, \"sys.stdin = open ('%s', 'r')\")", script_interpreter->m_dictionary_name.c_str(),
1420 pty_slave_name);
1421 PyRun_SimpleString (run_string.GetData());
1422 run_string.Clear ();
1423
Johnny Chen8054ba32011-03-11 00:28:50 +00001424 // The following call drops into the embedded interpreter loop and stays there until the
1425 // user chooses to exit from the Python interpreter.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001426
Caroline Ticece207c12011-03-11 00:21:55 +00001427 // When in the embedded interpreter, the user can call arbitrary system and Python stuff, which may require
Johnny Chen8054ba32011-03-11 00:28:50 +00001428 // 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 +00001429 // calls to Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS.
1430
1431 // We ALSO need to surround the call to the embedded interpreter with calls to PyGILState_Ensure and
1432 // PyGILState_Release. This is because this embedded interpreter is being run on a DIFFERENT THREAD than
1433 // the thread on which the call to Py_Initialize (and PyEval_InitThreads) was called. Those initializations
1434 // called PyGILState_Ensure on *that* thread, but it also needs to be called on *this* thread. Otherwise,
1435 // if the user calls Python code that does threading stuff, the interpreter state will be off, and things could
1436 // hang (it's happened before).
1437
Caroline Tice9d352ce2011-03-07 23:24:28 +00001438 Py_BEGIN_ALLOW_THREADS
1439 PyGILState_STATE gstate = PyGILState_Ensure();
1440
Caroline Tice0aa2e552011-01-14 00:29:16 +00001441 run_string.Printf ("run_python_interpreter (%s)", script_interpreter->m_dictionary_name.c_str());
1442 PyRun_SimpleString (run_string.GetData());
1443 run_string.Clear ();
Caroline Tice2ade6112010-11-10 19:18:14 +00001444
Caroline Tice9d352ce2011-03-07 23:24:28 +00001445 PyGILState_Release (gstate);
1446 Py_END_ALLOW_THREADS
1447
Caroline Tice0aa2e552011-01-14 00:29:16 +00001448 run_string.Printf ("run_one_line (%s, 'sys.stdin = save_stdin')", script_interpreter->m_dictionary_name.c_str());
1449 PyRun_SimpleString (run_string.GetData());
1450 run_string.Clear();
1451
1452 run_string.Printf ("run_one_line (%s, 'sys.stderr = save_stderr')", script_interpreter->m_dictionary_name.c_str());
1453 PyRun_SimpleString (run_string.GetData());
1454 run_string.Clear();
Caroline Tice202f6b82011-01-17 21:55:19 +00001455
1456 script_interpreter->LeaveSession ();
1457
Caroline Tice2ade6112010-11-10 19:18:14 +00001458 }
1459
Caroline Tice202f6b82011-01-17 21:55:19 +00001460 if (!safe_to_run)
1461 fprintf ((script_interpreter->m_dbg_stdout ? script_interpreter->m_dbg_stdout : stdout),
1462 "Python interpreter locked on another thread; unable to acquire lock.\n");
1463
1464 if (need_to_release_lock)
1465 ReleasePythonLock ();
1466
Caroline Tice2ade6112010-11-10 19:18:14 +00001467 if (script_interpreter->m_embedded_thread_input_reader_sp)
1468 script_interpreter->m_embedded_thread_input_reader_sp->SetIsDone (true);
1469
1470 script_interpreter->m_embedded_python_pty.CloseSlaveFileDescriptor();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001471
1472 script_interpreter->m_pty_slave_is_open = false;
Caroline Tice2ade6112010-11-10 19:18:14 +00001473
1474 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT);
1475 if (log)
1476 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread exiting...", baton);
1477
1478
Johnny Chen8054ba32011-03-11 00:28:50 +00001479 // Clean up the input reader and make the debugger pop it off the stack.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001480 Debugger &debugger = script_interpreter->GetCommandInterpreter().GetDebugger();
Caroline Tice2ade6112010-11-10 19:18:14 +00001481 const InputReaderSP reader_sp = script_interpreter->m_embedded_thread_input_reader_sp;
1482 script_interpreter->m_embedded_thread_input_reader_sp.reset();
1483 debugger.PopInputReader (reader_sp);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001484
Caroline Tice2ade6112010-11-10 19:18:14 +00001485 return NULL;
1486}
1487
1488
Caroline Tice0aa2e552011-01-14 00:29:16 +00001489void
Greg Claytone86cbb92011-03-22 01:14:58 +00001490ScriptInterpreterPython::InitializeInterpreter (SWIGInitCallback python_swig_init_callback,
1491 SWIGBreakpointCallbackFunction python_swig_breakpoint_callback)
1492{
1493 g_swig_init_callback = python_swig_init_callback;
1494 g_swig_breakpoint_callback = python_swig_breakpoint_callback;
1495}
1496
1497void
1498ScriptInterpreterPython::InitializePrivate ()
Caroline Tice0aa2e552011-01-14 00:29:16 +00001499{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001500 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
1501
Greg Clayton0fdd4a02011-02-07 23:24:47 +00001502 // Python will muck with STDIN terminal state, so save off any current TTY
1503 // settings so we can restore them.
1504 TerminalState stdin_tty_state;
1505 stdin_tty_state.Save(STDIN_FILENO, false);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001506
1507 // Find the module that owns this code and use that path we get to
1508 // set the PYTHONPATH appropriately.
1509
1510 FileSpec file_spec;
1511 char python_dir_path[PATH_MAX];
1512 if (Host::GetLLDBPath (ePathTypePythonDir, file_spec))
1513 {
1514 std::string python_path;
1515 const char *curr_python_path = ::getenv ("PYTHONPATH");
1516 if (curr_python_path)
1517 {
1518 // We have a current value for PYTHONPATH, so lets append to it
1519 python_path.append (curr_python_path);
1520 }
1521
1522 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
1523 {
1524 if (!python_path.empty())
1525 python_path.append (1, ':');
1526 python_path.append (python_dir_path);
1527 }
1528
1529 if (Host::GetLLDBPath (ePathTypeLLDBShlibDir, file_spec))
1530 {
1531 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
1532 {
1533 if (!python_path.empty())
1534 python_path.append (1, ':');
1535 python_path.append (python_dir_path);
1536 }
1537 }
1538 const char *pathon_path_env_cstr = python_path.c_str();
1539 ::setenv ("PYTHONPATH", pathon_path_env_cstr, 1);
1540 }
1541
Caroline Tice9d352ce2011-03-07 23:24:28 +00001542 PyEval_InitThreads ();
Caroline Ticea54461d2011-06-02 22:09:43 +00001543 Py_InitializeEx (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001544
1545 PyObject *compiled_module = Py_CompileString (embedded_interpreter_string,
1546 "embedded_interpreter.py",
1547 Py_file_input);
1548
1549 PyObject *py_error = PyErr_Occurred ();
1550 if (py_error != NULL)
1551 {
1552 PyErr_Print();
1553 PyErr_Clear();
1554 }
1555
1556
Greg Claytone86cbb92011-03-22 01:14:58 +00001557 // Initialize SWIG after setting up python
1558 assert (g_swig_init_callback != NULL);
1559 g_swig_init_callback ();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001560
1561 // Update the path python uses to search for modules to include the current directory.
1562
1563 int success = PyRun_SimpleString ("import sys");
1564 success = PyRun_SimpleString ("sys.path.append ('.')");
1565
1566 PyObject *pmod = NULL;
1567
1568 if (compiled_module)
1569 {
1570 pmod = PyImport_ExecCodeModule (const_cast<char*> ("embedded_interpreter"),
1571 compiled_module);
1572 Py_DECREF (compiled_module);
1573 }
1574
1575 if (pmod != NULL)
1576 {
1577 PyRun_SimpleString ("from embedded_interpreter import run_python_interpreter");
1578 PyRun_SimpleString ("from embedded_interpreter import run_one_line");
1579 PyRun_SimpleString ("import sys");
1580 PyRun_SimpleString ("from termios import *");
1581 Py_DECREF (pmod);
1582 }
Greg Clayton99208582011-02-07 19:04:58 +00001583
Greg Clayton0fdd4a02011-02-07 23:24:47 +00001584 stdin_tty_state.Restore();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001585}
1586
Greg Claytone86cbb92011-03-22 01:14:58 +00001587//void
1588//ScriptInterpreterPython::Terminate ()
1589//{
1590// // We are intentionally NOT calling Py_Finalize here (this would be the logical place to call it). Calling
1591// // Py_Finalize here causes test suite runs to seg fault: The test suite runs in Python. It registers
1592// // SBDebugger::Terminate to be called 'at_exit'. When the test suite Python harness finishes up, it calls
1593// // Py_Finalize, which calls all the 'at_exit' registered functions. SBDebugger::Terminate calls Debugger::Terminate,
1594// // which calls lldb::Terminate, which calls ScriptInterpreter::Terminate, which calls
1595// // ScriptInterpreterPython::Terminate. So if we call Py_Finalize here, we end up with Py_Finalize being called from
1596// // within Py_Finalize, which results in a seg fault.
1597// //
1598// // Since this function only gets called when lldb is shutting down and going away anyway, the fact that we don't
1599// // actually call Py_Finalize should not cause any problems (everything should shut down/go away anyway when the
1600// // process exits).
1601// //
1602//// Py_Finalize ();
1603//}