blob: 224ea7f6d37334cea6189558d45b76feae990004 [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
11// the *FIRST* header file included:
12
Caroline Tice5790e062010-10-28 21:51:20 +000013#if defined (__APPLE__)
14#include <Python/Python.h>
15#else
Chris Lattner24943d22010-06-08 16:52:24 +000016#include <Python.h>
Caroline Tice5790e062010-10-28 21:51:20 +000017#endif
Chris Lattner24943d22010-06-08 16:52:24 +000018
19#include "lldb/Interpreter/ScriptInterpreterPython.h"
20
21
22#include <sys/ioctl.h>
23#include <termios.h>
24#include <stdlib.h>
25#include <stdio.h>
26
27#include <string>
28
Greg Clayton5144f382010-10-07 17:14:24 +000029#include "lldb/API/SBFrame.h"
30#include "lldb/API/SBBreakpointLocation.h"
Chris Lattner24943d22010-06-08 16:52:24 +000031#include "lldb/Breakpoint/Breakpoint.h"
32#include "lldb/Breakpoint/BreakpointLocation.h"
Greg Clayton63094e02010-06-23 01:19:29 +000033#include "lldb/Breakpoint/StoppointCallbackContext.h"
Chris Lattner24943d22010-06-08 16:52:24 +000034#include "lldb/Core/Debugger.h"
35#include "lldb/Core/FileSpec.h"
36#include "lldb/Core/InputReader.h"
37#include "lldb/Core/Stream.h"
38#include "lldb/Core/StreamString.h"
39#include "lldb/Core/Timer.h"
40#include "lldb/Host/Host.h"
41#include "lldb/Interpreter/CommandInterpreter.h"
42#include "lldb/Interpreter/CommandReturnObject.h"
Greg Clayton63094e02010-06-23 01:19:29 +000043#include "lldb/Core/Debugger.h"
Chris Lattner24943d22010-06-08 16:52:24 +000044#include "lldb/Target/Process.h"
Greg Clayton5144f382010-10-07 17:14:24 +000045#include "lldb/Target/Thread.h"
Chris Lattner24943d22010-06-08 16:52:24 +000046
Greg Clayton121f3312010-07-07 18:40:03 +000047// This function is in the C++ output file generated by SWIG after it is
48// run on all of the headers in "lldb/API/SB*.h"
Chris Lattner24943d22010-06-08 16:52:24 +000049extern "C" void init_lldb (void);
50
Greg Clayton5144f382010-10-07 17:14:24 +000051extern "C" bool
52LLDBSWIGPythonBreakpointCallbackFunction
53(
54 const char *python_function_name,
Caroline Tice0aa2e552011-01-14 00:29:16 +000055 const char *session_dictionary_name,
Greg Clayton5144f382010-10-07 17:14:24 +000056 lldb::SBFrame& sb_frame,
57 lldb::SBBreakpointLocation& sb_bp_loc
58);
59
Chris Lattner24943d22010-06-08 16:52:24 +000060using namespace lldb;
61using namespace lldb_private;
62
63const char embedded_interpreter_string[] =
64"import readline\n\
65import code\n\
66import sys\n\
67import traceback\n\
68\n\
69class SimpleREPL(code.InteractiveConsole):\n\
70 def __init__(self, prompt, dict):\n\
71 code.InteractiveConsole.__init__(self,dict)\n\
72 self.prompt = prompt\n\
73 self.loop_exit = False\n\
74 self.dict = dict\n\
75\n\
76 def interact(self):\n\
77 try:\n\
78 sys.ps1\n\
79 except AttributeError:\n\
80 sys.ps1 = \">>> \"\n\
81 try:\n\
82 sys.ps2\n\
83 except AttributeError:\n\
84 sys.ps2 = \"... \"\n\
85\n\
86 while not self.loop_exit:\n\
87 try:\n\
88 self.read_py_command()\n\
89 except (SystemExit, EOFError):\n\
90 # EOF while in Python just breaks out to top level.\n\
91 self.write('\\n')\n\
92 self.loop_exit = True\n\
93 break\n\
94 except KeyboardInterrupt:\n\
95 self.write(\"\\nKeyboardInterrupt\\n\")\n\
96 self.resetbuffer()\n\
97 more = 0\n\
98 except:\n\
99 traceback.print_exc()\n\
100\n\
101 def process_input (self, in_str):\n\
102 # Canonicalize the format of the input string\n\
103 temp_str = in_str\n\
104 temp_str.strip(' \t')\n\
105 words = temp_str.split()\n\
106 temp_str = ('').join(words)\n\
107\n\
108 # Check the input string to see if it was the quit\n\
109 # command. If so, intercept it, so that it doesn't\n\
110 # close stdin on us!\n\
Jason Molendaa8a5e562010-06-09 21:56:00 +0000111 if (temp_str.lower() == \"quit()\" or temp_str.lower() == \"exit()\"):\n\
Chris Lattner24943d22010-06-08 16:52:24 +0000112 self.loop_exit = True\n\
113 in_str = \"raise SystemExit \"\n\
114 return in_str\n\
115\n\
116 def my_raw_input (self, prompt):\n\
117 stream = sys.stdout\n\
118 stream.write (prompt)\n\
119 stream.flush ()\n\
120 try:\n\
121 line = sys.stdin.readline()\n\
122 except KeyboardInterrupt:\n\
123 line = \" \\n\"\n\
124 except (SystemExit, EOFError):\n\
125 line = \"quit()\\n\"\n\
126 if not line:\n\
127 raise EOFError\n\
128 if line[-1] == '\\n':\n\
129 line = line[:-1]\n\
130 return line\n\
131\n\
132 def read_py_command(self):\n\
133 # Read off a complete Python command.\n\
134 more = 0\n\
135 while 1:\n\
136 if more:\n\
137 prompt = sys.ps2\n\
138 else:\n\
139 prompt = sys.ps1\n\
140 line = self.my_raw_input(prompt)\n\
141 # Can be None if sys.stdin was redefined\n\
142 encoding = getattr(sys.stdin, \"encoding\", None)\n\
143 if encoding and not isinstance(line, unicode):\n\
144 line = line.decode(encoding)\n\
145 line = self.process_input (line)\n\
146 more = self.push(line)\n\
147 if not more:\n\
148 break\n\
149\n\
Caroline Tice0aa2e552011-01-14 00:29:16 +0000150 def one_line (self, input):\n\
151 line = self.process_input (input)\n\
152 more = self.push(line)\n\
153 if more:\n\
154 self.write (\"Input not a complete line.\")\n\
155 self.resetbuffer()\n\
156 more = 0\n\
157\n\
Chris Lattner24943d22010-06-08 16:52:24 +0000158def run_python_interpreter (dict):\n\
159 # Pass in the dictionary, for continuity from one session to the next.\n\
160 repl = SimpleREPL('>>> ', dict)\n\
Caroline Tice0aa2e552011-01-14 00:29:16 +0000161 repl.interact()\n\
162\n\
163def run_one_line (dict, input_string):\n\
164 repl = SimpleREPL ('', dict)\n\
165 repl.one_line (input_string)\n";
Chris Lattner24943d22010-06-08 16:52:24 +0000166
167static int
168_check_and_flush (FILE *stream)
169{
170 int prev_fail = ferror (stream);
171 return fflush (stream) || prev_fail ? EOF : 0;
172}
173
Caroline Tice202f6b82011-01-17 21:55:19 +0000174static Predicate<lldb::tid_t> &
175PythonMutexPredicate ()
Caroline Tice0aa2e552011-01-14 00:29:16 +0000176{
Caroline Tice202f6b82011-01-17 21:55:19 +0000177 static lldb_private::Predicate<lldb::tid_t> g_interpreter_is_running (LLDB_INVALID_THREAD_ID);
178 return g_interpreter_is_running;
179}
180
181static bool
182CurrentThreadHasPythonLock ()
183{
184 TimeValue timeout;
185
186 timeout = TimeValue::Now(); // Don't wait any time.
187
188 return PythonMutexPredicate().WaitForValueEqualTo (Host::GetCurrentThreadID(), &timeout, NULL);
189}
190
191static bool
192GetPythonLock (uint32_t seconds_to_wait)
193{
194
195 TimeValue timeout;
196
197 if (seconds_to_wait != UINT32_MAX)
198 {
199 timeout = TimeValue::Now();
200 timeout.OffsetWithSeconds (seconds_to_wait);
201 }
202
203 return PythonMutexPredicate().WaitForValueEqualToAndSetValueTo (LLDB_INVALID_THREAD_ID,
204 Host::GetCurrentThreadID(), &timeout, NULL);
205}
206
207static void
208ReleasePythonLock ()
209{
210 PythonMutexPredicate().SetValue (LLDB_INVALID_THREAD_ID, eBroadcastAlways);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000211}
212
Greg Clayton63094e02010-06-23 01:19:29 +0000213ScriptInterpreterPython::ScriptInterpreterPython (CommandInterpreter &interpreter) :
Greg Clayton238c0a12010-09-18 01:14:36 +0000214 ScriptInterpreter (interpreter, eScriptLanguagePython),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000215 m_embedded_python_pty (),
216 m_embedded_thread_input_reader_sp (),
217 m_dbg_stdout (interpreter.GetDebugger().GetOutputFileHandle()),
218 m_new_sysout (NULL),
219 m_dictionary_name (interpreter.GetDebugger().GetInstanceName().AsCString()),
Caroline Tice2ade6112010-11-10 19:18:14 +0000220 m_termios (),
221 m_termios_valid (false),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000222 m_session_is_active (false),
223 m_pty_slave_is_open (false),
224 m_valid_session (true)
Chris Lattner24943d22010-06-08 16:52:24 +0000225{
226
Caroline Tice202f6b82011-01-17 21:55:19 +0000227 bool safe_to_run = false;
228 bool need_to_release_lock = true;
229 int interval = 5; // Number of seconds to try getting the Python lock before timing out.
230
231 // We don't dare exit this function without finishing setting up the script interpreter, so we must wait until
232 // we can get the Python lock.
233
234 if (CurrentThreadHasPythonLock())
235 {
236 safe_to_run = true;
237 need_to_release_lock = false;
238 }
239
240 while (!safe_to_run)
241 {
242 safe_to_run = GetPythonLock (interval);
243 if (!safe_to_run)
244 {
245 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
246 fprintf (tmp_fh,
247 "Python interpreter is locked on another thread; "
248 "please release interpreter in order to continue.\n");
249 interval = interval * 2;
250 }
251 }
252
Caroline Tice0aa2e552011-01-14 00:29:16 +0000253 m_dictionary_name.append("_dict");
254 StreamString run_string;
255 run_string.Printf ("%s = dict()", m_dictionary_name.c_str());
256 PyRun_SimpleString (run_string.GetData());
Caroline Tice5867f6b2010-10-18 18:24:17 +0000257
Caroline Tice0aa2e552011-01-14 00:29:16 +0000258 run_string.Clear();
259 run_string.Printf ("run_one_line (%s, 'import sys')", m_dictionary_name.c_str());
260 PyRun_SimpleString (run_string.GetData());
261
262 // Importing 'lldb' module calls SBDebugger::Initialize, which calls Debugger::Initialize, which increments a
263 // global debugger ref-count; therefore we need to check the ref-count before and after importing lldb, and if the
264 // ref-count increased we need to call Debugger::Terminate here to decrement the ref-count so that when the final
265 // call to Debugger::Terminate is made, the ref-count has the correct value.
266 //
267 // Bonus question: Why doesn't the ref-count always increase? Because sometimes lldb has already been imported, in
268 // which case the code inside it, including the call to SBDebugger::Initialize(), does not get executed.
Caroline Tice5867f6b2010-10-18 18:24:17 +0000269
Caroline Tice0aa2e552011-01-14 00:29:16 +0000270 int old_count = Debugger::TestDebuggerRefCount();
Chris Lattner24943d22010-06-08 16:52:24 +0000271
Caroline Tice0aa2e552011-01-14 00:29:16 +0000272 run_string.Clear();
273 run_string.Printf ("run_one_line (%s, 'import lldb')", m_dictionary_name.c_str());
274 PyRun_SimpleString (run_string.GetData());
Greg Clayton24b48ff2010-10-17 22:03:32 +0000275
Caroline Tice0aa2e552011-01-14 00:29:16 +0000276 int new_count = Debugger::TestDebuggerRefCount();
Chris Lattner24943d22010-06-08 16:52:24 +0000277
Caroline Tice0aa2e552011-01-14 00:29:16 +0000278 if (new_count > old_count)
279 Debugger::Terminate();
Caroline Tice5867f6b2010-10-18 18:24:17 +0000280
Caroline Tice0aa2e552011-01-14 00:29:16 +0000281 run_string.Clear();
282 run_string.Printf ("run_one_line (%s, 'import copy')", m_dictionary_name.c_str());
283 PyRun_SimpleString (run_string.GetData());
284
285 run_string.Clear();
286 run_string.Printf ("run_one_line (%s, 'lldb.debugger_unique_id = %d')", m_dictionary_name.c_str(),
287 interpreter.GetDebugger().GetID());
288 PyRun_SimpleString (run_string.GetData());
289
290 if (m_dbg_stdout != NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000291 {
Caroline Tice0aa2e552011-01-14 00:29:16 +0000292 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
Caroline Tice5867f6b2010-10-18 18:24:17 +0000293 }
Caroline Tice202f6b82011-01-17 21:55:19 +0000294
295 if (need_to_release_lock)
296 ReleasePythonLock();
Chris Lattner24943d22010-06-08 16:52:24 +0000297}
298
299ScriptInterpreterPython::~ScriptInterpreterPython ()
300{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000301 Debugger &debugger = GetCommandInterpreter().GetDebugger();
302
303 if (m_embedded_thread_input_reader_sp.get() != NULL)
304 {
305 m_embedded_thread_input_reader_sp->SetIsDone (true);
306 m_embedded_python_pty.CloseSlaveFileDescriptor();
307 m_pty_slave_is_open = false;
308 const InputReaderSP reader_sp = m_embedded_thread_input_reader_sp;
309 m_embedded_thread_input_reader_sp.reset();
310 debugger.PopInputReader (reader_sp);
311 }
312
313 if (m_new_sysout)
314 {
Caroline Tice202f6b82011-01-17 21:55:19 +0000315 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
316 if (!CurrentThreadHasPythonLock ())
317 {
318 while (!GetPythonLock (1))
319 fprintf (tmp_fh, "Python interpreter locked on another thread; waiting to acquire lock...\n");
320 Py_DECREF (m_new_sysout);
321 ReleasePythonLock ();
322 }
323 else
324 Py_DECREF (m_new_sysout);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000325 }
Chris Lattner24943d22010-06-08 16:52:24 +0000326}
327
Caroline Tice0aa2e552011-01-14 00:29:16 +0000328void
329ScriptInterpreterPython::ResetOutputFileHandle (FILE *fh)
330{
331 if (fh == NULL)
332 return;
333
334 m_dbg_stdout = fh;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000335
Caroline Tice202f6b82011-01-17 21:55:19 +0000336 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
337 if (!CurrentThreadHasPythonLock ())
338 {
339 while (!GetPythonLock (1))
340 fprintf (tmp_fh, "Python interpreter locked on another thread; waiting to acquire lock...\n");
341 EnterSession ();
342 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
343 LeaveSession ();
344 ReleasePythonLock ();
345 }
346 else
347 {
348 EnterSession ();
349 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
350 LeaveSession ();
351 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000352}
353
354void
355ScriptInterpreterPython::LeaveSession ()
356{
357 m_session_is_active = false;
358}
359
360void
361ScriptInterpreterPython::EnterSession ()
362{
363 // If we have already entered the session, without having officially 'left' it, then there is no need to
364 // 'enter' it again.
365
366 if (m_session_is_active)
367 return;
368
369 m_session_is_active = true;
370
Caroline Tice202f6b82011-01-17 21:55:19 +0000371 StreamString run_string;
372
373 run_string.Printf ("run_one_line (%s, 'lldb.debugger_unique_id = %d')", m_dictionary_name.c_str(),
374 GetCommandInterpreter().GetDebugger().GetID());
375 PyRun_SimpleString (run_string.GetData());
376
Caroline Tice0aa2e552011-01-14 00:29:16 +0000377
378 PyObject *sysmod = PyImport_AddModule ("sys");
379 PyObject *sysdict = PyModule_GetDict (sysmod);
380
381 if ((m_new_sysout != NULL)
382 && (sysmod != NULL)
383 && (sysdict != NULL))
384 PyDict_SetItemString (sysdict, "stdout", m_new_sysout);
385
386 if (PyErr_Occurred())
387 PyErr_Clear ();
388
Caroline Tice0aa2e552011-01-14 00:29:16 +0000389 if (!m_pty_slave_is_open)
390 {
Caroline Tice202f6b82011-01-17 21:55:19 +0000391 run_string.Clear();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000392 run_string.Printf ("run_one_line (%s, \"new_stdin = open('%s', 'r')\")", m_dictionary_name.c_str(),
393 m_pty_slave_name.c_str());
394 PyRun_SimpleString (run_string.GetData());
395 m_pty_slave_is_open = true;
396
397 run_string.Clear();
398 run_string.Printf ("run_one_line (%s, 'sys.stdin = new_stdin')", m_dictionary_name.c_str());
399 PyRun_SimpleString (run_string.GetData());
400 }
401}
402
403
Johnny Chen60dde642010-07-30 22:33:14 +0000404bool
Greg Clayton238c0a12010-09-18 01:14:36 +0000405ScriptInterpreterPython::ExecuteOneLine (const char *command, CommandReturnObject *result)
Chris Lattner24943d22010-06-08 16:52:24 +0000406{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000407 if (!m_valid_session)
408 return false;
409
Caroline Tice0aa2e552011-01-14 00:29:16 +0000410
Caroline Tice0aa2e552011-01-14 00:29:16 +0000411
Caroline Tice4a461da2011-01-14 21:09:29 +0000412 // We want to call run_one_line, passing in the dictionary and the command string. We cannot do this through
413 // PyRun_SimpleString here because the command string may contain escaped characters, and putting it inside
414 // another string to pass to PyRun_SimpleString messes up the escaping. So we use the following more complicated
415 // method to pass the command string directly down to Python.
416
417
Caroline Tice202f6b82011-01-17 21:55:19 +0000418 bool need_to_release_lock = true;
419
420 if (CurrentThreadHasPythonLock())
421 need_to_release_lock = false;
422 else if (!GetPythonLock (1))
423 {
424 fprintf ((m_dbg_stdout ? m_dbg_stdout : stdout),
425 "Python interpreter is currently locked by another thread; unable to process command.\n");
426 return false;
427 }
428
429 EnterSession ();
Caroline Tice4a461da2011-01-14 21:09:29 +0000430 bool success = false;
431
Greg Clayton63094e02010-06-23 01:19:29 +0000432 if (command)
Chris Lattner24943d22010-06-08 16:52:24 +0000433 {
Caroline Tice4a461da2011-01-14 21:09:29 +0000434 // Find the correct script interpreter dictionary in the main module.
435 PyObject *main_mod = PyImport_AddModule ("__main__");
436 PyObject *script_interpreter_dict = NULL;
437 if (main_mod != NULL)
438 {
439 PyObject *main_dict = PyModule_GetDict (main_mod);
440 if ((main_dict != NULL)
441 && PyDict_Check (main_dict))
442 {
443 // Go through the main dictionary looking for the correct python script interpreter dictionary
444 PyObject *key, *value;
445 Py_ssize_t pos = 0;
446
447 while (PyDict_Next (main_dict, &pos, &key, &value))
448 {
449 // We have stolen references to the key and value objects in the dictionary; we need to increment
450 // them now so that Python's garbage collector doesn't collect them out from under us.
451 Py_INCREF (key);
452 Py_INCREF (value);
453 if (strcmp (PyString_AsString (key), m_dictionary_name.c_str()) == 0)
454 {
455 script_interpreter_dict = value;
456 break;
457 }
458 }
459 }
460
461 if (script_interpreter_dict != NULL)
462 {
463 PyObject *pfunc = NULL;
464 PyObject *pmod = PyImport_AddModule ("embedded_interpreter");
465 if (pmod != NULL)
466 {
467 PyObject *pmod_dict = PyModule_GetDict (pmod);
468 if ((pmod_dict != NULL)
469 && PyDict_Check (pmod_dict))
470 {
471 PyObject *key, *value;
472 Py_ssize_t pos = 0;
473
474 while (PyDict_Next (pmod_dict, &pos, &key, &value))
475 {
476 Py_INCREF (key);
477 Py_INCREF (value);
478 if (strcmp (PyString_AsString (key), "run_one_line") == 0)
479 {
480 pfunc = value;
481 break;
482 }
483 }
484
485 PyObject *string_arg = PyString_FromString (command);
486 if (pfunc && string_arg && PyCallable_Check (pfunc))
487 {
488 PyObject *pargs = PyTuple_New (2);
489 if (pargs != NULL)
490 {
491 PyTuple_SetItem (pargs, 0, script_interpreter_dict);
492 PyTuple_SetItem (pargs, 1, string_arg);
493 PyObject *pvalue = PyObject_CallObject (pfunc, pargs);
494 Py_DECREF (pargs);
495 if (pvalue != NULL)
496 {
497 Py_DECREF (pvalue);
498 success = true;
499 }
500 else if (PyErr_Occurred ())
501 {
502 PyErr_Print();
503 PyErr_Clear();
504 }
505 }
506 }
507 }
508 }
509 Py_INCREF (script_interpreter_dict);
510 }
511 }
Greg Clayton63094e02010-06-23 01:19:29 +0000512
Caroline Tice0aa2e552011-01-14 00:29:16 +0000513 LeaveSession ();
514
Caroline Tice202f6b82011-01-17 21:55:19 +0000515 if (need_to_release_lock)
516 ReleasePythonLock();
517
Caroline Tice4a461da2011-01-14 21:09:29 +0000518 if (success)
Johnny Chen60dde642010-07-30 22:33:14 +0000519 return true;
520
521 // The one-liner failed. Append the error message.
522 if (result)
523 result->AppendErrorWithFormat ("python failed attempting to evaluate '%s'\n", command);
524 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000525 }
Johnny Chen60dde642010-07-30 22:33:14 +0000526
Caroline Tice0aa2e552011-01-14 00:29:16 +0000527 LeaveSession ();
Caroline Tice202f6b82011-01-17 21:55:19 +0000528
529 if (need_to_release_lock)
530 ReleasePythonLock ();
531
Johnny Chen60dde642010-07-30 22:33:14 +0000532 if (result)
533 result->AppendError ("empty command passed to python\n");
534 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000535}
536
537
538
539size_t
540ScriptInterpreterPython::InputReaderCallback
541(
542 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000543 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000544 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000545 const char *bytes,
546 size_t bytes_len
547)
548{
Caroline Tice2ade6112010-11-10 19:18:14 +0000549 lldb::thread_t embedded_interpreter_thread;
550 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
551
Chris Lattner24943d22010-06-08 16:52:24 +0000552 if (baton == NULL)
553 return 0;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000554
555 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
556
557 if (script_interpreter->m_script_lang != eScriptLanguagePython)
558 return 0;
559
Caroline Tice67637d82010-12-15 19:51:12 +0000560 FILE *out_fh = reader.GetDebugger().GetOutputFileHandle ();
561 if (out_fh == NULL)
562 out_fh = stdout;
563
Chris Lattner24943d22010-06-08 16:52:24 +0000564 switch (notification)
565 {
566 case eInputReaderActivate:
567 {
Caroline Tice67637d82010-12-15 19:51:12 +0000568 if (out_fh)
569 {
570 ::fprintf (out_fh, "Python Interactive Interpreter. To exit Python, type 'quit()' or 'exit()'.\n");
571 ::fprintf (out_fh, "Do NOT use Ctrl-D (EOF) to exit, as that will cause the lldb debugger to hang.\n");
572 }
Chris Lattner24943d22010-06-08 16:52:24 +0000573 // Save terminal settings if we can
Caroline Ticec95c6d12010-09-14 22:49:06 +0000574 int input_fd;
Greg Clayton63094e02010-06-23 01:19:29 +0000575 FILE *input_fh = reader.GetDebugger().GetInputFileHandle();
Caroline Ticec95c6d12010-09-14 22:49:06 +0000576 if (input_fh != NULL)
Greg Clayton24b48ff2010-10-17 22:03:32 +0000577 input_fd = ::fileno (input_fh);
Caroline Ticec95c6d12010-09-14 22:49:06 +0000578 else
Greg Clayton24b48ff2010-10-17 22:03:32 +0000579 input_fd = STDIN_FILENO;
Caroline Ticec95c6d12010-09-14 22:49:06 +0000580
Greg Clayton63094e02010-06-23 01:19:29 +0000581 script_interpreter->m_termios_valid = ::tcgetattr (input_fd, &script_interpreter->m_termios) == 0;
Greg Clayton24b48ff2010-10-17 22:03:32 +0000582
Caroline Tice202f6b82011-01-17 21:55:19 +0000583 if (!CurrentThreadHasPythonLock())
584 {
585 while (!GetPythonLock(1))
586 {
587 ::fprintf (out_fh, "Python interpreter locked on another thread; waiting to acquire lock...\n");
588 }
589 script_interpreter->EnterSession ();
590 ReleasePythonLock();
591 }
592 else
593 script_interpreter->EnterSession ();
594
Caroline Tice2ade6112010-11-10 19:18:14 +0000595 char error_str[1024];
596 if (script_interpreter->m_embedded_python_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, error_str,
597 sizeof(error_str)))
598 {
599 if (log)
600 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in opening master pty (fd = %d).",
601 script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor());
602 embedded_interpreter_thread = Host::ThreadCreate ("<lldb.script-interpreter.embedded-python-loop>",
603 ScriptInterpreterPython::RunEmbeddedPythonInterpreter,
604 script_interpreter, NULL);
605 if (embedded_interpreter_thread != LLDB_INVALID_HOST_THREAD)
606 {
607 if (log)
608 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in creating thread (thread = %d)", embedded_interpreter_thread);
609 Error detach_error;
610 Host::ThreadDetach (embedded_interpreter_thread, &detach_error);
611 }
612 else
613 {
614 if (log)
615 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed in creating thread");
616 reader.SetIsDone (true);
617 }
618 }
619 else
620 {
621 if (log)
622 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed to open master pty ");
623 reader.SetIsDone (true);
624 }
Chris Lattner24943d22010-06-08 16:52:24 +0000625 }
626 break;
627
628 case eInputReaderDeactivate:
Caroline Tice0aa2e552011-01-14 00:29:16 +0000629 script_interpreter->LeaveSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000630 break;
631
632 case eInputReaderReactivate:
Caroline Tice202f6b82011-01-17 21:55:19 +0000633 if (!CurrentThreadHasPythonLock())
634 {
635 while (!GetPythonLock(1))
636 {
637 // Wait until lock is acquired.
638 }
639 script_interpreter->EnterSession ();
640 ReleasePythonLock();
641 }
642 else
643 script_interpreter->EnterSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000644 break;
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000645
646 case eInputReaderInterrupt:
647 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "raise KeyboardInterrupt\n", 24);
648 break;
649
650 case eInputReaderEndOfFile:
651 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()\n", 7);
652 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000653
654 case eInputReaderGotToken:
Caroline Tice2ade6112010-11-10 19:18:14 +0000655 if (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor() != -1)
Chris Lattner24943d22010-06-08 16:52:24 +0000656 {
Caroline Tice2ade6112010-11-10 19:18:14 +0000657 if (log)
658 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %d", bytes,
659 bytes_len);
660 if (bytes && bytes_len)
661 {
662 if ((int) bytes[0] == 4)
663 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()", 6);
664 else
665 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), bytes, bytes_len);
666 }
667 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "\n", 1);
Chris Lattner24943d22010-06-08 16:52:24 +0000668 }
Caroline Tice2ade6112010-11-10 19:18:14 +0000669 else
670 {
671 if (log)
672 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %d, Master File Descriptor is bad.",
673 bytes,
674 bytes_len);
675 reader.SetIsDone (true);
676 }
677
Chris Lattner24943d22010-06-08 16:52:24 +0000678 break;
679
680 case eInputReaderDone:
Caroline Tice0aa2e552011-01-14 00:29:16 +0000681 script_interpreter->LeaveSession ();
682
Chris Lattner24943d22010-06-08 16:52:24 +0000683 // Restore terminal settings if they were validly saved
Caroline Tice2ade6112010-11-10 19:18:14 +0000684 if (log)
685 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Done, closing down input reader.");
Greg Clayton63094e02010-06-23 01:19:29 +0000686 if (script_interpreter->m_termios_valid)
Chris Lattner24943d22010-06-08 16:52:24 +0000687 {
Caroline Ticec95c6d12010-09-14 22:49:06 +0000688 int input_fd;
689 FILE *input_fh = reader.GetDebugger().GetInputFileHandle();
690 if (input_fh != NULL)
Greg Clayton24b48ff2010-10-17 22:03:32 +0000691 input_fd = ::fileno (input_fh);
Caroline Ticec95c6d12010-09-14 22:49:06 +0000692 else
Greg Clayton24b48ff2010-10-17 22:03:32 +0000693 input_fd = STDIN_FILENO;
Caroline Ticec95c6d12010-09-14 22:49:06 +0000694
695 ::tcsetattr (input_fd, TCSANOW, &script_interpreter->m_termios);
Chris Lattner24943d22010-06-08 16:52:24 +0000696 }
Caroline Tice2ade6112010-11-10 19:18:14 +0000697 script_interpreter->m_embedded_python_pty.CloseMasterFileDescriptor();
Chris Lattner24943d22010-06-08 16:52:24 +0000698 break;
699 }
700
701 return bytes_len;
702}
703
704
705void
Greg Clayton238c0a12010-09-18 01:14:36 +0000706ScriptInterpreterPython::ExecuteInterpreterLoop ()
Chris Lattner24943d22010-06-08 16:52:24 +0000707{
708 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
709
Caroline Tice0aa2e552011-01-14 00:29:16 +0000710 Debugger &debugger = GetCommandInterpreter().GetDebugger();
Caroline Ticec95c6d12010-09-14 22:49:06 +0000711
712 // At the moment, the only time the debugger does not have an input file handle is when this is called
713 // directly from Python, in which case it is both dangerous and unnecessary (not to mention confusing) to
714 // try to embed a running interpreter loop inside the already running Python interpreter loop, so we won't
715 // do it.
716
717 if (debugger.GetInputFileHandle() == NULL)
718 return;
719
Greg Clayton63094e02010-06-23 01:19:29 +0000720 InputReaderSP reader_sp (new InputReader(debugger));
Chris Lattner24943d22010-06-08 16:52:24 +0000721 if (reader_sp)
722 {
723 Error error (reader_sp->Initialize (ScriptInterpreterPython::InputReaderCallback,
724 this, // baton
725 eInputReaderGranularityLine, // token size, to pass to callback function
726 NULL, // end token
727 NULL, // prompt
728 true)); // echo input
729
730 if (error.Success())
731 {
Greg Clayton63094e02010-06-23 01:19:29 +0000732 debugger.PushInputReader (reader_sp);
Caroline Tice2ade6112010-11-10 19:18:14 +0000733 m_embedded_thread_input_reader_sp = reader_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000734 }
735 }
736}
737
738bool
739ScriptInterpreterPython::ExecuteOneLineWithReturn (const char *in_string,
740 ScriptInterpreter::ReturnType return_type,
741 void *ret_value)
742{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000743
Caroline Tice202f6b82011-01-17 21:55:19 +0000744 bool need_to_release_lock = true;
745
746 if (CurrentThreadHasPythonLock())
747 need_to_release_lock = false;
748 else if (!GetPythonLock (1))
749 {
750 fprintf ((m_dbg_stdout ? m_dbg_stdout : stdout),
751 "Python interpreter is currently locked by another thread; unable to process command.\n");
752 return false;
753 }
754
755 EnterSession ();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000756
Chris Lattner24943d22010-06-08 16:52:24 +0000757 PyObject *py_return = NULL;
758 PyObject *mainmod = PyImport_AddModule ("__main__");
759 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000760 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000761 PyObject *py_error = NULL;
762 bool ret_success;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000763 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000764 int success;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000765
766 if (PyDict_Check (globals))
767 {
768 PyObject *key, *value;
769 Py_ssize_t pos = 0;
770
771 int i = 0;
772 while (PyDict_Next (globals, &pos, &key, &value))
773 {
774 // We have stolen references to the key and value objects in the dictionary; we need to increment them now
775 // so that Python's garbage collector doesn't collect them out from under us.
776 Py_INCREF (key);
777 Py_INCREF (value);
778 char *c_str = PyString_AsString (key);
779 if (strcmp (c_str, m_dictionary_name.c_str()) == 0)
780 locals = value;
781 ++i;
782 }
783 }
Chris Lattner24943d22010-06-08 16:52:24 +0000784
Caroline Tice0aa2e552011-01-14 00:29:16 +0000785 if (locals == NULL)
786 {
787 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
788 should_decrement_locals = true;
789 }
790
791 if (locals == NULL)
792 {
793 locals = globals;
794 should_decrement_locals = false;
795 }
796
797 py_error = PyErr_Occurred();
798 if (py_error != NULL)
799 PyErr_Clear();
800
Chris Lattner24943d22010-06-08 16:52:24 +0000801 if (in_string != NULL)
802 {
803 py_return = PyRun_String (in_string, Py_eval_input, globals, locals);
804 if (py_return == NULL)
805 {
806 py_error = PyErr_Occurred ();
807 if (py_error != NULL)
808 PyErr_Clear ();
809
810 py_return = PyRun_String (in_string, Py_single_input, globals, locals);
811 }
812
Caroline Tice0aa2e552011-01-14 00:29:16 +0000813 if (locals != NULL
814 && should_decrement_locals)
815 Py_DECREF (locals);
816
Chris Lattner24943d22010-06-08 16:52:24 +0000817 if (py_return != NULL)
818 {
819 switch (return_type)
820 {
821 case eCharPtr: // "char *"
822 {
823 const char format[3] = "s#";
824 success = PyArg_Parse (py_return, format, (char **) &ret_value);
825 break;
826 }
827 case eBool:
828 {
829 const char format[2] = "b";
830 success = PyArg_Parse (py_return, format, (bool *) ret_value);
831 break;
832 }
833 case eShortInt:
834 {
835 const char format[2] = "h";
836 success = PyArg_Parse (py_return, format, (short *) ret_value);
837 break;
838 }
839 case eShortIntUnsigned:
840 {
841 const char format[2] = "H";
842 success = PyArg_Parse (py_return, format, (unsigned short *) ret_value);
843 break;
844 }
845 case eInt:
846 {
847 const char format[2] = "i";
848 success = PyArg_Parse (py_return, format, (int *) ret_value);
849 break;
850 }
851 case eIntUnsigned:
852 {
853 const char format[2] = "I";
854 success = PyArg_Parse (py_return, format, (unsigned int *) ret_value);
855 break;
856 }
857 case eLongInt:
858 {
859 const char format[2] = "l";
860 success = PyArg_Parse (py_return, format, (long *) ret_value);
861 break;
862 }
863 case eLongIntUnsigned:
864 {
865 const char format[2] = "k";
866 success = PyArg_Parse (py_return, format, (unsigned long *) ret_value);
867 break;
868 }
869 case eLongLong:
870 {
871 const char format[2] = "L";
872 success = PyArg_Parse (py_return, format, (long long *) ret_value);
873 break;
874 }
875 case eLongLongUnsigned:
876 {
877 const char format[2] = "K";
878 success = PyArg_Parse (py_return, format, (unsigned long long *) ret_value);
879 break;
880 }
881 case eFloat:
882 {
883 const char format[2] = "f";
884 success = PyArg_Parse (py_return, format, (float *) ret_value);
885 break;
886 }
887 case eDouble:
888 {
889 const char format[2] = "d";
890 success = PyArg_Parse (py_return, format, (double *) ret_value);
891 break;
892 }
893 case eChar:
894 {
895 const char format[2] = "c";
896 success = PyArg_Parse (py_return, format, (char *) ret_value);
897 break;
898 }
899 default:
900 {}
901 }
902 Py_DECREF (py_return);
903 if (success)
904 ret_success = true;
905 else
906 ret_success = false;
907 }
908 }
909
910 py_error = PyErr_Occurred();
911 if (py_error != NULL)
912 {
913 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
914 PyErr_Print ();
915 PyErr_Clear();
916 ret_success = false;
917 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000918
919 LeaveSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000920
Caroline Tice202f6b82011-01-17 21:55:19 +0000921 if (need_to_release_lock)
922 ReleasePythonLock();
923
Chris Lattner24943d22010-06-08 16:52:24 +0000924 return ret_success;
925}
926
927bool
928ScriptInterpreterPython::ExecuteMultipleLines (const char *in_string)
929{
Caroline Tice202f6b82011-01-17 21:55:19 +0000930 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
931 bool need_to_release_lock = true;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000932
Caroline Tice202f6b82011-01-17 21:55:19 +0000933 if (CurrentThreadHasPythonLock())
934 need_to_release_lock = false;
935 else
936 {
937 while (!GetPythonLock (1))
938 fprintf (tmp_fh, "Python interpreter locked on another thread; waiting to acquire lock...\n");
939 }
940
941 EnterSession ();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000942
Chris Lattner24943d22010-06-08 16:52:24 +0000943 bool success = false;
944 PyObject *py_return = NULL;
945 PyObject *mainmod = PyImport_AddModule ("__main__");
946 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000947 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000948 PyObject *py_error = NULL;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000949 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000950
Caroline Tice0aa2e552011-01-14 00:29:16 +0000951 if (PyDict_Check (globals))
952 {
953 PyObject *key, *value;
954 Py_ssize_t pos = 0;
955
956 while (PyDict_Next (globals, &pos, &key, &value))
957 {
958 // We have stolen references to the key and value objects in the dictionary; we need to increment them now
959 // so that Python's garbage collector doesn't collect them out from under us.
960 Py_INCREF (key);
961 Py_INCREF (value);
962 if (strcmp (PyString_AsString (key), m_dictionary_name.c_str()) == 0)
963 locals = value;
964 }
965 }
966
967 if (locals == NULL)
968 {
969 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
970 should_decrement_locals = true;
971 }
972
973 if (locals == NULL)
974 {
975 locals = globals;
976 should_decrement_locals = false;
977 }
978
979 py_error = PyErr_Occurred();
980 if (py_error != NULL)
981 PyErr_Clear();
982
Chris Lattner24943d22010-06-08 16:52:24 +0000983 if (in_string != NULL)
984 {
985 struct _node *compiled_node = PyParser_SimpleParseString (in_string, Py_file_input);
986 if (compiled_node)
987 {
988 PyCodeObject *compiled_code = PyNode_Compile (compiled_node, "temp.py");
989 if (compiled_code)
990 {
991 py_return = PyEval_EvalCode (compiled_code, globals, locals);
992 if (py_return != NULL)
993 {
994 success = true;
995 Py_DECREF (py_return);
996 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000997 if (locals && should_decrement_locals)
998 Py_DECREF (locals);
Chris Lattner24943d22010-06-08 16:52:24 +0000999 }
1000 }
1001 }
1002
1003 py_error = PyErr_Occurred ();
1004 if (py_error != NULL)
1005 {
1006 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
1007 PyErr_Print ();
1008 PyErr_Clear();
1009 success = false;
1010 }
1011
Caroline Tice0aa2e552011-01-14 00:29:16 +00001012 LeaveSession ();
1013
Caroline Tice202f6b82011-01-17 21:55:19 +00001014 if (need_to_release_lock)
1015 ReleasePythonLock();
1016
Chris Lattner24943d22010-06-08 16:52:24 +00001017 return success;
1018}
1019
1020static const char *g_reader_instructions = "Enter your Python command(s). Type 'DONE' to end.";
1021
1022size_t
1023ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback
1024(
1025 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +00001026 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +00001027 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +00001028 const char *bytes,
1029 size_t bytes_len
1030)
1031{
1032 static StringList commands_in_progress;
1033
Greg Clayton63094e02010-06-23 01:19:29 +00001034 FILE *out_fh = reader.GetDebugger().GetOutputFileHandle();
Caroline Ticec95c6d12010-09-14 22:49:06 +00001035 if (out_fh == NULL)
1036 out_fh = stdout;
1037
Chris Lattner24943d22010-06-08 16:52:24 +00001038 switch (notification)
1039 {
1040 case eInputReaderActivate:
1041 {
1042 commands_in_progress.Clear();
1043 if (out_fh)
1044 {
1045 ::fprintf (out_fh, "%s\n", g_reader_instructions);
Greg Clayton63094e02010-06-23 01:19:29 +00001046 if (reader.GetPrompt())
1047 ::fprintf (out_fh, "%s", reader.GetPrompt());
Caroline Ticef81b4c52010-10-27 18:34:42 +00001048 ::fflush (out_fh);
Chris Lattner24943d22010-06-08 16:52:24 +00001049 }
1050 }
1051 break;
1052
1053 case eInputReaderDeactivate:
1054 break;
1055
1056 case eInputReaderReactivate:
Greg Clayton63094e02010-06-23 01:19:29 +00001057 if (reader.GetPrompt() && out_fh)
Caroline Ticef81b4c52010-10-27 18:34:42 +00001058 {
Greg Clayton63094e02010-06-23 01:19:29 +00001059 ::fprintf (out_fh, "%s", reader.GetPrompt());
Caroline Ticef81b4c52010-10-27 18:34:42 +00001060 ::fflush (out_fh);
1061 }
Chris Lattner24943d22010-06-08 16:52:24 +00001062 break;
1063
1064 case eInputReaderGotToken:
1065 {
1066 std::string temp_string (bytes, bytes_len);
1067 commands_in_progress.AppendString (temp_string.c_str());
Greg Clayton63094e02010-06-23 01:19:29 +00001068 if (out_fh && !reader.IsDone() && reader.GetPrompt())
Caroline Ticef81b4c52010-10-27 18:34:42 +00001069 {
Greg Clayton63094e02010-06-23 01:19:29 +00001070 ::fprintf (out_fh, "%s", reader.GetPrompt());
Caroline Ticef81b4c52010-10-27 18:34:42 +00001071 ::fflush (out_fh);
1072 }
Chris Lattner24943d22010-06-08 16:52:24 +00001073 }
1074 break;
1075
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001076 case eInputReaderEndOfFile:
1077 case eInputReaderInterrupt:
1078 // Control-c (SIGINT) & control-d both mean finish & exit.
1079 reader.SetIsDone(true);
1080
1081 // Control-c (SIGINT) ALSO means cancel; do NOT create a breakpoint command.
1082 if (notification == eInputReaderInterrupt)
1083 commands_in_progress.Clear();
1084
1085 // Fall through here...
1086
Chris Lattner24943d22010-06-08 16:52:24 +00001087 case eInputReaderDone:
1088 {
1089 BreakpointOptions *bp_options = (BreakpointOptions *)baton;
1090 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1091 data_ap->user_source.AppendList (commands_in_progress);
1092 if (data_ap.get())
1093 {
Greg Clayton63094e02010-06-23 01:19:29 +00001094 ScriptInterpreter *interpreter = reader.GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
Chris Lattner24943d22010-06-08 16:52:24 +00001095 if (interpreter)
1096 {
1097 if (interpreter->GenerateBreakpointCommandCallbackData (data_ap->user_source,
1098 data_ap->script_source))
1099 {
1100 if (data_ap->script_source.GetSize() == 1)
1101 {
1102 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1103 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
1104 }
1105 }
Caroline Ticeb447e842010-09-21 19:25:28 +00001106 else
Caroline Tice5136f942010-09-27 21:35:15 +00001107 ::fprintf (out_fh, "Warning: No command attached to breakpoint.\n");
Chris Lattner24943d22010-06-08 16:52:24 +00001108 }
1109 else
1110 {
1111 // FIXME: Error processing.
1112 }
1113 }
1114 }
1115 break;
1116
1117 }
1118
1119 return bytes_len;
1120}
1121
1122void
Greg Clayton238c0a12010-09-18 01:14:36 +00001123ScriptInterpreterPython::CollectDataForBreakpointCommandCallback (BreakpointOptions *bp_options,
Chris Lattner24943d22010-06-08 16:52:24 +00001124 CommandReturnObject &result)
1125{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001126 Debugger &debugger = GetCommandInterpreter().GetDebugger();
1127
Greg Clayton63094e02010-06-23 01:19:29 +00001128 InputReaderSP reader_sp (new InputReader (debugger));
Chris Lattner24943d22010-06-08 16:52:24 +00001129
1130 if (reader_sp)
1131 {
1132 Error err = reader_sp->Initialize (
1133 ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback,
1134 bp_options, // baton
1135 eInputReaderGranularityLine, // token size, for feeding data to callback function
1136 "DONE", // end token
1137 "> ", // prompt
1138 true); // echo input
1139
1140 if (err.Success())
Greg Clayton63094e02010-06-23 01:19:29 +00001141 debugger.PushInputReader (reader_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001142 else
1143 {
1144 result.AppendError (err.AsCString());
1145 result.SetStatus (eReturnStatusFailed);
1146 }
1147 }
1148 else
1149 {
1150 result.AppendError("out of memory");
1151 result.SetStatus (eReturnStatusFailed);
1152 }
1153}
1154
Johnny Chen3e0571b2010-09-11 00:23:59 +00001155// Set a Python one-liner as the callback for the breakpoint.
Johnny Chend1c2dca2010-09-10 18:21:10 +00001156void
Greg Clayton238c0a12010-09-18 01:14:36 +00001157ScriptInterpreterPython::SetBreakpointCommandCallback (BreakpointOptions *bp_options,
Johnny Chend1c2dca2010-09-10 18:21:10 +00001158 const char *oneliner)
1159{
1160 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1161
1162 // It's necessary to set both user_source and script_source to the oneliner.
1163 // The former is used to generate callback description (as in breakpoint command list)
1164 // while the latter is used for Python to interpret during the actual callback.
Caroline Tice5136f942010-09-27 21:35:15 +00001165
Johnny Chend1c2dca2010-09-10 18:21:10 +00001166 data_ap->user_source.AppendString (oneliner);
Johnny Chend1c2dca2010-09-10 18:21:10 +00001167
Caroline Tice5136f942010-09-27 21:35:15 +00001168 if (GenerateBreakpointCommandCallbackData (data_ap->user_source, data_ap->script_source))
1169 {
1170 if (data_ap->script_source.GetSize() == 1)
1171 {
1172 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1173 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
1174 }
1175 }
1176
Johnny Chend1c2dca2010-09-10 18:21:10 +00001177 return;
1178}
1179
Chris Lattner24943d22010-06-08 16:52:24 +00001180bool
1181ScriptInterpreterPython::ExportFunctionDefinitionToInterpreter (StringList &function_def)
1182{
1183 // Convert StringList to one long, newline delimited, const char *.
1184 std::string function_def_string;
1185
1186 int num_lines = function_def.GetSize();
1187
1188 for (int i = 0; i < num_lines; ++i)
1189 {
1190 function_def_string.append (function_def.GetStringAtIndex(i));
1191 if (function_def_string.at (function_def_string.length() - 1) != '\n')
1192 function_def_string.append ("\n");
1193
1194 }
1195
1196 return ExecuteMultipleLines (function_def_string.c_str());
1197}
1198
1199bool
1200ScriptInterpreterPython::GenerateBreakpointCommandCallbackData (StringList &user_input, StringList &callback_data)
1201{
1202 static int num_created_functions = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001203 user_input.RemoveBlankLines ();
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001204 int num_lines = user_input.GetSize ();
1205 StreamString sstr;
Chris Lattner24943d22010-06-08 16:52:24 +00001206
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001207 // Check to see if we have any data; if not, just return.
1208 if (user_input.GetSize() == 0)
1209 return false;
1210
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001211 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1212 // frame and breakpoint location as parameters to the function.
Caroline Ticeb447e842010-09-21 19:25:28 +00001213
Caroline Ticeb447e842010-09-21 19:25:28 +00001214
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001215 sstr.Printf ("lldb_autogen_python_bp_callback_func_%d", num_created_functions);
1216 ++num_created_functions;
1217 std::string auto_generated_function_name = sstr.GetData();
Caroline Ticeb447e842010-09-21 19:25:28 +00001218
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001219 sstr.Clear();
Caroline Ticeb447e842010-09-21 19:25:28 +00001220 StringList auto_generated_function;
Caroline Ticeb447e842010-09-21 19:25:28 +00001221
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001222 // Create the function name & definition string.
1223
Caroline Tice0aa2e552011-01-14 00:29:16 +00001224 sstr.Printf ("def %s (frame, bp_loc, dict):", auto_generated_function_name.c_str());
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001225 auto_generated_function.AppendString (sstr.GetData());
Caroline Tice0aa2e552011-01-14 00:29:16 +00001226
1227 // Pre-pend code for setting up the session dictionary.
1228
1229 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1230 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1231 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1232 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1233 // global dictionary.
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001234
1235 // Wrap everything up inside the function, increasing the indentation.
Chris Lattner24943d22010-06-08 16:52:24 +00001236
1237 for (int i = 0; i < num_lines; ++i)
1238 {
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001239 sstr.Clear ();
1240 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1241 auto_generated_function.AppendString (sstr.GetData());
Caroline Ticeb447e842010-09-21 19:25:28 +00001242 }
Chris Lattner24943d22010-06-08 16:52:24 +00001243
Caroline Tice0aa2e552011-01-14 00:29:16 +00001244 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1245 // got written to the values in the global dictionary, not the session dictionary).
1246
1247 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1248 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1249 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1250 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1251
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001252 // Verify that the results are valid Python.
Chris Lattner24943d22010-06-08 16:52:24 +00001253
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001254 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
Caroline Ticeb447e842010-09-21 19:25:28 +00001255 {
Caroline Ticeb447e842010-09-21 19:25:28 +00001256 return false;
Chris Lattner24943d22010-06-08 16:52:24 +00001257 }
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001258
1259 // Store the name of the auto-generated function to be called.
1260
1261 callback_data.AppendString (auto_generated_function_name.c_str());
1262 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001263}
1264
Greg Clayton5144f382010-10-07 17:14:24 +00001265bool
1266ScriptInterpreterPython::BreakpointCallbackFunction
1267(
1268 void *baton,
1269 StoppointCallbackContext *context,
1270 user_id_t break_id,
1271 user_id_t break_loc_id
1272)
1273{
1274 BreakpointOptions::CommandData *bp_option_data = (BreakpointOptions::CommandData *) baton;
1275 const char *python_function_name = bp_option_data->script_source.GetStringAtIndex (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001276
1277 if (!context)
1278 return true;
1279
1280 Target *target = context->exe_ctx.target;
1281
1282 if (!target)
1283 return true;
1284
1285 Debugger &debugger = target->GetDebugger();
1286 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1287 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1288
1289 if (!script_interpreter)
1290 return true;
Greg Clayton5144f382010-10-07 17:14:24 +00001291
1292 if (python_function_name != NULL
1293 && python_function_name[0] != '\0')
1294 {
1295 Thread *thread = context->exe_ctx.thread;
Greg Clayton5144f382010-10-07 17:14:24 +00001296 const StackFrameSP stop_frame_sp = thread->GetStackFrameSPForStackFramePtr (context->exe_ctx.frame);
1297 BreakpointSP breakpoint_sp = target->GetBreakpointByID (break_id);
1298 const BreakpointLocationSP bp_loc_sp = breakpoint_sp->FindLocationByID (break_loc_id);
1299
1300 SBFrame sb_frame (stop_frame_sp);
1301 SBBreakpointLocation sb_bp_loc (bp_loc_sp);
1302
1303 if (sb_bp_loc.IsValid() || sb_frame.IsValid())
Caroline Tice0aa2e552011-01-14 00:29:16 +00001304 {
Caroline Tice202f6b82011-01-17 21:55:19 +00001305 bool ret_val = true;
1306 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
1307 if (CurrentThreadHasPythonLock())
1308 {
1309 python_interpreter->EnterSession ();
1310 ret_val = LLDBSWIGPythonBreakpointCallbackFunction(python_function_name,
1311 python_interpreter->m_dictionary_name.c_str(),
1312 sb_frame, sb_bp_loc);
1313 python_interpreter->LeaveSession ();
1314 }
1315 else
1316 {
1317 while (!GetPythonLock (1))
1318 fprintf (tmp_fh,
1319 "Python interpreter locked on another thread; waiting to acquire lock...\n");
1320 python_interpreter->EnterSession ();
1321 ret_val = LLDBSWIGPythonBreakpointCallbackFunction(python_function_name,
1322 python_interpreter->m_dictionary_name.c_str(),
1323 sb_frame, sb_bp_loc);
1324 python_interpreter->LeaveSession ();
1325 ReleasePythonLock ();
1326 }
Caroline Tice0aa2e552011-01-14 00:29:16 +00001327 return ret_val;
1328 }
Greg Clayton5144f382010-10-07 17:14:24 +00001329 }
1330 // We currently always true so we stop in case anything goes wrong when
1331 // trying to call the script function
1332 return true;
1333}
Caroline Tice2ade6112010-11-10 19:18:14 +00001334
1335lldb::thread_result_t
1336ScriptInterpreterPython::RunEmbeddedPythonInterpreter (lldb::thread_arg_t baton)
1337{
1338 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
1339
1340 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
1341
1342 if (log)
1343 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread starting...", baton);
1344
1345 char error_str[1024];
1346 const char *pty_slave_name = script_interpreter->m_embedded_python_pty.GetSlaveName (error_str, sizeof (error_str));
Caroline Tice202f6b82011-01-17 21:55:19 +00001347 bool need_to_release_lock = true;
1348 bool safe_to_run = false;
Caroline Tice0aa2e552011-01-14 00:29:16 +00001349
Caroline Tice202f6b82011-01-17 21:55:19 +00001350 if (CurrentThreadHasPythonLock())
1351 {
1352 safe_to_run = true;
1353 need_to_release_lock = false;
1354 }
1355 else
1356 {
1357 int interval = 1;
1358 safe_to_run = GetPythonLock (interval);
1359 while (!safe_to_run)
1360 {
1361 interval = interval * 2;
1362 safe_to_run = GetPythonLock (interval);
1363 }
1364 }
1365
1366 if (pty_slave_name != NULL && safe_to_run)
1367 {
Caroline Tice2ade6112010-11-10 19:18:14 +00001368 StreamString run_string;
Caroline Tice2ade6112010-11-10 19:18:14 +00001369
Caroline Tice202f6b82011-01-17 21:55:19 +00001370 script_interpreter->EnterSession ();
1371
Caroline Tice0aa2e552011-01-14 00:29:16 +00001372 run_string.Printf ("run_one_line (%s, 'save_stderr = sys.stderr')", script_interpreter->m_dictionary_name.c_str());
1373 PyRun_SimpleString (run_string.GetData());
1374 run_string.Clear ();
1375
1376 run_string.Printf ("run_one_line (%s, 'sys.stderr = sys.stdout')", script_interpreter->m_dictionary_name.c_str());
1377 PyRun_SimpleString (run_string.GetData());
1378 run_string.Clear ();
1379
1380 run_string.Printf ("run_one_line (%s, 'save_stdin = sys.stdin')", script_interpreter->m_dictionary_name.c_str());
1381 PyRun_SimpleString (run_string.GetData());
1382 run_string.Clear ();
1383
1384 run_string.Printf ("run_one_line (%s, \"sys.stdin = open ('%s', 'r')\")", script_interpreter->m_dictionary_name.c_str(),
1385 pty_slave_name);
1386 PyRun_SimpleString (run_string.GetData());
1387 run_string.Clear ();
1388
Caroline Tice2ade6112010-11-10 19:18:14 +00001389 // The following call drops into the embedded interpreter loop and stays there until the
1390 // user chooses to exit from the Python interpreter.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001391
1392 run_string.Printf ("run_python_interpreter (%s)", script_interpreter->m_dictionary_name.c_str());
1393 PyRun_SimpleString (run_string.GetData());
1394 run_string.Clear ();
Caroline Tice2ade6112010-11-10 19:18:14 +00001395
Caroline Tice0aa2e552011-01-14 00:29:16 +00001396 run_string.Printf ("run_one_line (%s, 'sys.stdin = save_stdin')", script_interpreter->m_dictionary_name.c_str());
1397 PyRun_SimpleString (run_string.GetData());
1398 run_string.Clear();
1399
1400 run_string.Printf ("run_one_line (%s, 'sys.stderr = save_stderr')", script_interpreter->m_dictionary_name.c_str());
1401 PyRun_SimpleString (run_string.GetData());
1402 run_string.Clear();
Caroline Tice202f6b82011-01-17 21:55:19 +00001403
1404 script_interpreter->LeaveSession ();
1405
Caroline Tice2ade6112010-11-10 19:18:14 +00001406 }
1407
Caroline Tice202f6b82011-01-17 21:55:19 +00001408 if (!safe_to_run)
1409 fprintf ((script_interpreter->m_dbg_stdout ? script_interpreter->m_dbg_stdout : stdout),
1410 "Python interpreter locked on another thread; unable to acquire lock.\n");
1411
1412 if (need_to_release_lock)
1413 ReleasePythonLock ();
1414
Caroline Tice2ade6112010-11-10 19:18:14 +00001415 if (script_interpreter->m_embedded_thread_input_reader_sp)
1416 script_interpreter->m_embedded_thread_input_reader_sp->SetIsDone (true);
1417
1418 script_interpreter->m_embedded_python_pty.CloseSlaveFileDescriptor();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001419
1420 script_interpreter->m_pty_slave_is_open = false;
Caroline Tice2ade6112010-11-10 19:18:14 +00001421
1422 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT);
1423 if (log)
1424 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread exiting...", baton);
1425
1426
Caroline Tice0aa2e552011-01-14 00:29:16 +00001427 // Clean up the input reader and make the debugger pop it off the stack.
1428 Debugger &debugger = script_interpreter->GetCommandInterpreter().GetDebugger();
Caroline Tice2ade6112010-11-10 19:18:14 +00001429 const InputReaderSP reader_sp = script_interpreter->m_embedded_thread_input_reader_sp;
1430 script_interpreter->m_embedded_thread_input_reader_sp.reset();
1431 debugger.PopInputReader (reader_sp);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001432
Caroline Tice2ade6112010-11-10 19:18:14 +00001433 return NULL;
1434}
1435
1436
Caroline Tice0aa2e552011-01-14 00:29:16 +00001437void
1438ScriptInterpreterPython::Initialize ()
1439{
Caroline Tice2ade6112010-11-10 19:18:14 +00001440
Caroline Tice0aa2e552011-01-14 00:29:16 +00001441 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
1442
1443 int input_fd = STDIN_FILENO;
1444
1445 struct termios stdin_termios;
1446 bool valid_termios = ::tcgetattr (input_fd, &stdin_termios) == 0;
1447
1448 // Find the module that owns this code and use that path we get to
1449 // set the PYTHONPATH appropriately.
1450
1451 FileSpec file_spec;
1452 char python_dir_path[PATH_MAX];
1453 if (Host::GetLLDBPath (ePathTypePythonDir, file_spec))
1454 {
1455 std::string python_path;
1456 const char *curr_python_path = ::getenv ("PYTHONPATH");
1457 if (curr_python_path)
1458 {
1459 // We have a current value for PYTHONPATH, so lets append to it
1460 python_path.append (curr_python_path);
1461 }
1462
1463 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
1464 {
1465 if (!python_path.empty())
1466 python_path.append (1, ':');
1467 python_path.append (python_dir_path);
1468 }
1469
1470 if (Host::GetLLDBPath (ePathTypeLLDBShlibDir, file_spec))
1471 {
1472 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
1473 {
1474 if (!python_path.empty())
1475 python_path.append (1, ':');
1476 python_path.append (python_dir_path);
1477 }
1478 }
1479 const char *pathon_path_env_cstr = python_path.c_str();
1480 ::setenv ("PYTHONPATH", pathon_path_env_cstr, 1);
1481 }
1482
1483 Py_Initialize ();
1484
1485 PyObject *compiled_module = Py_CompileString (embedded_interpreter_string,
1486 "embedded_interpreter.py",
1487 Py_file_input);
1488
1489 PyObject *py_error = PyErr_Occurred ();
1490 if (py_error != NULL)
1491 {
1492 PyErr_Print();
1493 PyErr_Clear();
1494 }
1495
1496
1497 // This function is in the C++ output file generated by SWIG after it is
1498 // run on all of the headers in "lldb/API/SB*.h"
1499 init_lldb ();
1500
1501 // Update the path python uses to search for modules to include the current directory.
1502
1503 int success = PyRun_SimpleString ("import sys");
1504 success = PyRun_SimpleString ("sys.path.append ('.')");
1505
1506 PyObject *pmod = NULL;
1507
1508 if (compiled_module)
1509 {
1510 pmod = PyImport_ExecCodeModule (const_cast<char*> ("embedded_interpreter"),
1511 compiled_module);
1512 Py_DECREF (compiled_module);
1513 }
1514
1515 if (pmod != NULL)
1516 {
1517 PyRun_SimpleString ("from embedded_interpreter import run_python_interpreter");
1518 PyRun_SimpleString ("from embedded_interpreter import run_one_line");
1519 PyRun_SimpleString ("import sys");
1520 PyRun_SimpleString ("from termios import *");
1521 Py_DECREF (pmod);
1522 }
1523
1524 if (valid_termios)
1525 ::tcsetattr (input_fd, TCSANOW, &stdin_termios);
1526}
1527
1528void
1529ScriptInterpreterPython::Terminate ()
1530{
1531 // We are intentionally NOT calling Py_Finalize here (this would be the logical place to call it). Calling
1532 // Py_Finalize here causes test suite runs to seg fault: The test suite runs in Python. It registers
1533 // SBDebugger::Terminate to be called 'at_exit'. When the test suite Python harness finishes up, it calls
1534 // Py_Finalize, which calls all the 'at_exit' registered functions. SBDebugger::Terminate calls Debugger::Terminate,
1535 // which calls lldb::Terminate, which calls ScriptInterpreter::Terminate, which calls
1536 // ScriptInterpreterPython::Terminate. So if we call Py_Finalize here, we end up with Py_Finalize being called from
1537 // within Py_Finalize, which results in a seg fault.
1538 //
1539 // Since this function only gets called when lldb is shutting down and going away anyway, the fact that we don't
1540 // actually call Py_Finalize should not cause any problems (everything should shut down/go away anyway when the
1541 // process exits).
1542 //
1543// Py_Finalize ();
1544}