blob: 0ebc095f57bfcc7037105174cb9f9386521dac56 [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
Greg Clayton7c330d62011-01-27 01:01:10 +0000227 static int g_initialized = false;
228
229 if (!g_initialized)
230 {
231 g_initialized = true;
232 ScriptInterpreterPython::Initialize ();
233 }
234
Caroline Tice202f6b82011-01-17 21:55:19 +0000235 bool safe_to_run = false;
236 bool need_to_release_lock = true;
237 int interval = 5; // Number of seconds to try getting the Python lock before timing out.
238
239 // We don't dare exit this function without finishing setting up the script interpreter, so we must wait until
240 // we can get the Python lock.
241
242 if (CurrentThreadHasPythonLock())
243 {
244 safe_to_run = true;
245 need_to_release_lock = false;
246 }
247
248 while (!safe_to_run)
249 {
250 safe_to_run = GetPythonLock (interval);
251 if (!safe_to_run)
252 {
253 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
254 fprintf (tmp_fh,
255 "Python interpreter is locked on another thread; "
256 "please release interpreter in order to continue.\n");
257 interval = interval * 2;
258 }
259 }
260
Caroline Tice0aa2e552011-01-14 00:29:16 +0000261 m_dictionary_name.append("_dict");
262 StreamString run_string;
263 run_string.Printf ("%s = dict()", m_dictionary_name.c_str());
264 PyRun_SimpleString (run_string.GetData());
Caroline Tice5867f6b2010-10-18 18:24:17 +0000265
Caroline Tice0aa2e552011-01-14 00:29:16 +0000266 run_string.Clear();
267 run_string.Printf ("run_one_line (%s, 'import sys')", m_dictionary_name.c_str());
268 PyRun_SimpleString (run_string.GetData());
269
270 // Importing 'lldb' module calls SBDebugger::Initialize, which calls Debugger::Initialize, which increments a
271 // global debugger ref-count; therefore we need to check the ref-count before and after importing lldb, and if the
272 // ref-count increased we need to call Debugger::Terminate here to decrement the ref-count so that when the final
273 // call to Debugger::Terminate is made, the ref-count has the correct value.
274 //
275 // Bonus question: Why doesn't the ref-count always increase? Because sometimes lldb has already been imported, in
276 // which case the code inside it, including the call to SBDebugger::Initialize(), does not get executed.
Caroline Tice5867f6b2010-10-18 18:24:17 +0000277
Caroline Tice0aa2e552011-01-14 00:29:16 +0000278 int old_count = Debugger::TestDebuggerRefCount();
Chris Lattner24943d22010-06-08 16:52:24 +0000279
Caroline Tice0aa2e552011-01-14 00:29:16 +0000280 run_string.Clear();
281 run_string.Printf ("run_one_line (%s, 'import lldb')", m_dictionary_name.c_str());
282 PyRun_SimpleString (run_string.GetData());
Greg Clayton24b48ff2010-10-17 22:03:32 +0000283
Caroline Tice0aa2e552011-01-14 00:29:16 +0000284 int new_count = Debugger::TestDebuggerRefCount();
Chris Lattner24943d22010-06-08 16:52:24 +0000285
Caroline Tice0aa2e552011-01-14 00:29:16 +0000286 if (new_count > old_count)
287 Debugger::Terminate();
Caroline Tice5867f6b2010-10-18 18:24:17 +0000288
Caroline Tice0aa2e552011-01-14 00:29:16 +0000289 run_string.Clear();
290 run_string.Printf ("run_one_line (%s, 'import copy')", m_dictionary_name.c_str());
291 PyRun_SimpleString (run_string.GetData());
292
293 run_string.Clear();
294 run_string.Printf ("run_one_line (%s, 'lldb.debugger_unique_id = %d')", m_dictionary_name.c_str(),
295 interpreter.GetDebugger().GetID());
296 PyRun_SimpleString (run_string.GetData());
297
298 if (m_dbg_stdout != NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000299 {
Caroline Tice0aa2e552011-01-14 00:29:16 +0000300 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
Caroline Tice5867f6b2010-10-18 18:24:17 +0000301 }
Caroline Tice202f6b82011-01-17 21:55:19 +0000302
303 if (need_to_release_lock)
304 ReleasePythonLock();
Chris Lattner24943d22010-06-08 16:52:24 +0000305}
306
307ScriptInterpreterPython::~ScriptInterpreterPython ()
308{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000309 Debugger &debugger = GetCommandInterpreter().GetDebugger();
310
311 if (m_embedded_thread_input_reader_sp.get() != NULL)
312 {
313 m_embedded_thread_input_reader_sp->SetIsDone (true);
314 m_embedded_python_pty.CloseSlaveFileDescriptor();
315 m_pty_slave_is_open = false;
316 const InputReaderSP reader_sp = m_embedded_thread_input_reader_sp;
317 m_embedded_thread_input_reader_sp.reset();
318 debugger.PopInputReader (reader_sp);
319 }
320
321 if (m_new_sysout)
322 {
Caroline Tice202f6b82011-01-17 21:55:19 +0000323 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
324 if (!CurrentThreadHasPythonLock ())
325 {
326 while (!GetPythonLock (1))
327 fprintf (tmp_fh, "Python interpreter locked on another thread; waiting to acquire lock...\n");
328 Py_DECREF (m_new_sysout);
329 ReleasePythonLock ();
330 }
331 else
332 Py_DECREF (m_new_sysout);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000333 }
Chris Lattner24943d22010-06-08 16:52:24 +0000334}
335
Caroline Tice0aa2e552011-01-14 00:29:16 +0000336void
337ScriptInterpreterPython::ResetOutputFileHandle (FILE *fh)
338{
339 if (fh == NULL)
340 return;
341
342 m_dbg_stdout = fh;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000343
Caroline Tice202f6b82011-01-17 21:55:19 +0000344 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
345 if (!CurrentThreadHasPythonLock ())
346 {
347 while (!GetPythonLock (1))
348 fprintf (tmp_fh, "Python interpreter locked on another thread; waiting to acquire lock...\n");
349 EnterSession ();
350 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
351 LeaveSession ();
352 ReleasePythonLock ();
353 }
354 else
355 {
356 EnterSession ();
357 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
358 LeaveSession ();
359 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000360}
361
362void
363ScriptInterpreterPython::LeaveSession ()
364{
365 m_session_is_active = false;
366}
367
368void
369ScriptInterpreterPython::EnterSession ()
370{
371 // If we have already entered the session, without having officially 'left' it, then there is no need to
372 // 'enter' it again.
373
374 if (m_session_is_active)
375 return;
376
377 m_session_is_active = true;
378
Caroline Tice202f6b82011-01-17 21:55:19 +0000379 StreamString run_string;
380
381 run_string.Printf ("run_one_line (%s, 'lldb.debugger_unique_id = %d')", m_dictionary_name.c_str(),
382 GetCommandInterpreter().GetDebugger().GetID());
383 PyRun_SimpleString (run_string.GetData());
384
Caroline Tice0aa2e552011-01-14 00:29:16 +0000385
386 PyObject *sysmod = PyImport_AddModule ("sys");
387 PyObject *sysdict = PyModule_GetDict (sysmod);
388
389 if ((m_new_sysout != NULL)
390 && (sysmod != NULL)
391 && (sysdict != NULL))
392 PyDict_SetItemString (sysdict, "stdout", m_new_sysout);
393
394 if (PyErr_Occurred())
395 PyErr_Clear ();
396
Caroline Tice0aa2e552011-01-14 00:29:16 +0000397 if (!m_pty_slave_is_open)
398 {
Caroline Tice202f6b82011-01-17 21:55:19 +0000399 run_string.Clear();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000400 run_string.Printf ("run_one_line (%s, \"new_stdin = open('%s', 'r')\")", m_dictionary_name.c_str(),
401 m_pty_slave_name.c_str());
402 PyRun_SimpleString (run_string.GetData());
403 m_pty_slave_is_open = true;
404
405 run_string.Clear();
406 run_string.Printf ("run_one_line (%s, 'sys.stdin = new_stdin')", m_dictionary_name.c_str());
407 PyRun_SimpleString (run_string.GetData());
408 }
409}
410
411
Johnny Chen60dde642010-07-30 22:33:14 +0000412bool
Greg Clayton238c0a12010-09-18 01:14:36 +0000413ScriptInterpreterPython::ExecuteOneLine (const char *command, CommandReturnObject *result)
Chris Lattner24943d22010-06-08 16:52:24 +0000414{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000415 if (!m_valid_session)
416 return false;
417
Caroline Tice0aa2e552011-01-14 00:29:16 +0000418
Caroline Tice0aa2e552011-01-14 00:29:16 +0000419
Caroline Tice4a461da2011-01-14 21:09:29 +0000420 // We want to call run_one_line, passing in the dictionary and the command string. We cannot do this through
421 // PyRun_SimpleString here because the command string may contain escaped characters, and putting it inside
422 // another string to pass to PyRun_SimpleString messes up the escaping. So we use the following more complicated
423 // method to pass the command string directly down to Python.
424
425
Caroline Tice202f6b82011-01-17 21:55:19 +0000426 bool need_to_release_lock = true;
427
428 if (CurrentThreadHasPythonLock())
429 need_to_release_lock = false;
430 else if (!GetPythonLock (1))
431 {
432 fprintf ((m_dbg_stdout ? m_dbg_stdout : stdout),
433 "Python interpreter is currently locked by another thread; unable to process command.\n");
434 return false;
435 }
436
437 EnterSession ();
Caroline Tice4a461da2011-01-14 21:09:29 +0000438 bool success = false;
439
Greg Clayton63094e02010-06-23 01:19:29 +0000440 if (command)
Chris Lattner24943d22010-06-08 16:52:24 +0000441 {
Caroline Tice4a461da2011-01-14 21:09:29 +0000442 // Find the correct script interpreter dictionary in the main module.
443 PyObject *main_mod = PyImport_AddModule ("__main__");
444 PyObject *script_interpreter_dict = NULL;
445 if (main_mod != NULL)
446 {
447 PyObject *main_dict = PyModule_GetDict (main_mod);
448 if ((main_dict != NULL)
449 && PyDict_Check (main_dict))
450 {
451 // Go through the main dictionary looking for the correct python script interpreter dictionary
452 PyObject *key, *value;
453 Py_ssize_t pos = 0;
454
455 while (PyDict_Next (main_dict, &pos, &key, &value))
456 {
457 // We have stolen references to the key and value objects in the dictionary; we need to increment
458 // them now so that Python's garbage collector doesn't collect them out from under us.
459 Py_INCREF (key);
460 Py_INCREF (value);
461 if (strcmp (PyString_AsString (key), m_dictionary_name.c_str()) == 0)
462 {
463 script_interpreter_dict = value;
464 break;
465 }
466 }
467 }
468
469 if (script_interpreter_dict != NULL)
470 {
471 PyObject *pfunc = NULL;
472 PyObject *pmod = PyImport_AddModule ("embedded_interpreter");
473 if (pmod != NULL)
474 {
475 PyObject *pmod_dict = PyModule_GetDict (pmod);
476 if ((pmod_dict != NULL)
477 && PyDict_Check (pmod_dict))
478 {
479 PyObject *key, *value;
480 Py_ssize_t pos = 0;
481
482 while (PyDict_Next (pmod_dict, &pos, &key, &value))
483 {
484 Py_INCREF (key);
485 Py_INCREF (value);
486 if (strcmp (PyString_AsString (key), "run_one_line") == 0)
487 {
488 pfunc = value;
489 break;
490 }
491 }
492
493 PyObject *string_arg = PyString_FromString (command);
494 if (pfunc && string_arg && PyCallable_Check (pfunc))
495 {
496 PyObject *pargs = PyTuple_New (2);
497 if (pargs != NULL)
498 {
499 PyTuple_SetItem (pargs, 0, script_interpreter_dict);
500 PyTuple_SetItem (pargs, 1, string_arg);
501 PyObject *pvalue = PyObject_CallObject (pfunc, pargs);
502 Py_DECREF (pargs);
503 if (pvalue != NULL)
504 {
505 Py_DECREF (pvalue);
506 success = true;
507 }
508 else if (PyErr_Occurred ())
509 {
510 PyErr_Print();
511 PyErr_Clear();
512 }
513 }
514 }
515 }
516 }
517 Py_INCREF (script_interpreter_dict);
518 }
519 }
Greg Clayton63094e02010-06-23 01:19:29 +0000520
Caroline Tice0aa2e552011-01-14 00:29:16 +0000521 LeaveSession ();
522
Caroline Tice202f6b82011-01-17 21:55:19 +0000523 if (need_to_release_lock)
524 ReleasePythonLock();
525
Caroline Tice4a461da2011-01-14 21:09:29 +0000526 if (success)
Johnny Chen60dde642010-07-30 22:33:14 +0000527 return true;
528
529 // The one-liner failed. Append the error message.
530 if (result)
531 result->AppendErrorWithFormat ("python failed attempting to evaluate '%s'\n", command);
532 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000533 }
Johnny Chen60dde642010-07-30 22:33:14 +0000534
Caroline Tice0aa2e552011-01-14 00:29:16 +0000535 LeaveSession ();
Caroline Tice202f6b82011-01-17 21:55:19 +0000536
537 if (need_to_release_lock)
538 ReleasePythonLock ();
539
Johnny Chen60dde642010-07-30 22:33:14 +0000540 if (result)
541 result->AppendError ("empty command passed to python\n");
542 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000543}
544
545
546
547size_t
548ScriptInterpreterPython::InputReaderCallback
549(
550 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000551 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000552 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000553 const char *bytes,
554 size_t bytes_len
555)
556{
Caroline Tice2ade6112010-11-10 19:18:14 +0000557 lldb::thread_t embedded_interpreter_thread;
558 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
559
Chris Lattner24943d22010-06-08 16:52:24 +0000560 if (baton == NULL)
561 return 0;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000562
563 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
564
565 if (script_interpreter->m_script_lang != eScriptLanguagePython)
566 return 0;
567
Caroline Tice67637d82010-12-15 19:51:12 +0000568 FILE *out_fh = reader.GetDebugger().GetOutputFileHandle ();
569 if (out_fh == NULL)
570 out_fh = stdout;
571
Chris Lattner24943d22010-06-08 16:52:24 +0000572 switch (notification)
573 {
574 case eInputReaderActivate:
575 {
Caroline Tice67637d82010-12-15 19:51:12 +0000576 if (out_fh)
577 {
Caroline Ticea81c3672011-02-03 20:08:40 +0000578 ::fprintf (out_fh, "Python Interactive Interpreter. To exit, type 'quit()', 'exit()' or Ctrl-D.\n");
Caroline Tice67637d82010-12-15 19:51:12 +0000579 }
Chris Lattner24943d22010-06-08 16:52:24 +0000580 // Save terminal settings if we can
Caroline Ticec95c6d12010-09-14 22:49:06 +0000581 int input_fd;
Greg Clayton63094e02010-06-23 01:19:29 +0000582 FILE *input_fh = reader.GetDebugger().GetInputFileHandle();
Caroline Ticec95c6d12010-09-14 22:49:06 +0000583 if (input_fh != NULL)
Greg Clayton24b48ff2010-10-17 22:03:32 +0000584 input_fd = ::fileno (input_fh);
Caroline Ticec95c6d12010-09-14 22:49:06 +0000585 else
Greg Clayton24b48ff2010-10-17 22:03:32 +0000586 input_fd = STDIN_FILENO;
Caroline Ticec95c6d12010-09-14 22:49:06 +0000587
Greg Clayton63094e02010-06-23 01:19:29 +0000588 script_interpreter->m_termios_valid = ::tcgetattr (input_fd, &script_interpreter->m_termios) == 0;
Greg Clayton24b48ff2010-10-17 22:03:32 +0000589
Caroline Tice202f6b82011-01-17 21:55:19 +0000590 if (!CurrentThreadHasPythonLock())
591 {
592 while (!GetPythonLock(1))
593 {
594 ::fprintf (out_fh, "Python interpreter locked on another thread; waiting to acquire lock...\n");
595 }
596 script_interpreter->EnterSession ();
597 ReleasePythonLock();
598 }
599 else
600 script_interpreter->EnterSession ();
601
Caroline Tice2ade6112010-11-10 19:18:14 +0000602 char error_str[1024];
603 if (script_interpreter->m_embedded_python_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, error_str,
604 sizeof(error_str)))
605 {
606 if (log)
607 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in opening master pty (fd = %d).",
608 script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor());
609 embedded_interpreter_thread = Host::ThreadCreate ("<lldb.script-interpreter.embedded-python-loop>",
610 ScriptInterpreterPython::RunEmbeddedPythonInterpreter,
611 script_interpreter, NULL);
612 if (embedded_interpreter_thread != LLDB_INVALID_HOST_THREAD)
613 {
614 if (log)
615 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in creating thread (thread = %d)", embedded_interpreter_thread);
616 Error detach_error;
617 Host::ThreadDetach (embedded_interpreter_thread, &detach_error);
618 }
619 else
620 {
621 if (log)
622 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed in creating thread");
623 reader.SetIsDone (true);
624 }
625 }
626 else
627 {
628 if (log)
629 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed to open master pty ");
630 reader.SetIsDone (true);
631 }
Chris Lattner24943d22010-06-08 16:52:24 +0000632 }
633 break;
634
635 case eInputReaderDeactivate:
Caroline Tice0aa2e552011-01-14 00:29:16 +0000636 script_interpreter->LeaveSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000637 break;
638
639 case eInputReaderReactivate:
Caroline Tice202f6b82011-01-17 21:55:19 +0000640 if (!CurrentThreadHasPythonLock())
641 {
642 while (!GetPythonLock(1))
643 {
644 // Wait until lock is acquired.
645 }
646 script_interpreter->EnterSession ();
647 ReleasePythonLock();
648 }
649 else
650 script_interpreter->EnterSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000651 break;
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000652
653 case eInputReaderInterrupt:
654 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "raise KeyboardInterrupt\n", 24);
655 break;
656
657 case eInputReaderEndOfFile:
658 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()\n", 7);
659 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000660
661 case eInputReaderGotToken:
Caroline Tice2ade6112010-11-10 19:18:14 +0000662 if (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor() != -1)
Chris Lattner24943d22010-06-08 16:52:24 +0000663 {
Caroline Tice2ade6112010-11-10 19:18:14 +0000664 if (log)
665 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %d", bytes,
666 bytes_len);
667 if (bytes && bytes_len)
668 {
669 if ((int) bytes[0] == 4)
670 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()", 6);
671 else
672 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), bytes, bytes_len);
673 }
674 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "\n", 1);
Chris Lattner24943d22010-06-08 16:52:24 +0000675 }
Caroline Tice2ade6112010-11-10 19:18:14 +0000676 else
677 {
678 if (log)
679 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %d, Master File Descriptor is bad.",
680 bytes,
681 bytes_len);
682 reader.SetIsDone (true);
683 }
684
Chris Lattner24943d22010-06-08 16:52:24 +0000685 break;
686
687 case eInputReaderDone:
Caroline Tice0aa2e552011-01-14 00:29:16 +0000688 script_interpreter->LeaveSession ();
689
Chris Lattner24943d22010-06-08 16:52:24 +0000690 // Restore terminal settings if they were validly saved
Caroline Tice2ade6112010-11-10 19:18:14 +0000691 if (log)
692 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Done, closing down input reader.");
Greg Clayton63094e02010-06-23 01:19:29 +0000693 if (script_interpreter->m_termios_valid)
Chris Lattner24943d22010-06-08 16:52:24 +0000694 {
Caroline Ticec95c6d12010-09-14 22:49:06 +0000695 int input_fd;
696 FILE *input_fh = reader.GetDebugger().GetInputFileHandle();
697 if (input_fh != NULL)
Greg Clayton24b48ff2010-10-17 22:03:32 +0000698 input_fd = ::fileno (input_fh);
Caroline Ticec95c6d12010-09-14 22:49:06 +0000699 else
Greg Clayton24b48ff2010-10-17 22:03:32 +0000700 input_fd = STDIN_FILENO;
Caroline Ticec95c6d12010-09-14 22:49:06 +0000701
702 ::tcsetattr (input_fd, TCSANOW, &script_interpreter->m_termios);
Chris Lattner24943d22010-06-08 16:52:24 +0000703 }
Caroline Tice2ade6112010-11-10 19:18:14 +0000704 script_interpreter->m_embedded_python_pty.CloseMasterFileDescriptor();
Chris Lattner24943d22010-06-08 16:52:24 +0000705 break;
706 }
707
708 return bytes_len;
709}
710
711
712void
Greg Clayton238c0a12010-09-18 01:14:36 +0000713ScriptInterpreterPython::ExecuteInterpreterLoop ()
Chris Lattner24943d22010-06-08 16:52:24 +0000714{
715 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
716
Caroline Tice0aa2e552011-01-14 00:29:16 +0000717 Debugger &debugger = GetCommandInterpreter().GetDebugger();
Caroline Ticec95c6d12010-09-14 22:49:06 +0000718
719 // At the moment, the only time the debugger does not have an input file handle is when this is called
720 // directly from Python, in which case it is both dangerous and unnecessary (not to mention confusing) to
721 // try to embed a running interpreter loop inside the already running Python interpreter loop, so we won't
722 // do it.
723
724 if (debugger.GetInputFileHandle() == NULL)
725 return;
726
Greg Clayton63094e02010-06-23 01:19:29 +0000727 InputReaderSP reader_sp (new InputReader(debugger));
Chris Lattner24943d22010-06-08 16:52:24 +0000728 if (reader_sp)
729 {
730 Error error (reader_sp->Initialize (ScriptInterpreterPython::InputReaderCallback,
731 this, // baton
732 eInputReaderGranularityLine, // token size, to pass to callback function
733 NULL, // end token
734 NULL, // prompt
735 true)); // echo input
736
737 if (error.Success())
738 {
Greg Clayton63094e02010-06-23 01:19:29 +0000739 debugger.PushInputReader (reader_sp);
Caroline Tice2ade6112010-11-10 19:18:14 +0000740 m_embedded_thread_input_reader_sp = reader_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000741 }
742 }
743}
744
745bool
746ScriptInterpreterPython::ExecuteOneLineWithReturn (const char *in_string,
747 ScriptInterpreter::ReturnType return_type,
748 void *ret_value)
749{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000750
Caroline Tice202f6b82011-01-17 21:55:19 +0000751 bool need_to_release_lock = true;
752
753 if (CurrentThreadHasPythonLock())
754 need_to_release_lock = false;
755 else if (!GetPythonLock (1))
756 {
757 fprintf ((m_dbg_stdout ? m_dbg_stdout : stdout),
758 "Python interpreter is currently locked by another thread; unable to process command.\n");
759 return false;
760 }
761
762 EnterSession ();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000763
Chris Lattner24943d22010-06-08 16:52:24 +0000764 PyObject *py_return = NULL;
765 PyObject *mainmod = PyImport_AddModule ("__main__");
766 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000767 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000768 PyObject *py_error = NULL;
769 bool ret_success;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000770 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000771 int success;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000772
773 if (PyDict_Check (globals))
774 {
775 PyObject *key, *value;
776 Py_ssize_t pos = 0;
777
778 int i = 0;
779 while (PyDict_Next (globals, &pos, &key, &value))
780 {
781 // We have stolen references to the key and value objects in the dictionary; we need to increment them now
782 // so that Python's garbage collector doesn't collect them out from under us.
783 Py_INCREF (key);
784 Py_INCREF (value);
785 char *c_str = PyString_AsString (key);
786 if (strcmp (c_str, m_dictionary_name.c_str()) == 0)
787 locals = value;
788 ++i;
789 }
790 }
Chris Lattner24943d22010-06-08 16:52:24 +0000791
Caroline Tice0aa2e552011-01-14 00:29:16 +0000792 if (locals == NULL)
793 {
794 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
795 should_decrement_locals = true;
796 }
797
798 if (locals == NULL)
799 {
800 locals = globals;
801 should_decrement_locals = false;
802 }
803
804 py_error = PyErr_Occurred();
805 if (py_error != NULL)
806 PyErr_Clear();
807
Chris Lattner24943d22010-06-08 16:52:24 +0000808 if (in_string != NULL)
809 {
810 py_return = PyRun_String (in_string, Py_eval_input, globals, locals);
811 if (py_return == NULL)
812 {
813 py_error = PyErr_Occurred ();
814 if (py_error != NULL)
815 PyErr_Clear ();
816
817 py_return = PyRun_String (in_string, Py_single_input, globals, locals);
818 }
819
Caroline Tice0aa2e552011-01-14 00:29:16 +0000820 if (locals != NULL
821 && should_decrement_locals)
822 Py_DECREF (locals);
823
Chris Lattner24943d22010-06-08 16:52:24 +0000824 if (py_return != NULL)
825 {
826 switch (return_type)
827 {
828 case eCharPtr: // "char *"
829 {
830 const char format[3] = "s#";
831 success = PyArg_Parse (py_return, format, (char **) &ret_value);
832 break;
833 }
834 case eBool:
835 {
836 const char format[2] = "b";
837 success = PyArg_Parse (py_return, format, (bool *) ret_value);
838 break;
839 }
840 case eShortInt:
841 {
842 const char format[2] = "h";
843 success = PyArg_Parse (py_return, format, (short *) ret_value);
844 break;
845 }
846 case eShortIntUnsigned:
847 {
848 const char format[2] = "H";
849 success = PyArg_Parse (py_return, format, (unsigned short *) ret_value);
850 break;
851 }
852 case eInt:
853 {
854 const char format[2] = "i";
855 success = PyArg_Parse (py_return, format, (int *) ret_value);
856 break;
857 }
858 case eIntUnsigned:
859 {
860 const char format[2] = "I";
861 success = PyArg_Parse (py_return, format, (unsigned int *) ret_value);
862 break;
863 }
864 case eLongInt:
865 {
866 const char format[2] = "l";
867 success = PyArg_Parse (py_return, format, (long *) ret_value);
868 break;
869 }
870 case eLongIntUnsigned:
871 {
872 const char format[2] = "k";
873 success = PyArg_Parse (py_return, format, (unsigned long *) ret_value);
874 break;
875 }
876 case eLongLong:
877 {
878 const char format[2] = "L";
879 success = PyArg_Parse (py_return, format, (long long *) ret_value);
880 break;
881 }
882 case eLongLongUnsigned:
883 {
884 const char format[2] = "K";
885 success = PyArg_Parse (py_return, format, (unsigned long long *) ret_value);
886 break;
887 }
888 case eFloat:
889 {
890 const char format[2] = "f";
891 success = PyArg_Parse (py_return, format, (float *) ret_value);
892 break;
893 }
894 case eDouble:
895 {
896 const char format[2] = "d";
897 success = PyArg_Parse (py_return, format, (double *) ret_value);
898 break;
899 }
900 case eChar:
901 {
902 const char format[2] = "c";
903 success = PyArg_Parse (py_return, format, (char *) ret_value);
904 break;
905 }
906 default:
907 {}
908 }
909 Py_DECREF (py_return);
910 if (success)
911 ret_success = true;
912 else
913 ret_success = false;
914 }
915 }
916
917 py_error = PyErr_Occurred();
918 if (py_error != NULL)
919 {
920 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
921 PyErr_Print ();
922 PyErr_Clear();
923 ret_success = false;
924 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000925
926 LeaveSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000927
Caroline Tice202f6b82011-01-17 21:55:19 +0000928 if (need_to_release_lock)
929 ReleasePythonLock();
930
Chris Lattner24943d22010-06-08 16:52:24 +0000931 return ret_success;
932}
933
934bool
935ScriptInterpreterPython::ExecuteMultipleLines (const char *in_string)
936{
Caroline Tice202f6b82011-01-17 21:55:19 +0000937 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
938 bool need_to_release_lock = true;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000939
Caroline Tice202f6b82011-01-17 21:55:19 +0000940 if (CurrentThreadHasPythonLock())
941 need_to_release_lock = false;
942 else
943 {
944 while (!GetPythonLock (1))
945 fprintf (tmp_fh, "Python interpreter locked on another thread; waiting to acquire lock...\n");
946 }
947
948 EnterSession ();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000949
Chris Lattner24943d22010-06-08 16:52:24 +0000950 bool success = false;
951 PyObject *py_return = NULL;
952 PyObject *mainmod = PyImport_AddModule ("__main__");
953 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000954 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000955 PyObject *py_error = NULL;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000956 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000957
Caroline Tice0aa2e552011-01-14 00:29:16 +0000958 if (PyDict_Check (globals))
959 {
960 PyObject *key, *value;
961 Py_ssize_t pos = 0;
962
963 while (PyDict_Next (globals, &pos, &key, &value))
964 {
965 // We have stolen references to the key and value objects in the dictionary; we need to increment them now
966 // so that Python's garbage collector doesn't collect them out from under us.
967 Py_INCREF (key);
968 Py_INCREF (value);
969 if (strcmp (PyString_AsString (key), m_dictionary_name.c_str()) == 0)
970 locals = value;
971 }
972 }
973
974 if (locals == NULL)
975 {
976 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
977 should_decrement_locals = true;
978 }
979
980 if (locals == NULL)
981 {
982 locals = globals;
983 should_decrement_locals = false;
984 }
985
986 py_error = PyErr_Occurred();
987 if (py_error != NULL)
988 PyErr_Clear();
989
Chris Lattner24943d22010-06-08 16:52:24 +0000990 if (in_string != NULL)
991 {
992 struct _node *compiled_node = PyParser_SimpleParseString (in_string, Py_file_input);
993 if (compiled_node)
994 {
995 PyCodeObject *compiled_code = PyNode_Compile (compiled_node, "temp.py");
996 if (compiled_code)
997 {
998 py_return = PyEval_EvalCode (compiled_code, globals, locals);
999 if (py_return != NULL)
1000 {
1001 success = true;
1002 Py_DECREF (py_return);
1003 }
Caroline Tice0aa2e552011-01-14 00:29:16 +00001004 if (locals && should_decrement_locals)
1005 Py_DECREF (locals);
Chris Lattner24943d22010-06-08 16:52:24 +00001006 }
1007 }
1008 }
1009
1010 py_error = PyErr_Occurred ();
1011 if (py_error != NULL)
1012 {
1013 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
1014 PyErr_Print ();
1015 PyErr_Clear();
1016 success = false;
1017 }
1018
Caroline Tice0aa2e552011-01-14 00:29:16 +00001019 LeaveSession ();
1020
Caroline Tice202f6b82011-01-17 21:55:19 +00001021 if (need_to_release_lock)
1022 ReleasePythonLock();
1023
Chris Lattner24943d22010-06-08 16:52:24 +00001024 return success;
1025}
1026
1027static const char *g_reader_instructions = "Enter your Python command(s). Type 'DONE' to end.";
1028
1029size_t
1030ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback
1031(
1032 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +00001033 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +00001034 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +00001035 const char *bytes,
1036 size_t bytes_len
1037)
1038{
1039 static StringList commands_in_progress;
1040
Greg Clayton63094e02010-06-23 01:19:29 +00001041 FILE *out_fh = reader.GetDebugger().GetOutputFileHandle();
Caroline Ticec95c6d12010-09-14 22:49:06 +00001042 if (out_fh == NULL)
1043 out_fh = stdout;
1044
Chris Lattner24943d22010-06-08 16:52:24 +00001045 switch (notification)
1046 {
1047 case eInputReaderActivate:
1048 {
1049 commands_in_progress.Clear();
1050 if (out_fh)
1051 {
1052 ::fprintf (out_fh, "%s\n", g_reader_instructions);
Greg Clayton63094e02010-06-23 01:19:29 +00001053 if (reader.GetPrompt())
1054 ::fprintf (out_fh, "%s", reader.GetPrompt());
Caroline Ticef81b4c52010-10-27 18:34:42 +00001055 ::fflush (out_fh);
Chris Lattner24943d22010-06-08 16:52:24 +00001056 }
1057 }
1058 break;
1059
1060 case eInputReaderDeactivate:
1061 break;
1062
1063 case eInputReaderReactivate:
Greg Clayton63094e02010-06-23 01:19:29 +00001064 if (reader.GetPrompt() && out_fh)
Caroline Ticef81b4c52010-10-27 18:34:42 +00001065 {
Greg Clayton63094e02010-06-23 01:19:29 +00001066 ::fprintf (out_fh, "%s", reader.GetPrompt());
Caroline Ticef81b4c52010-10-27 18:34:42 +00001067 ::fflush (out_fh);
1068 }
Chris Lattner24943d22010-06-08 16:52:24 +00001069 break;
1070
1071 case eInputReaderGotToken:
1072 {
1073 std::string temp_string (bytes, bytes_len);
1074 commands_in_progress.AppendString (temp_string.c_str());
Greg Clayton63094e02010-06-23 01:19:29 +00001075 if (out_fh && !reader.IsDone() && reader.GetPrompt())
Caroline Ticef81b4c52010-10-27 18:34:42 +00001076 {
Greg Clayton63094e02010-06-23 01:19:29 +00001077 ::fprintf (out_fh, "%s", reader.GetPrompt());
Caroline Ticef81b4c52010-10-27 18:34:42 +00001078 ::fflush (out_fh);
1079 }
Chris Lattner24943d22010-06-08 16:52:24 +00001080 }
1081 break;
1082
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001083 case eInputReaderEndOfFile:
1084 case eInputReaderInterrupt:
1085 // Control-c (SIGINT) & control-d both mean finish & exit.
1086 reader.SetIsDone(true);
1087
1088 // Control-c (SIGINT) ALSO means cancel; do NOT create a breakpoint command.
1089 if (notification == eInputReaderInterrupt)
1090 commands_in_progress.Clear();
1091
1092 // Fall through here...
1093
Chris Lattner24943d22010-06-08 16:52:24 +00001094 case eInputReaderDone:
1095 {
1096 BreakpointOptions *bp_options = (BreakpointOptions *)baton;
1097 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1098 data_ap->user_source.AppendList (commands_in_progress);
1099 if (data_ap.get())
1100 {
Greg Clayton63094e02010-06-23 01:19:29 +00001101 ScriptInterpreter *interpreter = reader.GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
Chris Lattner24943d22010-06-08 16:52:24 +00001102 if (interpreter)
1103 {
1104 if (interpreter->GenerateBreakpointCommandCallbackData (data_ap->user_source,
1105 data_ap->script_source))
1106 {
1107 if (data_ap->script_source.GetSize() == 1)
1108 {
1109 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1110 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
1111 }
1112 }
Caroline Ticeb447e842010-09-21 19:25:28 +00001113 else
Caroline Tice5136f942010-09-27 21:35:15 +00001114 ::fprintf (out_fh, "Warning: No command attached to breakpoint.\n");
Chris Lattner24943d22010-06-08 16:52:24 +00001115 }
1116 else
1117 {
1118 // FIXME: Error processing.
1119 }
1120 }
1121 }
1122 break;
1123
1124 }
1125
1126 return bytes_len;
1127}
1128
1129void
Greg Clayton238c0a12010-09-18 01:14:36 +00001130ScriptInterpreterPython::CollectDataForBreakpointCommandCallback (BreakpointOptions *bp_options,
Chris Lattner24943d22010-06-08 16:52:24 +00001131 CommandReturnObject &result)
1132{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001133 Debugger &debugger = GetCommandInterpreter().GetDebugger();
1134
Greg Clayton63094e02010-06-23 01:19:29 +00001135 InputReaderSP reader_sp (new InputReader (debugger));
Chris Lattner24943d22010-06-08 16:52:24 +00001136
1137 if (reader_sp)
1138 {
1139 Error err = reader_sp->Initialize (
1140 ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback,
1141 bp_options, // baton
1142 eInputReaderGranularityLine, // token size, for feeding data to callback function
1143 "DONE", // end token
1144 "> ", // prompt
1145 true); // echo input
1146
1147 if (err.Success())
Greg Clayton63094e02010-06-23 01:19:29 +00001148 debugger.PushInputReader (reader_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001149 else
1150 {
1151 result.AppendError (err.AsCString());
1152 result.SetStatus (eReturnStatusFailed);
1153 }
1154 }
1155 else
1156 {
1157 result.AppendError("out of memory");
1158 result.SetStatus (eReturnStatusFailed);
1159 }
1160}
1161
Johnny Chen3e0571b2010-09-11 00:23:59 +00001162// Set a Python one-liner as the callback for the breakpoint.
Johnny Chend1c2dca2010-09-10 18:21:10 +00001163void
Greg Clayton238c0a12010-09-18 01:14:36 +00001164ScriptInterpreterPython::SetBreakpointCommandCallback (BreakpointOptions *bp_options,
Johnny Chend1c2dca2010-09-10 18:21:10 +00001165 const char *oneliner)
1166{
1167 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1168
1169 // It's necessary to set both user_source and script_source to the oneliner.
1170 // The former is used to generate callback description (as in breakpoint command list)
1171 // while the latter is used for Python to interpret during the actual callback.
Caroline Tice5136f942010-09-27 21:35:15 +00001172
Johnny Chend1c2dca2010-09-10 18:21:10 +00001173 data_ap->user_source.AppendString (oneliner);
Johnny Chend1c2dca2010-09-10 18:21:10 +00001174
Caroline Tice5136f942010-09-27 21:35:15 +00001175 if (GenerateBreakpointCommandCallbackData (data_ap->user_source, data_ap->script_source))
1176 {
1177 if (data_ap->script_source.GetSize() == 1)
1178 {
1179 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1180 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
1181 }
1182 }
1183
Johnny Chend1c2dca2010-09-10 18:21:10 +00001184 return;
1185}
1186
Chris Lattner24943d22010-06-08 16:52:24 +00001187bool
1188ScriptInterpreterPython::ExportFunctionDefinitionToInterpreter (StringList &function_def)
1189{
1190 // Convert StringList to one long, newline delimited, const char *.
1191 std::string function_def_string;
1192
1193 int num_lines = function_def.GetSize();
1194
1195 for (int i = 0; i < num_lines; ++i)
1196 {
1197 function_def_string.append (function_def.GetStringAtIndex(i));
1198 if (function_def_string.at (function_def_string.length() - 1) != '\n')
1199 function_def_string.append ("\n");
1200
1201 }
1202
1203 return ExecuteMultipleLines (function_def_string.c_str());
1204}
1205
1206bool
1207ScriptInterpreterPython::GenerateBreakpointCommandCallbackData (StringList &user_input, StringList &callback_data)
1208{
1209 static int num_created_functions = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001210 user_input.RemoveBlankLines ();
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001211 int num_lines = user_input.GetSize ();
1212 StreamString sstr;
Chris Lattner24943d22010-06-08 16:52:24 +00001213
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001214 // Check to see if we have any data; if not, just return.
1215 if (user_input.GetSize() == 0)
1216 return false;
1217
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001218 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1219 // frame and breakpoint location as parameters to the function.
Caroline Ticeb447e842010-09-21 19:25:28 +00001220
Caroline Ticeb447e842010-09-21 19:25:28 +00001221
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001222 sstr.Printf ("lldb_autogen_python_bp_callback_func_%d", num_created_functions);
1223 ++num_created_functions;
1224 std::string auto_generated_function_name = sstr.GetData();
Caroline Ticeb447e842010-09-21 19:25:28 +00001225
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001226 sstr.Clear();
Caroline Ticeb447e842010-09-21 19:25:28 +00001227 StringList auto_generated_function;
Caroline Ticeb447e842010-09-21 19:25:28 +00001228
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001229 // Create the function name & definition string.
1230
Caroline Tice0aa2e552011-01-14 00:29:16 +00001231 sstr.Printf ("def %s (frame, bp_loc, dict):", auto_generated_function_name.c_str());
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001232 auto_generated_function.AppendString (sstr.GetData());
Caroline Tice0aa2e552011-01-14 00:29:16 +00001233
1234 // Pre-pend code for setting up the session dictionary.
1235
1236 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1237 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1238 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1239 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1240 // global dictionary.
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001241
1242 // Wrap everything up inside the function, increasing the indentation.
Chris Lattner24943d22010-06-08 16:52:24 +00001243
1244 for (int i = 0; i < num_lines; ++i)
1245 {
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001246 sstr.Clear ();
1247 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1248 auto_generated_function.AppendString (sstr.GetData());
Caroline Ticeb447e842010-09-21 19:25:28 +00001249 }
Chris Lattner24943d22010-06-08 16:52:24 +00001250
Caroline Tice0aa2e552011-01-14 00:29:16 +00001251 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1252 // got written to the values in the global dictionary, not the session dictionary).
1253
1254 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1255 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1256 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1257 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1258
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001259 // Verify that the results are valid Python.
Chris Lattner24943d22010-06-08 16:52:24 +00001260
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001261 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
Caroline Ticeb447e842010-09-21 19:25:28 +00001262 {
Caroline Ticeb447e842010-09-21 19:25:28 +00001263 return false;
Chris Lattner24943d22010-06-08 16:52:24 +00001264 }
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001265
1266 // Store the name of the auto-generated function to be called.
1267
1268 callback_data.AppendString (auto_generated_function_name.c_str());
1269 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001270}
1271
Greg Clayton5144f382010-10-07 17:14:24 +00001272bool
1273ScriptInterpreterPython::BreakpointCallbackFunction
1274(
1275 void *baton,
1276 StoppointCallbackContext *context,
1277 user_id_t break_id,
1278 user_id_t break_loc_id
1279)
1280{
1281 BreakpointOptions::CommandData *bp_option_data = (BreakpointOptions::CommandData *) baton;
1282 const char *python_function_name = bp_option_data->script_source.GetStringAtIndex (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001283
1284 if (!context)
1285 return true;
1286
1287 Target *target = context->exe_ctx.target;
1288
1289 if (!target)
1290 return true;
1291
1292 Debugger &debugger = target->GetDebugger();
1293 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1294 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1295
1296 if (!script_interpreter)
1297 return true;
Greg Clayton5144f382010-10-07 17:14:24 +00001298
1299 if (python_function_name != NULL
1300 && python_function_name[0] != '\0')
1301 {
1302 Thread *thread = context->exe_ctx.thread;
Greg Clayton5144f382010-10-07 17:14:24 +00001303 const StackFrameSP stop_frame_sp = thread->GetStackFrameSPForStackFramePtr (context->exe_ctx.frame);
1304 BreakpointSP breakpoint_sp = target->GetBreakpointByID (break_id);
1305 const BreakpointLocationSP bp_loc_sp = breakpoint_sp->FindLocationByID (break_loc_id);
1306
1307 SBFrame sb_frame (stop_frame_sp);
1308 SBBreakpointLocation sb_bp_loc (bp_loc_sp);
1309
1310 if (sb_bp_loc.IsValid() || sb_frame.IsValid())
Caroline Tice0aa2e552011-01-14 00:29:16 +00001311 {
Caroline Tice202f6b82011-01-17 21:55:19 +00001312 bool ret_val = true;
1313 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
1314 if (CurrentThreadHasPythonLock())
1315 {
1316 python_interpreter->EnterSession ();
1317 ret_val = LLDBSWIGPythonBreakpointCallbackFunction(python_function_name,
1318 python_interpreter->m_dictionary_name.c_str(),
1319 sb_frame, sb_bp_loc);
1320 python_interpreter->LeaveSession ();
1321 }
1322 else
1323 {
1324 while (!GetPythonLock (1))
1325 fprintf (tmp_fh,
1326 "Python interpreter locked on another thread; waiting to acquire lock...\n");
1327 python_interpreter->EnterSession ();
1328 ret_val = LLDBSWIGPythonBreakpointCallbackFunction(python_function_name,
1329 python_interpreter->m_dictionary_name.c_str(),
1330 sb_frame, sb_bp_loc);
1331 python_interpreter->LeaveSession ();
1332 ReleasePythonLock ();
1333 }
Caroline Tice0aa2e552011-01-14 00:29:16 +00001334 return ret_val;
1335 }
Greg Clayton5144f382010-10-07 17:14:24 +00001336 }
1337 // We currently always true so we stop in case anything goes wrong when
1338 // trying to call the script function
1339 return true;
1340}
Caroline Tice2ade6112010-11-10 19:18:14 +00001341
1342lldb::thread_result_t
1343ScriptInterpreterPython::RunEmbeddedPythonInterpreter (lldb::thread_arg_t baton)
1344{
1345 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
1346
1347 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
1348
1349 if (log)
1350 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread starting...", baton);
1351
1352 char error_str[1024];
1353 const char *pty_slave_name = script_interpreter->m_embedded_python_pty.GetSlaveName (error_str, sizeof (error_str));
Caroline Tice202f6b82011-01-17 21:55:19 +00001354 bool need_to_release_lock = true;
1355 bool safe_to_run = false;
Caroline Tice0aa2e552011-01-14 00:29:16 +00001356
Caroline Tice202f6b82011-01-17 21:55:19 +00001357 if (CurrentThreadHasPythonLock())
1358 {
1359 safe_to_run = true;
1360 need_to_release_lock = false;
1361 }
1362 else
1363 {
1364 int interval = 1;
1365 safe_to_run = GetPythonLock (interval);
1366 while (!safe_to_run)
1367 {
1368 interval = interval * 2;
1369 safe_to_run = GetPythonLock (interval);
1370 }
1371 }
1372
1373 if (pty_slave_name != NULL && safe_to_run)
1374 {
Caroline Tice2ade6112010-11-10 19:18:14 +00001375 StreamString run_string;
Caroline Tice2ade6112010-11-10 19:18:14 +00001376
Caroline Tice202f6b82011-01-17 21:55:19 +00001377 script_interpreter->EnterSession ();
1378
Caroline Tice0aa2e552011-01-14 00:29:16 +00001379 run_string.Printf ("run_one_line (%s, 'save_stderr = sys.stderr')", script_interpreter->m_dictionary_name.c_str());
1380 PyRun_SimpleString (run_string.GetData());
1381 run_string.Clear ();
1382
1383 run_string.Printf ("run_one_line (%s, 'sys.stderr = sys.stdout')", script_interpreter->m_dictionary_name.c_str());
1384 PyRun_SimpleString (run_string.GetData());
1385 run_string.Clear ();
1386
1387 run_string.Printf ("run_one_line (%s, 'save_stdin = sys.stdin')", script_interpreter->m_dictionary_name.c_str());
1388 PyRun_SimpleString (run_string.GetData());
1389 run_string.Clear ();
1390
1391 run_string.Printf ("run_one_line (%s, \"sys.stdin = open ('%s', 'r')\")", script_interpreter->m_dictionary_name.c_str(),
1392 pty_slave_name);
1393 PyRun_SimpleString (run_string.GetData());
1394 run_string.Clear ();
1395
Caroline Tice2ade6112010-11-10 19:18:14 +00001396 // The following call drops into the embedded interpreter loop and stays there until the
1397 // user chooses to exit from the Python interpreter.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001398
1399 run_string.Printf ("run_python_interpreter (%s)", script_interpreter->m_dictionary_name.c_str());
1400 PyRun_SimpleString (run_string.GetData());
1401 run_string.Clear ();
Caroline Tice2ade6112010-11-10 19:18:14 +00001402
Caroline Tice0aa2e552011-01-14 00:29:16 +00001403 run_string.Printf ("run_one_line (%s, 'sys.stdin = save_stdin')", script_interpreter->m_dictionary_name.c_str());
1404 PyRun_SimpleString (run_string.GetData());
1405 run_string.Clear();
1406
1407 run_string.Printf ("run_one_line (%s, 'sys.stderr = save_stderr')", script_interpreter->m_dictionary_name.c_str());
1408 PyRun_SimpleString (run_string.GetData());
1409 run_string.Clear();
Caroline Tice202f6b82011-01-17 21:55:19 +00001410
1411 script_interpreter->LeaveSession ();
1412
Caroline Tice2ade6112010-11-10 19:18:14 +00001413 }
1414
Caroline Tice202f6b82011-01-17 21:55:19 +00001415 if (!safe_to_run)
1416 fprintf ((script_interpreter->m_dbg_stdout ? script_interpreter->m_dbg_stdout : stdout),
1417 "Python interpreter locked on another thread; unable to acquire lock.\n");
1418
1419 if (need_to_release_lock)
1420 ReleasePythonLock ();
1421
Caroline Tice2ade6112010-11-10 19:18:14 +00001422 if (script_interpreter->m_embedded_thread_input_reader_sp)
1423 script_interpreter->m_embedded_thread_input_reader_sp->SetIsDone (true);
1424
1425 script_interpreter->m_embedded_python_pty.CloseSlaveFileDescriptor();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001426
1427 script_interpreter->m_pty_slave_is_open = false;
Caroline Tice2ade6112010-11-10 19:18:14 +00001428
1429 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT);
1430 if (log)
1431 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread exiting...", baton);
1432
1433
Caroline Tice0aa2e552011-01-14 00:29:16 +00001434 // Clean up the input reader and make the debugger pop it off the stack.
1435 Debugger &debugger = script_interpreter->GetCommandInterpreter().GetDebugger();
Caroline Tice2ade6112010-11-10 19:18:14 +00001436 const InputReaderSP reader_sp = script_interpreter->m_embedded_thread_input_reader_sp;
1437 script_interpreter->m_embedded_thread_input_reader_sp.reset();
1438 debugger.PopInputReader (reader_sp);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001439
Caroline Tice2ade6112010-11-10 19:18:14 +00001440 return NULL;
1441}
1442
1443
Caroline Tice0aa2e552011-01-14 00:29:16 +00001444void
1445ScriptInterpreterPython::Initialize ()
1446{
Caroline Tice2ade6112010-11-10 19:18:14 +00001447
Caroline Tice0aa2e552011-01-14 00:29:16 +00001448 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
1449
1450 int input_fd = STDIN_FILENO;
1451
1452 struct termios stdin_termios;
1453 bool valid_termios = ::tcgetattr (input_fd, &stdin_termios) == 0;
1454
1455 // Find the module that owns this code and use that path we get to
1456 // set the PYTHONPATH appropriately.
1457
1458 FileSpec file_spec;
1459 char python_dir_path[PATH_MAX];
1460 if (Host::GetLLDBPath (ePathTypePythonDir, file_spec))
1461 {
1462 std::string python_path;
1463 const char *curr_python_path = ::getenv ("PYTHONPATH");
1464 if (curr_python_path)
1465 {
1466 // We have a current value for PYTHONPATH, so lets append to it
1467 python_path.append (curr_python_path);
1468 }
1469
1470 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
1471 {
1472 if (!python_path.empty())
1473 python_path.append (1, ':');
1474 python_path.append (python_dir_path);
1475 }
1476
1477 if (Host::GetLLDBPath (ePathTypeLLDBShlibDir, file_spec))
1478 {
1479 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
1480 {
1481 if (!python_path.empty())
1482 python_path.append (1, ':');
1483 python_path.append (python_dir_path);
1484 }
1485 }
1486 const char *pathon_path_env_cstr = python_path.c_str();
1487 ::setenv ("PYTHONPATH", pathon_path_env_cstr, 1);
1488 }
1489
1490 Py_Initialize ();
1491
1492 PyObject *compiled_module = Py_CompileString (embedded_interpreter_string,
1493 "embedded_interpreter.py",
1494 Py_file_input);
1495
1496 PyObject *py_error = PyErr_Occurred ();
1497 if (py_error != NULL)
1498 {
1499 PyErr_Print();
1500 PyErr_Clear();
1501 }
1502
1503
1504 // This function is in the C++ output file generated by SWIG after it is
1505 // run on all of the headers in "lldb/API/SB*.h"
1506 init_lldb ();
1507
1508 // Update the path python uses to search for modules to include the current directory.
1509
1510 int success = PyRun_SimpleString ("import sys");
1511 success = PyRun_SimpleString ("sys.path.append ('.')");
1512
1513 PyObject *pmod = NULL;
1514
1515 if (compiled_module)
1516 {
1517 pmod = PyImport_ExecCodeModule (const_cast<char*> ("embedded_interpreter"),
1518 compiled_module);
1519 Py_DECREF (compiled_module);
1520 }
1521
1522 if (pmod != NULL)
1523 {
1524 PyRun_SimpleString ("from embedded_interpreter import run_python_interpreter");
1525 PyRun_SimpleString ("from embedded_interpreter import run_one_line");
1526 PyRun_SimpleString ("import sys");
1527 PyRun_SimpleString ("from termios import *");
1528 Py_DECREF (pmod);
1529 }
1530
1531 if (valid_termios)
1532 ::tcsetattr (input_fd, TCSANOW, &stdin_termios);
1533}
1534
1535void
1536ScriptInterpreterPython::Terminate ()
1537{
1538 // We are intentionally NOT calling Py_Finalize here (this would be the logical place to call it). Calling
1539 // Py_Finalize here causes test suite runs to seg fault: The test suite runs in Python. It registers
1540 // SBDebugger::Terminate to be called 'at_exit'. When the test suite Python harness finishes up, it calls
1541 // Py_Finalize, which calls all the 'at_exit' registered functions. SBDebugger::Terminate calls Debugger::Terminate,
1542 // which calls lldb::Terminate, which calls ScriptInterpreter::Terminate, which calls
1543 // ScriptInterpreterPython::Terminate. So if we call Py_Finalize here, we end up with Py_Finalize being called from
1544 // within Py_Finalize, which results in a seg fault.
1545 //
1546 // Since this function only gets called when lldb is shutting down and going away anyway, the fact that we don't
1547 // actually call Py_Finalize should not cause any problems (everything should shut down/go away anyway when the
1548 // process exits).
1549 //
1550// Py_Finalize ();
1551}