blob: 368399b08e58fbfc2beb53829331a2a991404965 [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 {
578 ::fprintf (out_fh, "Python Interactive Interpreter. To exit Python, type 'quit()' or 'exit()'.\n");
579 ::fprintf (out_fh, "Do NOT use Ctrl-D (EOF) to exit, as that will cause the lldb debugger to hang.\n");
580 }
Chris Lattner24943d22010-06-08 16:52:24 +0000581 // Save terminal settings if we can
Caroline Ticec95c6d12010-09-14 22:49:06 +0000582 int input_fd;
Greg Clayton63094e02010-06-23 01:19:29 +0000583 FILE *input_fh = reader.GetDebugger().GetInputFileHandle();
Caroline Ticec95c6d12010-09-14 22:49:06 +0000584 if (input_fh != NULL)
Greg Clayton24b48ff2010-10-17 22:03:32 +0000585 input_fd = ::fileno (input_fh);
Caroline Ticec95c6d12010-09-14 22:49:06 +0000586 else
Greg Clayton24b48ff2010-10-17 22:03:32 +0000587 input_fd = STDIN_FILENO;
Caroline Ticec95c6d12010-09-14 22:49:06 +0000588
Greg Clayton63094e02010-06-23 01:19:29 +0000589 script_interpreter->m_termios_valid = ::tcgetattr (input_fd, &script_interpreter->m_termios) == 0;
Greg Clayton24b48ff2010-10-17 22:03:32 +0000590
Caroline Tice202f6b82011-01-17 21:55:19 +0000591 if (!CurrentThreadHasPythonLock())
592 {
593 while (!GetPythonLock(1))
594 {
595 ::fprintf (out_fh, "Python interpreter locked on another thread; waiting to acquire lock...\n");
596 }
597 script_interpreter->EnterSession ();
598 ReleasePythonLock();
599 }
600 else
601 script_interpreter->EnterSession ();
602
Caroline Tice2ade6112010-11-10 19:18:14 +0000603 char error_str[1024];
604 if (script_interpreter->m_embedded_python_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, error_str,
605 sizeof(error_str)))
606 {
607 if (log)
608 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in opening master pty (fd = %d).",
609 script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor());
610 embedded_interpreter_thread = Host::ThreadCreate ("<lldb.script-interpreter.embedded-python-loop>",
611 ScriptInterpreterPython::RunEmbeddedPythonInterpreter,
612 script_interpreter, NULL);
613 if (embedded_interpreter_thread != LLDB_INVALID_HOST_THREAD)
614 {
615 if (log)
616 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in creating thread (thread = %d)", embedded_interpreter_thread);
617 Error detach_error;
618 Host::ThreadDetach (embedded_interpreter_thread, &detach_error);
619 }
620 else
621 {
622 if (log)
623 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed in creating thread");
624 reader.SetIsDone (true);
625 }
626 }
627 else
628 {
629 if (log)
630 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed to open master pty ");
631 reader.SetIsDone (true);
632 }
Chris Lattner24943d22010-06-08 16:52:24 +0000633 }
634 break;
635
636 case eInputReaderDeactivate:
Caroline Tice0aa2e552011-01-14 00:29:16 +0000637 script_interpreter->LeaveSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000638 break;
639
640 case eInputReaderReactivate:
Caroline Tice202f6b82011-01-17 21:55:19 +0000641 if (!CurrentThreadHasPythonLock())
642 {
643 while (!GetPythonLock(1))
644 {
645 // Wait until lock is acquired.
646 }
647 script_interpreter->EnterSession ();
648 ReleasePythonLock();
649 }
650 else
651 script_interpreter->EnterSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000652 break;
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000653
654 case eInputReaderInterrupt:
655 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "raise KeyboardInterrupt\n", 24);
656 break;
657
658 case eInputReaderEndOfFile:
659 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()\n", 7);
660 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000661
662 case eInputReaderGotToken:
Caroline Tice2ade6112010-11-10 19:18:14 +0000663 if (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor() != -1)
Chris Lattner24943d22010-06-08 16:52:24 +0000664 {
Caroline Tice2ade6112010-11-10 19:18:14 +0000665 if (log)
666 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %d", bytes,
667 bytes_len);
668 if (bytes && bytes_len)
669 {
670 if ((int) bytes[0] == 4)
671 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()", 6);
672 else
673 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), bytes, bytes_len);
674 }
675 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "\n", 1);
Chris Lattner24943d22010-06-08 16:52:24 +0000676 }
Caroline Tice2ade6112010-11-10 19:18:14 +0000677 else
678 {
679 if (log)
680 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %d, Master File Descriptor is bad.",
681 bytes,
682 bytes_len);
683 reader.SetIsDone (true);
684 }
685
Chris Lattner24943d22010-06-08 16:52:24 +0000686 break;
687
688 case eInputReaderDone:
Caroline Tice0aa2e552011-01-14 00:29:16 +0000689 script_interpreter->LeaveSession ();
690
Chris Lattner24943d22010-06-08 16:52:24 +0000691 // Restore terminal settings if they were validly saved
Caroline Tice2ade6112010-11-10 19:18:14 +0000692 if (log)
693 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Done, closing down input reader.");
Greg Clayton63094e02010-06-23 01:19:29 +0000694 if (script_interpreter->m_termios_valid)
Chris Lattner24943d22010-06-08 16:52:24 +0000695 {
Caroline Ticec95c6d12010-09-14 22:49:06 +0000696 int input_fd;
697 FILE *input_fh = reader.GetDebugger().GetInputFileHandle();
698 if (input_fh != NULL)
Greg Clayton24b48ff2010-10-17 22:03:32 +0000699 input_fd = ::fileno (input_fh);
Caroline Ticec95c6d12010-09-14 22:49:06 +0000700 else
Greg Clayton24b48ff2010-10-17 22:03:32 +0000701 input_fd = STDIN_FILENO;
Caroline Ticec95c6d12010-09-14 22:49:06 +0000702
703 ::tcsetattr (input_fd, TCSANOW, &script_interpreter->m_termios);
Chris Lattner24943d22010-06-08 16:52:24 +0000704 }
Caroline Tice2ade6112010-11-10 19:18:14 +0000705 script_interpreter->m_embedded_python_pty.CloseMasterFileDescriptor();
Chris Lattner24943d22010-06-08 16:52:24 +0000706 break;
707 }
708
709 return bytes_len;
710}
711
712
713void
Greg Clayton238c0a12010-09-18 01:14:36 +0000714ScriptInterpreterPython::ExecuteInterpreterLoop ()
Chris Lattner24943d22010-06-08 16:52:24 +0000715{
716 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
717
Caroline Tice0aa2e552011-01-14 00:29:16 +0000718 Debugger &debugger = GetCommandInterpreter().GetDebugger();
Caroline Ticec95c6d12010-09-14 22:49:06 +0000719
720 // At the moment, the only time the debugger does not have an input file handle is when this is called
721 // directly from Python, in which case it is both dangerous and unnecessary (not to mention confusing) to
722 // try to embed a running interpreter loop inside the already running Python interpreter loop, so we won't
723 // do it.
724
725 if (debugger.GetInputFileHandle() == NULL)
726 return;
727
Greg Clayton63094e02010-06-23 01:19:29 +0000728 InputReaderSP reader_sp (new InputReader(debugger));
Chris Lattner24943d22010-06-08 16:52:24 +0000729 if (reader_sp)
730 {
731 Error error (reader_sp->Initialize (ScriptInterpreterPython::InputReaderCallback,
732 this, // baton
733 eInputReaderGranularityLine, // token size, to pass to callback function
734 NULL, // end token
735 NULL, // prompt
736 true)); // echo input
737
738 if (error.Success())
739 {
Greg Clayton63094e02010-06-23 01:19:29 +0000740 debugger.PushInputReader (reader_sp);
Caroline Tice2ade6112010-11-10 19:18:14 +0000741 m_embedded_thread_input_reader_sp = reader_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000742 }
743 }
744}
745
746bool
747ScriptInterpreterPython::ExecuteOneLineWithReturn (const char *in_string,
748 ScriptInterpreter::ReturnType return_type,
749 void *ret_value)
750{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000751
Caroline Tice202f6b82011-01-17 21:55:19 +0000752 bool need_to_release_lock = true;
753
754 if (CurrentThreadHasPythonLock())
755 need_to_release_lock = false;
756 else if (!GetPythonLock (1))
757 {
758 fprintf ((m_dbg_stdout ? m_dbg_stdout : stdout),
759 "Python interpreter is currently locked by another thread; unable to process command.\n");
760 return false;
761 }
762
763 EnterSession ();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000764
Chris Lattner24943d22010-06-08 16:52:24 +0000765 PyObject *py_return = NULL;
766 PyObject *mainmod = PyImport_AddModule ("__main__");
767 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000768 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000769 PyObject *py_error = NULL;
770 bool ret_success;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000771 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000772 int success;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000773
774 if (PyDict_Check (globals))
775 {
776 PyObject *key, *value;
777 Py_ssize_t pos = 0;
778
779 int i = 0;
780 while (PyDict_Next (globals, &pos, &key, &value))
781 {
782 // We have stolen references to the key and value objects in the dictionary; we need to increment them now
783 // so that Python's garbage collector doesn't collect them out from under us.
784 Py_INCREF (key);
785 Py_INCREF (value);
786 char *c_str = PyString_AsString (key);
787 if (strcmp (c_str, m_dictionary_name.c_str()) == 0)
788 locals = value;
789 ++i;
790 }
791 }
Chris Lattner24943d22010-06-08 16:52:24 +0000792
Caroline Tice0aa2e552011-01-14 00:29:16 +0000793 if (locals == NULL)
794 {
795 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
796 should_decrement_locals = true;
797 }
798
799 if (locals == NULL)
800 {
801 locals = globals;
802 should_decrement_locals = false;
803 }
804
805 py_error = PyErr_Occurred();
806 if (py_error != NULL)
807 PyErr_Clear();
808
Chris Lattner24943d22010-06-08 16:52:24 +0000809 if (in_string != NULL)
810 {
811 py_return = PyRun_String (in_string, Py_eval_input, globals, locals);
812 if (py_return == NULL)
813 {
814 py_error = PyErr_Occurred ();
815 if (py_error != NULL)
816 PyErr_Clear ();
817
818 py_return = PyRun_String (in_string, Py_single_input, globals, locals);
819 }
820
Caroline Tice0aa2e552011-01-14 00:29:16 +0000821 if (locals != NULL
822 && should_decrement_locals)
823 Py_DECREF (locals);
824
Chris Lattner24943d22010-06-08 16:52:24 +0000825 if (py_return != NULL)
826 {
827 switch (return_type)
828 {
829 case eCharPtr: // "char *"
830 {
831 const char format[3] = "s#";
832 success = PyArg_Parse (py_return, format, (char **) &ret_value);
833 break;
834 }
835 case eBool:
836 {
837 const char format[2] = "b";
838 success = PyArg_Parse (py_return, format, (bool *) ret_value);
839 break;
840 }
841 case eShortInt:
842 {
843 const char format[2] = "h";
844 success = PyArg_Parse (py_return, format, (short *) ret_value);
845 break;
846 }
847 case eShortIntUnsigned:
848 {
849 const char format[2] = "H";
850 success = PyArg_Parse (py_return, format, (unsigned short *) ret_value);
851 break;
852 }
853 case eInt:
854 {
855 const char format[2] = "i";
856 success = PyArg_Parse (py_return, format, (int *) ret_value);
857 break;
858 }
859 case eIntUnsigned:
860 {
861 const char format[2] = "I";
862 success = PyArg_Parse (py_return, format, (unsigned int *) ret_value);
863 break;
864 }
865 case eLongInt:
866 {
867 const char format[2] = "l";
868 success = PyArg_Parse (py_return, format, (long *) ret_value);
869 break;
870 }
871 case eLongIntUnsigned:
872 {
873 const char format[2] = "k";
874 success = PyArg_Parse (py_return, format, (unsigned long *) ret_value);
875 break;
876 }
877 case eLongLong:
878 {
879 const char format[2] = "L";
880 success = PyArg_Parse (py_return, format, (long long *) ret_value);
881 break;
882 }
883 case eLongLongUnsigned:
884 {
885 const char format[2] = "K";
886 success = PyArg_Parse (py_return, format, (unsigned long long *) ret_value);
887 break;
888 }
889 case eFloat:
890 {
891 const char format[2] = "f";
892 success = PyArg_Parse (py_return, format, (float *) ret_value);
893 break;
894 }
895 case eDouble:
896 {
897 const char format[2] = "d";
898 success = PyArg_Parse (py_return, format, (double *) ret_value);
899 break;
900 }
901 case eChar:
902 {
903 const char format[2] = "c";
904 success = PyArg_Parse (py_return, format, (char *) ret_value);
905 break;
906 }
907 default:
908 {}
909 }
910 Py_DECREF (py_return);
911 if (success)
912 ret_success = true;
913 else
914 ret_success = false;
915 }
916 }
917
918 py_error = PyErr_Occurred();
919 if (py_error != NULL)
920 {
921 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
922 PyErr_Print ();
923 PyErr_Clear();
924 ret_success = false;
925 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000926
927 LeaveSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000928
Caroline Tice202f6b82011-01-17 21:55:19 +0000929 if (need_to_release_lock)
930 ReleasePythonLock();
931
Chris Lattner24943d22010-06-08 16:52:24 +0000932 return ret_success;
933}
934
935bool
936ScriptInterpreterPython::ExecuteMultipleLines (const char *in_string)
937{
Caroline Tice202f6b82011-01-17 21:55:19 +0000938 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
939 bool need_to_release_lock = true;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000940
Caroline Tice202f6b82011-01-17 21:55:19 +0000941 if (CurrentThreadHasPythonLock())
942 need_to_release_lock = false;
943 else
944 {
945 while (!GetPythonLock (1))
946 fprintf (tmp_fh, "Python interpreter locked on another thread; waiting to acquire lock...\n");
947 }
948
949 EnterSession ();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000950
Chris Lattner24943d22010-06-08 16:52:24 +0000951 bool success = false;
952 PyObject *py_return = NULL;
953 PyObject *mainmod = PyImport_AddModule ("__main__");
954 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000955 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000956 PyObject *py_error = NULL;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000957 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000958
Caroline Tice0aa2e552011-01-14 00:29:16 +0000959 if (PyDict_Check (globals))
960 {
961 PyObject *key, *value;
962 Py_ssize_t pos = 0;
963
964 while (PyDict_Next (globals, &pos, &key, &value))
965 {
966 // We have stolen references to the key and value objects in the dictionary; we need to increment them now
967 // so that Python's garbage collector doesn't collect them out from under us.
968 Py_INCREF (key);
969 Py_INCREF (value);
970 if (strcmp (PyString_AsString (key), m_dictionary_name.c_str()) == 0)
971 locals = value;
972 }
973 }
974
975 if (locals == NULL)
976 {
977 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
978 should_decrement_locals = true;
979 }
980
981 if (locals == NULL)
982 {
983 locals = globals;
984 should_decrement_locals = false;
985 }
986
987 py_error = PyErr_Occurred();
988 if (py_error != NULL)
989 PyErr_Clear();
990
Chris Lattner24943d22010-06-08 16:52:24 +0000991 if (in_string != NULL)
992 {
993 struct _node *compiled_node = PyParser_SimpleParseString (in_string, Py_file_input);
994 if (compiled_node)
995 {
996 PyCodeObject *compiled_code = PyNode_Compile (compiled_node, "temp.py");
997 if (compiled_code)
998 {
999 py_return = PyEval_EvalCode (compiled_code, globals, locals);
1000 if (py_return != NULL)
1001 {
1002 success = true;
1003 Py_DECREF (py_return);
1004 }
Caroline Tice0aa2e552011-01-14 00:29:16 +00001005 if (locals && should_decrement_locals)
1006 Py_DECREF (locals);
Chris Lattner24943d22010-06-08 16:52:24 +00001007 }
1008 }
1009 }
1010
1011 py_error = PyErr_Occurred ();
1012 if (py_error != NULL)
1013 {
1014 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
1015 PyErr_Print ();
1016 PyErr_Clear();
1017 success = false;
1018 }
1019
Caroline Tice0aa2e552011-01-14 00:29:16 +00001020 LeaveSession ();
1021
Caroline Tice202f6b82011-01-17 21:55:19 +00001022 if (need_to_release_lock)
1023 ReleasePythonLock();
1024
Chris Lattner24943d22010-06-08 16:52:24 +00001025 return success;
1026}
1027
1028static const char *g_reader_instructions = "Enter your Python command(s). Type 'DONE' to end.";
1029
1030size_t
1031ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback
1032(
1033 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +00001034 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +00001035 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +00001036 const char *bytes,
1037 size_t bytes_len
1038)
1039{
1040 static StringList commands_in_progress;
1041
Greg Clayton63094e02010-06-23 01:19:29 +00001042 FILE *out_fh = reader.GetDebugger().GetOutputFileHandle();
Caroline Ticec95c6d12010-09-14 22:49:06 +00001043 if (out_fh == NULL)
1044 out_fh = stdout;
1045
Chris Lattner24943d22010-06-08 16:52:24 +00001046 switch (notification)
1047 {
1048 case eInputReaderActivate:
1049 {
1050 commands_in_progress.Clear();
1051 if (out_fh)
1052 {
1053 ::fprintf (out_fh, "%s\n", g_reader_instructions);
Greg Clayton63094e02010-06-23 01:19:29 +00001054 if (reader.GetPrompt())
1055 ::fprintf (out_fh, "%s", reader.GetPrompt());
Caroline Ticef81b4c52010-10-27 18:34:42 +00001056 ::fflush (out_fh);
Chris Lattner24943d22010-06-08 16:52:24 +00001057 }
1058 }
1059 break;
1060
1061 case eInputReaderDeactivate:
1062 break;
1063
1064 case eInputReaderReactivate:
Greg Clayton63094e02010-06-23 01:19:29 +00001065 if (reader.GetPrompt() && out_fh)
Caroline Ticef81b4c52010-10-27 18:34:42 +00001066 {
Greg Clayton63094e02010-06-23 01:19:29 +00001067 ::fprintf (out_fh, "%s", reader.GetPrompt());
Caroline Ticef81b4c52010-10-27 18:34:42 +00001068 ::fflush (out_fh);
1069 }
Chris Lattner24943d22010-06-08 16:52:24 +00001070 break;
1071
1072 case eInputReaderGotToken:
1073 {
1074 std::string temp_string (bytes, bytes_len);
1075 commands_in_progress.AppendString (temp_string.c_str());
Greg Clayton63094e02010-06-23 01:19:29 +00001076 if (out_fh && !reader.IsDone() && reader.GetPrompt())
Caroline Ticef81b4c52010-10-27 18:34:42 +00001077 {
Greg Clayton63094e02010-06-23 01:19:29 +00001078 ::fprintf (out_fh, "%s", reader.GetPrompt());
Caroline Ticef81b4c52010-10-27 18:34:42 +00001079 ::fflush (out_fh);
1080 }
Chris Lattner24943d22010-06-08 16:52:24 +00001081 }
1082 break;
1083
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001084 case eInputReaderEndOfFile:
1085 case eInputReaderInterrupt:
1086 // Control-c (SIGINT) & control-d both mean finish & exit.
1087 reader.SetIsDone(true);
1088
1089 // Control-c (SIGINT) ALSO means cancel; do NOT create a breakpoint command.
1090 if (notification == eInputReaderInterrupt)
1091 commands_in_progress.Clear();
1092
1093 // Fall through here...
1094
Chris Lattner24943d22010-06-08 16:52:24 +00001095 case eInputReaderDone:
1096 {
1097 BreakpointOptions *bp_options = (BreakpointOptions *)baton;
1098 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1099 data_ap->user_source.AppendList (commands_in_progress);
1100 if (data_ap.get())
1101 {
Greg Clayton63094e02010-06-23 01:19:29 +00001102 ScriptInterpreter *interpreter = reader.GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
Chris Lattner24943d22010-06-08 16:52:24 +00001103 if (interpreter)
1104 {
1105 if (interpreter->GenerateBreakpointCommandCallbackData (data_ap->user_source,
1106 data_ap->script_source))
1107 {
1108 if (data_ap->script_source.GetSize() == 1)
1109 {
1110 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1111 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
1112 }
1113 }
Caroline Ticeb447e842010-09-21 19:25:28 +00001114 else
Caroline Tice5136f942010-09-27 21:35:15 +00001115 ::fprintf (out_fh, "Warning: No command attached to breakpoint.\n");
Chris Lattner24943d22010-06-08 16:52:24 +00001116 }
1117 else
1118 {
1119 // FIXME: Error processing.
1120 }
1121 }
1122 }
1123 break;
1124
1125 }
1126
1127 return bytes_len;
1128}
1129
1130void
Greg Clayton238c0a12010-09-18 01:14:36 +00001131ScriptInterpreterPython::CollectDataForBreakpointCommandCallback (BreakpointOptions *bp_options,
Chris Lattner24943d22010-06-08 16:52:24 +00001132 CommandReturnObject &result)
1133{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001134 Debugger &debugger = GetCommandInterpreter().GetDebugger();
1135
Greg Clayton63094e02010-06-23 01:19:29 +00001136 InputReaderSP reader_sp (new InputReader (debugger));
Chris Lattner24943d22010-06-08 16:52:24 +00001137
1138 if (reader_sp)
1139 {
1140 Error err = reader_sp->Initialize (
1141 ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback,
1142 bp_options, // baton
1143 eInputReaderGranularityLine, // token size, for feeding data to callback function
1144 "DONE", // end token
1145 "> ", // prompt
1146 true); // echo input
1147
1148 if (err.Success())
Greg Clayton63094e02010-06-23 01:19:29 +00001149 debugger.PushInputReader (reader_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001150 else
1151 {
1152 result.AppendError (err.AsCString());
1153 result.SetStatus (eReturnStatusFailed);
1154 }
1155 }
1156 else
1157 {
1158 result.AppendError("out of memory");
1159 result.SetStatus (eReturnStatusFailed);
1160 }
1161}
1162
Johnny Chen3e0571b2010-09-11 00:23:59 +00001163// Set a Python one-liner as the callback for the breakpoint.
Johnny Chend1c2dca2010-09-10 18:21:10 +00001164void
Greg Clayton238c0a12010-09-18 01:14:36 +00001165ScriptInterpreterPython::SetBreakpointCommandCallback (BreakpointOptions *bp_options,
Johnny Chend1c2dca2010-09-10 18:21:10 +00001166 const char *oneliner)
1167{
1168 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1169
1170 // It's necessary to set both user_source and script_source to the oneliner.
1171 // The former is used to generate callback description (as in breakpoint command list)
1172 // while the latter is used for Python to interpret during the actual callback.
Caroline Tice5136f942010-09-27 21:35:15 +00001173
Johnny Chend1c2dca2010-09-10 18:21:10 +00001174 data_ap->user_source.AppendString (oneliner);
Johnny Chend1c2dca2010-09-10 18:21:10 +00001175
Caroline Tice5136f942010-09-27 21:35:15 +00001176 if (GenerateBreakpointCommandCallbackData (data_ap->user_source, data_ap->script_source))
1177 {
1178 if (data_ap->script_source.GetSize() == 1)
1179 {
1180 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1181 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
1182 }
1183 }
1184
Johnny Chend1c2dca2010-09-10 18:21:10 +00001185 return;
1186}
1187
Chris Lattner24943d22010-06-08 16:52:24 +00001188bool
1189ScriptInterpreterPython::ExportFunctionDefinitionToInterpreter (StringList &function_def)
1190{
1191 // Convert StringList to one long, newline delimited, const char *.
1192 std::string function_def_string;
1193
1194 int num_lines = function_def.GetSize();
1195
1196 for (int i = 0; i < num_lines; ++i)
1197 {
1198 function_def_string.append (function_def.GetStringAtIndex(i));
1199 if (function_def_string.at (function_def_string.length() - 1) != '\n')
1200 function_def_string.append ("\n");
1201
1202 }
1203
1204 return ExecuteMultipleLines (function_def_string.c_str());
1205}
1206
1207bool
1208ScriptInterpreterPython::GenerateBreakpointCommandCallbackData (StringList &user_input, StringList &callback_data)
1209{
1210 static int num_created_functions = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001211 user_input.RemoveBlankLines ();
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001212 int num_lines = user_input.GetSize ();
1213 StreamString sstr;
Chris Lattner24943d22010-06-08 16:52:24 +00001214
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001215 // Check to see if we have any data; if not, just return.
1216 if (user_input.GetSize() == 0)
1217 return false;
1218
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001219 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1220 // frame and breakpoint location as parameters to the function.
Caroline Ticeb447e842010-09-21 19:25:28 +00001221
Caroline Ticeb447e842010-09-21 19:25:28 +00001222
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001223 sstr.Printf ("lldb_autogen_python_bp_callback_func_%d", num_created_functions);
1224 ++num_created_functions;
1225 std::string auto_generated_function_name = sstr.GetData();
Caroline Ticeb447e842010-09-21 19:25:28 +00001226
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001227 sstr.Clear();
Caroline Ticeb447e842010-09-21 19:25:28 +00001228 StringList auto_generated_function;
Caroline Ticeb447e842010-09-21 19:25:28 +00001229
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001230 // Create the function name & definition string.
1231
Caroline Tice0aa2e552011-01-14 00:29:16 +00001232 sstr.Printf ("def %s (frame, bp_loc, dict):", auto_generated_function_name.c_str());
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001233 auto_generated_function.AppendString (sstr.GetData());
Caroline Tice0aa2e552011-01-14 00:29:16 +00001234
1235 // Pre-pend code for setting up the session dictionary.
1236
1237 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1238 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1239 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1240 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1241 // global dictionary.
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001242
1243 // Wrap everything up inside the function, increasing the indentation.
Chris Lattner24943d22010-06-08 16:52:24 +00001244
1245 for (int i = 0; i < num_lines; ++i)
1246 {
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001247 sstr.Clear ();
1248 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1249 auto_generated_function.AppendString (sstr.GetData());
Caroline Ticeb447e842010-09-21 19:25:28 +00001250 }
Chris Lattner24943d22010-06-08 16:52:24 +00001251
Caroline Tice0aa2e552011-01-14 00:29:16 +00001252 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1253 // got written to the values in the global dictionary, not the session dictionary).
1254
1255 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1256 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1257 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1258 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1259
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001260 // Verify that the results are valid Python.
Chris Lattner24943d22010-06-08 16:52:24 +00001261
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001262 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
Caroline Ticeb447e842010-09-21 19:25:28 +00001263 {
Caroline Ticeb447e842010-09-21 19:25:28 +00001264 return false;
Chris Lattner24943d22010-06-08 16:52:24 +00001265 }
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001266
1267 // Store the name of the auto-generated function to be called.
1268
1269 callback_data.AppendString (auto_generated_function_name.c_str());
1270 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001271}
1272
Greg Clayton5144f382010-10-07 17:14:24 +00001273bool
1274ScriptInterpreterPython::BreakpointCallbackFunction
1275(
1276 void *baton,
1277 StoppointCallbackContext *context,
1278 user_id_t break_id,
1279 user_id_t break_loc_id
1280)
1281{
1282 BreakpointOptions::CommandData *bp_option_data = (BreakpointOptions::CommandData *) baton;
1283 const char *python_function_name = bp_option_data->script_source.GetStringAtIndex (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001284
1285 if (!context)
1286 return true;
1287
1288 Target *target = context->exe_ctx.target;
1289
1290 if (!target)
1291 return true;
1292
1293 Debugger &debugger = target->GetDebugger();
1294 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1295 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1296
1297 if (!script_interpreter)
1298 return true;
Greg Clayton5144f382010-10-07 17:14:24 +00001299
1300 if (python_function_name != NULL
1301 && python_function_name[0] != '\0')
1302 {
1303 Thread *thread = context->exe_ctx.thread;
Greg Clayton5144f382010-10-07 17:14:24 +00001304 const StackFrameSP stop_frame_sp = thread->GetStackFrameSPForStackFramePtr (context->exe_ctx.frame);
1305 BreakpointSP breakpoint_sp = target->GetBreakpointByID (break_id);
1306 const BreakpointLocationSP bp_loc_sp = breakpoint_sp->FindLocationByID (break_loc_id);
1307
1308 SBFrame sb_frame (stop_frame_sp);
1309 SBBreakpointLocation sb_bp_loc (bp_loc_sp);
1310
1311 if (sb_bp_loc.IsValid() || sb_frame.IsValid())
Caroline Tice0aa2e552011-01-14 00:29:16 +00001312 {
Caroline Tice202f6b82011-01-17 21:55:19 +00001313 bool ret_val = true;
1314 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
1315 if (CurrentThreadHasPythonLock())
1316 {
1317 python_interpreter->EnterSession ();
1318 ret_val = LLDBSWIGPythonBreakpointCallbackFunction(python_function_name,
1319 python_interpreter->m_dictionary_name.c_str(),
1320 sb_frame, sb_bp_loc);
1321 python_interpreter->LeaveSession ();
1322 }
1323 else
1324 {
1325 while (!GetPythonLock (1))
1326 fprintf (tmp_fh,
1327 "Python interpreter locked on another thread; waiting to acquire lock...\n");
1328 python_interpreter->EnterSession ();
1329 ret_val = LLDBSWIGPythonBreakpointCallbackFunction(python_function_name,
1330 python_interpreter->m_dictionary_name.c_str(),
1331 sb_frame, sb_bp_loc);
1332 python_interpreter->LeaveSession ();
1333 ReleasePythonLock ();
1334 }
Caroline Tice0aa2e552011-01-14 00:29:16 +00001335 return ret_val;
1336 }
Greg Clayton5144f382010-10-07 17:14:24 +00001337 }
1338 // We currently always true so we stop in case anything goes wrong when
1339 // trying to call the script function
1340 return true;
1341}
Caroline Tice2ade6112010-11-10 19:18:14 +00001342
1343lldb::thread_result_t
1344ScriptInterpreterPython::RunEmbeddedPythonInterpreter (lldb::thread_arg_t baton)
1345{
1346 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
1347
1348 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
1349
1350 if (log)
1351 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread starting...", baton);
1352
1353 char error_str[1024];
1354 const char *pty_slave_name = script_interpreter->m_embedded_python_pty.GetSlaveName (error_str, sizeof (error_str));
Caroline Tice202f6b82011-01-17 21:55:19 +00001355 bool need_to_release_lock = true;
1356 bool safe_to_run = false;
Caroline Tice0aa2e552011-01-14 00:29:16 +00001357
Caroline Tice202f6b82011-01-17 21:55:19 +00001358 if (CurrentThreadHasPythonLock())
1359 {
1360 safe_to_run = true;
1361 need_to_release_lock = false;
1362 }
1363 else
1364 {
1365 int interval = 1;
1366 safe_to_run = GetPythonLock (interval);
1367 while (!safe_to_run)
1368 {
1369 interval = interval * 2;
1370 safe_to_run = GetPythonLock (interval);
1371 }
1372 }
1373
1374 if (pty_slave_name != NULL && safe_to_run)
1375 {
Caroline Tice2ade6112010-11-10 19:18:14 +00001376 StreamString run_string;
Caroline Tice2ade6112010-11-10 19:18:14 +00001377
Caroline Tice202f6b82011-01-17 21:55:19 +00001378 script_interpreter->EnterSession ();
1379
Caroline Tice0aa2e552011-01-14 00:29:16 +00001380 run_string.Printf ("run_one_line (%s, 'save_stderr = sys.stderr')", 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.stderr = sys.stdout')", script_interpreter->m_dictionary_name.c_str());
1385 PyRun_SimpleString (run_string.GetData());
1386 run_string.Clear ();
1387
1388 run_string.Printf ("run_one_line (%s, 'save_stdin = sys.stdin')", script_interpreter->m_dictionary_name.c_str());
1389 PyRun_SimpleString (run_string.GetData());
1390 run_string.Clear ();
1391
1392 run_string.Printf ("run_one_line (%s, \"sys.stdin = open ('%s', 'r')\")", script_interpreter->m_dictionary_name.c_str(),
1393 pty_slave_name);
1394 PyRun_SimpleString (run_string.GetData());
1395 run_string.Clear ();
1396
Caroline Tice2ade6112010-11-10 19:18:14 +00001397 // The following call drops into the embedded interpreter loop and stays there until the
1398 // user chooses to exit from the Python interpreter.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001399
1400 run_string.Printf ("run_python_interpreter (%s)", script_interpreter->m_dictionary_name.c_str());
1401 PyRun_SimpleString (run_string.GetData());
1402 run_string.Clear ();
Caroline Tice2ade6112010-11-10 19:18:14 +00001403
Caroline Tice0aa2e552011-01-14 00:29:16 +00001404 run_string.Printf ("run_one_line (%s, 'sys.stdin = save_stdin')", script_interpreter->m_dictionary_name.c_str());
1405 PyRun_SimpleString (run_string.GetData());
1406 run_string.Clear();
1407
1408 run_string.Printf ("run_one_line (%s, 'sys.stderr = save_stderr')", script_interpreter->m_dictionary_name.c_str());
1409 PyRun_SimpleString (run_string.GetData());
1410 run_string.Clear();
Caroline Tice202f6b82011-01-17 21:55:19 +00001411
1412 script_interpreter->LeaveSession ();
1413
Caroline Tice2ade6112010-11-10 19:18:14 +00001414 }
1415
Caroline Tice202f6b82011-01-17 21:55:19 +00001416 if (!safe_to_run)
1417 fprintf ((script_interpreter->m_dbg_stdout ? script_interpreter->m_dbg_stdout : stdout),
1418 "Python interpreter locked on another thread; unable to acquire lock.\n");
1419
1420 if (need_to_release_lock)
1421 ReleasePythonLock ();
1422
Caroline Tice2ade6112010-11-10 19:18:14 +00001423 if (script_interpreter->m_embedded_thread_input_reader_sp)
1424 script_interpreter->m_embedded_thread_input_reader_sp->SetIsDone (true);
1425
1426 script_interpreter->m_embedded_python_pty.CloseSlaveFileDescriptor();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001427
1428 script_interpreter->m_pty_slave_is_open = false;
Caroline Tice2ade6112010-11-10 19:18:14 +00001429
1430 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT);
1431 if (log)
1432 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread exiting...", baton);
1433
1434
Caroline Tice0aa2e552011-01-14 00:29:16 +00001435 // Clean up the input reader and make the debugger pop it off the stack.
1436 Debugger &debugger = script_interpreter->GetCommandInterpreter().GetDebugger();
Caroline Tice2ade6112010-11-10 19:18:14 +00001437 const InputReaderSP reader_sp = script_interpreter->m_embedded_thread_input_reader_sp;
1438 script_interpreter->m_embedded_thread_input_reader_sp.reset();
1439 debugger.PopInputReader (reader_sp);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001440
Caroline Tice2ade6112010-11-10 19:18:14 +00001441 return NULL;
1442}
1443
1444
Caroline Tice0aa2e552011-01-14 00:29:16 +00001445void
1446ScriptInterpreterPython::Initialize ()
1447{
Caroline Tice2ade6112010-11-10 19:18:14 +00001448
Caroline Tice0aa2e552011-01-14 00:29:16 +00001449 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
1450
1451 int input_fd = STDIN_FILENO;
1452
1453 struct termios stdin_termios;
1454 bool valid_termios = ::tcgetattr (input_fd, &stdin_termios) == 0;
1455
1456 // Find the module that owns this code and use that path we get to
1457 // set the PYTHONPATH appropriately.
1458
1459 FileSpec file_spec;
1460 char python_dir_path[PATH_MAX];
1461 if (Host::GetLLDBPath (ePathTypePythonDir, file_spec))
1462 {
1463 std::string python_path;
1464 const char *curr_python_path = ::getenv ("PYTHONPATH");
1465 if (curr_python_path)
1466 {
1467 // We have a current value for PYTHONPATH, so lets append to it
1468 python_path.append (curr_python_path);
1469 }
1470
1471 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
1472 {
1473 if (!python_path.empty())
1474 python_path.append (1, ':');
1475 python_path.append (python_dir_path);
1476 }
1477
1478 if (Host::GetLLDBPath (ePathTypeLLDBShlibDir, file_spec))
1479 {
1480 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
1481 {
1482 if (!python_path.empty())
1483 python_path.append (1, ':');
1484 python_path.append (python_dir_path);
1485 }
1486 }
1487 const char *pathon_path_env_cstr = python_path.c_str();
1488 ::setenv ("PYTHONPATH", pathon_path_env_cstr, 1);
1489 }
1490
1491 Py_Initialize ();
1492
1493 PyObject *compiled_module = Py_CompileString (embedded_interpreter_string,
1494 "embedded_interpreter.py",
1495 Py_file_input);
1496
1497 PyObject *py_error = PyErr_Occurred ();
1498 if (py_error != NULL)
1499 {
1500 PyErr_Print();
1501 PyErr_Clear();
1502 }
1503
1504
1505 // This function is in the C++ output file generated by SWIG after it is
1506 // run on all of the headers in "lldb/API/SB*.h"
1507 init_lldb ();
1508
1509 // Update the path python uses to search for modules to include the current directory.
1510
1511 int success = PyRun_SimpleString ("import sys");
1512 success = PyRun_SimpleString ("sys.path.append ('.')");
1513
1514 PyObject *pmod = NULL;
1515
1516 if (compiled_module)
1517 {
1518 pmod = PyImport_ExecCodeModule (const_cast<char*> ("embedded_interpreter"),
1519 compiled_module);
1520 Py_DECREF (compiled_module);
1521 }
1522
1523 if (pmod != NULL)
1524 {
1525 PyRun_SimpleString ("from embedded_interpreter import run_python_interpreter");
1526 PyRun_SimpleString ("from embedded_interpreter import run_one_line");
1527 PyRun_SimpleString ("import sys");
1528 PyRun_SimpleString ("from termios import *");
1529 Py_DECREF (pmod);
1530 }
1531
1532 if (valid_termios)
1533 ::tcsetattr (input_fd, TCSANOW, &stdin_termios);
1534}
1535
1536void
1537ScriptInterpreterPython::Terminate ()
1538{
1539 // We are intentionally NOT calling Py_Finalize here (this would be the logical place to call it). Calling
1540 // Py_Finalize here causes test suite runs to seg fault: The test suite runs in Python. It registers
1541 // SBDebugger::Terminate to be called 'at_exit'. When the test suite Python harness finishes up, it calls
1542 // Py_Finalize, which calls all the 'at_exit' registered functions. SBDebugger::Terminate calls Debugger::Terminate,
1543 // which calls lldb::Terminate, which calls ScriptInterpreter::Terminate, which calls
1544 // ScriptInterpreterPython::Terminate. So if we call Py_Finalize here, we end up with Py_Finalize being called from
1545 // within Py_Finalize, which results in a seg fault.
1546 //
1547 // Since this function only gets called when lldb is shutting down and going away anyway, the fact that we don't
1548 // actually call Py_Finalize should not cause any problems (everything should shut down/go away anyway when the
1549 // process exits).
1550 //
1551// Py_Finalize ();
1552}