blob: d461fb2221994e41f919509b53d1ade678cd28a6 [file] [log] [blame]
Chris Lattner24943d22010-06-08 16:52:24 +00001//===-- ScriptInterpreterPython.cpp -----------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10// In order to guarantee correct working with Python, Python.h *MUST* be
Greg Clayton17f5afe2011-02-05 02:56:16 +000011// the *FIRST* header file included in ScriptInterpreterPython.h, and that
12// must be the *FIRST* header file included here.
Chris Lattner24943d22010-06-08 16:52:24 +000013
14#include "lldb/Interpreter/ScriptInterpreterPython.h"
15
Chris Lattner24943d22010-06-08 16:52:24 +000016#include <stdlib.h>
17#include <stdio.h>
18
19#include <string>
20
Greg Clayton5144f382010-10-07 17:14:24 +000021#include "lldb/API/SBFrame.h"
22#include "lldb/API/SBBreakpointLocation.h"
Greg Clayton63094e02010-06-23 01:19:29 +000023#include "lldb/Breakpoint/StoppointCallbackContext.h"
Chris Lattner24943d22010-06-08 16:52:24 +000024#include "lldb/Core/Debugger.h"
Chris Lattner24943d22010-06-08 16:52:24 +000025#include "lldb/Core/Timer.h"
26#include "lldb/Host/Host.h"
27#include "lldb/Interpreter/CommandInterpreter.h"
28#include "lldb/Interpreter/CommandReturnObject.h"
Greg Clayton5144f382010-10-07 17:14:24 +000029#include "lldb/Target/Thread.h"
Chris Lattner24943d22010-06-08 16:52:24 +000030
Greg Clayton121f3312010-07-07 18:40:03 +000031// This function is in the C++ output file generated by SWIG after it is
32// run on all of the headers in "lldb/API/SB*.h"
Chris Lattner24943d22010-06-08 16:52:24 +000033extern "C" void init_lldb (void);
34
Greg Clayton5144f382010-10-07 17:14:24 +000035extern "C" bool
36LLDBSWIGPythonBreakpointCallbackFunction
37(
38 const char *python_function_name,
Caroline Tice0aa2e552011-01-14 00:29:16 +000039 const char *session_dictionary_name,
Greg Clayton5144f382010-10-07 17:14:24 +000040 lldb::SBFrame& sb_frame,
41 lldb::SBBreakpointLocation& sb_bp_loc
42);
43
Chris Lattner24943d22010-06-08 16:52:24 +000044using namespace lldb;
45using namespace lldb_private;
46
47const char embedded_interpreter_string[] =
48"import readline\n\
49import code\n\
50import sys\n\
51import traceback\n\
52\n\
53class SimpleREPL(code.InteractiveConsole):\n\
54 def __init__(self, prompt, dict):\n\
55 code.InteractiveConsole.__init__(self,dict)\n\
56 self.prompt = prompt\n\
57 self.loop_exit = False\n\
58 self.dict = dict\n\
59\n\
60 def interact(self):\n\
61 try:\n\
62 sys.ps1\n\
63 except AttributeError:\n\
64 sys.ps1 = \">>> \"\n\
65 try:\n\
66 sys.ps2\n\
67 except AttributeError:\n\
68 sys.ps2 = \"... \"\n\
69\n\
70 while not self.loop_exit:\n\
71 try:\n\
72 self.read_py_command()\n\
73 except (SystemExit, EOFError):\n\
74 # EOF while in Python just breaks out to top level.\n\
75 self.write('\\n')\n\
76 self.loop_exit = True\n\
77 break\n\
78 except KeyboardInterrupt:\n\
79 self.write(\"\\nKeyboardInterrupt\\n\")\n\
80 self.resetbuffer()\n\
81 more = 0\n\
82 except:\n\
83 traceback.print_exc()\n\
84\n\
85 def process_input (self, in_str):\n\
86 # Canonicalize the format of the input string\n\
87 temp_str = in_str\n\
88 temp_str.strip(' \t')\n\
89 words = temp_str.split()\n\
90 temp_str = ('').join(words)\n\
91\n\
92 # Check the input string to see if it was the quit\n\
93 # command. If so, intercept it, so that it doesn't\n\
94 # close stdin on us!\n\
Jason Molendaa8a5e562010-06-09 21:56:00 +000095 if (temp_str.lower() == \"quit()\" or temp_str.lower() == \"exit()\"):\n\
Chris Lattner24943d22010-06-08 16:52:24 +000096 self.loop_exit = True\n\
97 in_str = \"raise SystemExit \"\n\
98 return in_str\n\
99\n\
100 def my_raw_input (self, prompt):\n\
101 stream = sys.stdout\n\
102 stream.write (prompt)\n\
103 stream.flush ()\n\
104 try:\n\
105 line = sys.stdin.readline()\n\
106 except KeyboardInterrupt:\n\
107 line = \" \\n\"\n\
108 except (SystemExit, EOFError):\n\
109 line = \"quit()\\n\"\n\
110 if not line:\n\
111 raise EOFError\n\
112 if line[-1] == '\\n':\n\
113 line = line[:-1]\n\
114 return line\n\
115\n\
116 def read_py_command(self):\n\
117 # Read off a complete Python command.\n\
118 more = 0\n\
119 while 1:\n\
120 if more:\n\
121 prompt = sys.ps2\n\
122 else:\n\
123 prompt = sys.ps1\n\
124 line = self.my_raw_input(prompt)\n\
125 # Can be None if sys.stdin was redefined\n\
126 encoding = getattr(sys.stdin, \"encoding\", None)\n\
127 if encoding and not isinstance(line, unicode):\n\
128 line = line.decode(encoding)\n\
129 line = self.process_input (line)\n\
130 more = self.push(line)\n\
131 if not more:\n\
132 break\n\
133\n\
Caroline Tice0aa2e552011-01-14 00:29:16 +0000134 def one_line (self, input):\n\
135 line = self.process_input (input)\n\
136 more = self.push(line)\n\
137 if more:\n\
138 self.write (\"Input not a complete line.\")\n\
139 self.resetbuffer()\n\
140 more = 0\n\
141\n\
Chris Lattner24943d22010-06-08 16:52:24 +0000142def run_python_interpreter (dict):\n\
143 # Pass in the dictionary, for continuity from one session to the next.\n\
144 repl = SimpleREPL('>>> ', dict)\n\
Caroline Tice0aa2e552011-01-14 00:29:16 +0000145 repl.interact()\n\
146\n\
147def run_one_line (dict, input_string):\n\
148 repl = SimpleREPL ('', dict)\n\
149 repl.one_line (input_string)\n";
Chris Lattner24943d22010-06-08 16:52:24 +0000150
151static int
152_check_and_flush (FILE *stream)
153{
154 int prev_fail = ferror (stream);
155 return fflush (stream) || prev_fail ? EOF : 0;
156}
157
Caroline Tice202f6b82011-01-17 21:55:19 +0000158static Predicate<lldb::tid_t> &
159PythonMutexPredicate ()
Caroline Tice0aa2e552011-01-14 00:29:16 +0000160{
Caroline Tice202f6b82011-01-17 21:55:19 +0000161 static lldb_private::Predicate<lldb::tid_t> g_interpreter_is_running (LLDB_INVALID_THREAD_ID);
162 return g_interpreter_is_running;
163}
164
165static bool
166CurrentThreadHasPythonLock ()
167{
168 TimeValue timeout;
169
170 timeout = TimeValue::Now(); // Don't wait any time.
171
172 return PythonMutexPredicate().WaitForValueEqualTo (Host::GetCurrentThreadID(), &timeout, NULL);
173}
174
175static bool
176GetPythonLock (uint32_t seconds_to_wait)
177{
178
179 TimeValue timeout;
180
181 if (seconds_to_wait != UINT32_MAX)
182 {
183 timeout = TimeValue::Now();
184 timeout.OffsetWithSeconds (seconds_to_wait);
185 }
186
187 return PythonMutexPredicate().WaitForValueEqualToAndSetValueTo (LLDB_INVALID_THREAD_ID,
188 Host::GetCurrentThreadID(), &timeout, NULL);
189}
190
191static void
192ReleasePythonLock ()
193{
194 PythonMutexPredicate().SetValue (LLDB_INVALID_THREAD_ID, eBroadcastAlways);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000195}
196
Greg Clayton63094e02010-06-23 01:19:29 +0000197ScriptInterpreterPython::ScriptInterpreterPython (CommandInterpreter &interpreter) :
Greg Clayton238c0a12010-09-18 01:14:36 +0000198 ScriptInterpreter (interpreter, eScriptLanguagePython),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000199 m_embedded_python_pty (),
200 m_embedded_thread_input_reader_sp (),
201 m_dbg_stdout (interpreter.GetDebugger().GetOutputFileHandle()),
202 m_new_sysout (NULL),
203 m_dictionary_name (interpreter.GetDebugger().GetInstanceName().AsCString()),
Greg Clayton99208582011-02-07 19:04:58 +0000204#if LLDB_CONFIG_TERMIOS_SUPPORTED
Caroline Tice2ade6112010-11-10 19:18:14 +0000205 m_termios (),
206 m_termios_valid (false),
Greg Clayton9a7a9472011-02-07 19:22:32 +0000207#endif // #if LLDB_CONFIG_TERMIOS_SUPPORTED
Caroline Tice0aa2e552011-01-14 00:29:16 +0000208 m_session_is_active (false),
209 m_pty_slave_is_open (false),
210 m_valid_session (true)
Chris Lattner24943d22010-06-08 16:52:24 +0000211{
212
Greg Clayton7c330d62011-01-27 01:01:10 +0000213 static int g_initialized = false;
214
215 if (!g_initialized)
216 {
217 g_initialized = true;
218 ScriptInterpreterPython::Initialize ();
219 }
220
Caroline Tice202f6b82011-01-17 21:55:19 +0000221 bool safe_to_run = false;
222 bool need_to_release_lock = true;
223 int interval = 5; // Number of seconds to try getting the Python lock before timing out.
224
225 // We don't dare exit this function without finishing setting up the script interpreter, so we must wait until
226 // we can get the Python lock.
227
228 if (CurrentThreadHasPythonLock())
229 {
230 safe_to_run = true;
231 need_to_release_lock = false;
232 }
233
234 while (!safe_to_run)
235 {
236 safe_to_run = GetPythonLock (interval);
237 if (!safe_to_run)
238 {
239 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
240 fprintf (tmp_fh,
241 "Python interpreter is locked on another thread; "
242 "please release interpreter in order to continue.\n");
243 interval = interval * 2;
244 }
245 }
246
Caroline Tice0aa2e552011-01-14 00:29:16 +0000247 m_dictionary_name.append("_dict");
248 StreamString run_string;
249 run_string.Printf ("%s = dict()", m_dictionary_name.c_str());
250 PyRun_SimpleString (run_string.GetData());
Caroline Tice5867f6b2010-10-18 18:24:17 +0000251
Caroline Tice0aa2e552011-01-14 00:29:16 +0000252 run_string.Clear();
253 run_string.Printf ("run_one_line (%s, 'import sys')", m_dictionary_name.c_str());
254 PyRun_SimpleString (run_string.GetData());
255
256 // Importing 'lldb' module calls SBDebugger::Initialize, which calls Debugger::Initialize, which increments a
257 // global debugger ref-count; therefore we need to check the ref-count before and after importing lldb, and if the
258 // ref-count increased we need to call Debugger::Terminate here to decrement the ref-count so that when the final
259 // call to Debugger::Terminate is made, the ref-count has the correct value.
260 //
261 // Bonus question: Why doesn't the ref-count always increase? Because sometimes lldb has already been imported, in
262 // which case the code inside it, including the call to SBDebugger::Initialize(), does not get executed.
Caroline Tice5867f6b2010-10-18 18:24:17 +0000263
Caroline Tice0aa2e552011-01-14 00:29:16 +0000264 int old_count = Debugger::TestDebuggerRefCount();
Chris Lattner24943d22010-06-08 16:52:24 +0000265
Caroline Tice0aa2e552011-01-14 00:29:16 +0000266 run_string.Clear();
267 run_string.Printf ("run_one_line (%s, 'import lldb')", m_dictionary_name.c_str());
268 PyRun_SimpleString (run_string.GetData());
Greg Clayton24b48ff2010-10-17 22:03:32 +0000269
Caroline Tice0aa2e552011-01-14 00:29:16 +0000270 int new_count = Debugger::TestDebuggerRefCount();
Chris Lattner24943d22010-06-08 16:52:24 +0000271
Caroline Tice0aa2e552011-01-14 00:29:16 +0000272 if (new_count > old_count)
273 Debugger::Terminate();
Caroline Tice5867f6b2010-10-18 18:24:17 +0000274
Caroline Tice0aa2e552011-01-14 00:29:16 +0000275 run_string.Clear();
276 run_string.Printf ("run_one_line (%s, 'import copy')", m_dictionary_name.c_str());
277 PyRun_SimpleString (run_string.GetData());
278
279 run_string.Clear();
280 run_string.Printf ("run_one_line (%s, 'lldb.debugger_unique_id = %d')", m_dictionary_name.c_str(),
281 interpreter.GetDebugger().GetID());
282 PyRun_SimpleString (run_string.GetData());
283
284 if (m_dbg_stdout != NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000285 {
Caroline Tice0aa2e552011-01-14 00:29:16 +0000286 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
Caroline Tice5867f6b2010-10-18 18:24:17 +0000287 }
Caroline Tice202f6b82011-01-17 21:55:19 +0000288
289 if (need_to_release_lock)
290 ReleasePythonLock();
Chris Lattner24943d22010-06-08 16:52:24 +0000291}
292
293ScriptInterpreterPython::~ScriptInterpreterPython ()
294{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000295 Debugger &debugger = GetCommandInterpreter().GetDebugger();
296
297 if (m_embedded_thread_input_reader_sp.get() != NULL)
298 {
299 m_embedded_thread_input_reader_sp->SetIsDone (true);
300 m_embedded_python_pty.CloseSlaveFileDescriptor();
301 m_pty_slave_is_open = false;
302 const InputReaderSP reader_sp = m_embedded_thread_input_reader_sp;
303 m_embedded_thread_input_reader_sp.reset();
304 debugger.PopInputReader (reader_sp);
305 }
306
307 if (m_new_sysout)
308 {
Caroline Tice202f6b82011-01-17 21:55:19 +0000309 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
310 if (!CurrentThreadHasPythonLock ())
311 {
312 while (!GetPythonLock (1))
313 fprintf (tmp_fh, "Python interpreter locked on another thread; waiting to acquire lock...\n");
314 Py_DECREF (m_new_sysout);
315 ReleasePythonLock ();
316 }
317 else
318 Py_DECREF (m_new_sysout);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000319 }
Chris Lattner24943d22010-06-08 16:52:24 +0000320}
321
Caroline Tice0aa2e552011-01-14 00:29:16 +0000322void
323ScriptInterpreterPython::ResetOutputFileHandle (FILE *fh)
324{
325 if (fh == NULL)
326 return;
327
328 m_dbg_stdout = fh;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000329
Caroline Tice202f6b82011-01-17 21:55:19 +0000330 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
331 if (!CurrentThreadHasPythonLock ())
332 {
333 while (!GetPythonLock (1))
334 fprintf (tmp_fh, "Python interpreter locked on another thread; waiting to acquire lock...\n");
335 EnterSession ();
336 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
337 LeaveSession ();
338 ReleasePythonLock ();
339 }
340 else
341 {
342 EnterSession ();
343 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
344 LeaveSession ();
345 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000346}
347
348void
349ScriptInterpreterPython::LeaveSession ()
350{
351 m_session_is_active = false;
352}
353
354void
355ScriptInterpreterPython::EnterSession ()
356{
357 // If we have already entered the session, without having officially 'left' it, then there is no need to
358 // 'enter' it again.
359
360 if (m_session_is_active)
361 return;
362
363 m_session_is_active = true;
364
Caroline Tice202f6b82011-01-17 21:55:19 +0000365 StreamString run_string;
366
367 run_string.Printf ("run_one_line (%s, 'lldb.debugger_unique_id = %d')", m_dictionary_name.c_str(),
368 GetCommandInterpreter().GetDebugger().GetID());
369 PyRun_SimpleString (run_string.GetData());
370
Caroline Tice0aa2e552011-01-14 00:29:16 +0000371
372 PyObject *sysmod = PyImport_AddModule ("sys");
373 PyObject *sysdict = PyModule_GetDict (sysmod);
374
375 if ((m_new_sysout != NULL)
376 && (sysmod != NULL)
377 && (sysdict != NULL))
378 PyDict_SetItemString (sysdict, "stdout", m_new_sysout);
379
380 if (PyErr_Occurred())
381 PyErr_Clear ();
382
Caroline Tice0aa2e552011-01-14 00:29:16 +0000383 if (!m_pty_slave_is_open)
384 {
Caroline Tice202f6b82011-01-17 21:55:19 +0000385 run_string.Clear();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000386 run_string.Printf ("run_one_line (%s, \"new_stdin = open('%s', 'r')\")", m_dictionary_name.c_str(),
387 m_pty_slave_name.c_str());
388 PyRun_SimpleString (run_string.GetData());
389 m_pty_slave_is_open = true;
390
391 run_string.Clear();
392 run_string.Printf ("run_one_line (%s, 'sys.stdin = new_stdin')", m_dictionary_name.c_str());
393 PyRun_SimpleString (run_string.GetData());
394 }
395}
396
397
Johnny Chen60dde642010-07-30 22:33:14 +0000398bool
Greg Clayton238c0a12010-09-18 01:14:36 +0000399ScriptInterpreterPython::ExecuteOneLine (const char *command, CommandReturnObject *result)
Chris Lattner24943d22010-06-08 16:52:24 +0000400{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000401 if (!m_valid_session)
402 return false;
403
Caroline Tice0aa2e552011-01-14 00:29:16 +0000404
Caroline Tice0aa2e552011-01-14 00:29:16 +0000405
Caroline Tice4a461da2011-01-14 21:09:29 +0000406 // We want to call run_one_line, passing in the dictionary and the command string. We cannot do this through
407 // PyRun_SimpleString here because the command string may contain escaped characters, and putting it inside
408 // another string to pass to PyRun_SimpleString messes up the escaping. So we use the following more complicated
409 // method to pass the command string directly down to Python.
410
411
Caroline Tice202f6b82011-01-17 21:55:19 +0000412 bool need_to_release_lock = true;
413
414 if (CurrentThreadHasPythonLock())
415 need_to_release_lock = false;
416 else if (!GetPythonLock (1))
417 {
418 fprintf ((m_dbg_stdout ? m_dbg_stdout : stdout),
419 "Python interpreter is currently locked by another thread; unable to process command.\n");
420 return false;
421 }
422
423 EnterSession ();
Caroline Tice4a461da2011-01-14 21:09:29 +0000424 bool success = false;
425
Greg Clayton63094e02010-06-23 01:19:29 +0000426 if (command)
Chris Lattner24943d22010-06-08 16:52:24 +0000427 {
Caroline Tice4a461da2011-01-14 21:09:29 +0000428 // Find the correct script interpreter dictionary in the main module.
429 PyObject *main_mod = PyImport_AddModule ("__main__");
430 PyObject *script_interpreter_dict = NULL;
431 if (main_mod != NULL)
432 {
433 PyObject *main_dict = PyModule_GetDict (main_mod);
434 if ((main_dict != NULL)
435 && PyDict_Check (main_dict))
436 {
437 // Go through the main dictionary looking for the correct python script interpreter dictionary
438 PyObject *key, *value;
439 Py_ssize_t pos = 0;
440
441 while (PyDict_Next (main_dict, &pos, &key, &value))
442 {
443 // We have stolen references to the key and value objects in the dictionary; we need to increment
444 // them now so that Python's garbage collector doesn't collect them out from under us.
445 Py_INCREF (key);
446 Py_INCREF (value);
447 if (strcmp (PyString_AsString (key), m_dictionary_name.c_str()) == 0)
448 {
449 script_interpreter_dict = value;
450 break;
451 }
452 }
453 }
454
455 if (script_interpreter_dict != NULL)
456 {
457 PyObject *pfunc = NULL;
458 PyObject *pmod = PyImport_AddModule ("embedded_interpreter");
459 if (pmod != NULL)
460 {
461 PyObject *pmod_dict = PyModule_GetDict (pmod);
462 if ((pmod_dict != NULL)
463 && PyDict_Check (pmod_dict))
464 {
465 PyObject *key, *value;
466 Py_ssize_t pos = 0;
467
468 while (PyDict_Next (pmod_dict, &pos, &key, &value))
469 {
470 Py_INCREF (key);
471 Py_INCREF (value);
472 if (strcmp (PyString_AsString (key), "run_one_line") == 0)
473 {
474 pfunc = value;
475 break;
476 }
477 }
478
479 PyObject *string_arg = PyString_FromString (command);
480 if (pfunc && string_arg && PyCallable_Check (pfunc))
481 {
482 PyObject *pargs = PyTuple_New (2);
483 if (pargs != NULL)
484 {
485 PyTuple_SetItem (pargs, 0, script_interpreter_dict);
486 PyTuple_SetItem (pargs, 1, string_arg);
487 PyObject *pvalue = PyObject_CallObject (pfunc, pargs);
488 Py_DECREF (pargs);
489 if (pvalue != NULL)
490 {
491 Py_DECREF (pvalue);
492 success = true;
493 }
494 else if (PyErr_Occurred ())
495 {
496 PyErr_Print();
497 PyErr_Clear();
498 }
499 }
500 }
501 }
502 }
503 Py_INCREF (script_interpreter_dict);
504 }
505 }
Greg Clayton63094e02010-06-23 01:19:29 +0000506
Caroline Tice0aa2e552011-01-14 00:29:16 +0000507 LeaveSession ();
508
Caroline Tice202f6b82011-01-17 21:55:19 +0000509 if (need_to_release_lock)
510 ReleasePythonLock();
511
Caroline Tice4a461da2011-01-14 21:09:29 +0000512 if (success)
Johnny Chen60dde642010-07-30 22:33:14 +0000513 return true;
514
515 // The one-liner failed. Append the error message.
516 if (result)
517 result->AppendErrorWithFormat ("python failed attempting to evaluate '%s'\n", command);
518 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000519 }
Johnny Chen60dde642010-07-30 22:33:14 +0000520
Caroline Tice0aa2e552011-01-14 00:29:16 +0000521 LeaveSession ();
Caroline Tice202f6b82011-01-17 21:55:19 +0000522
523 if (need_to_release_lock)
524 ReleasePythonLock ();
525
Johnny Chen60dde642010-07-30 22:33:14 +0000526 if (result)
527 result->AppendError ("empty command passed to python\n");
528 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000529}
530
531
532
533size_t
534ScriptInterpreterPython::InputReaderCallback
535(
536 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000537 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000538 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000539 const char *bytes,
540 size_t bytes_len
541)
542{
Caroline Tice2ade6112010-11-10 19:18:14 +0000543 lldb::thread_t embedded_interpreter_thread;
544 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
545
Chris Lattner24943d22010-06-08 16:52:24 +0000546 if (baton == NULL)
547 return 0;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000548
549 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
550
551 if (script_interpreter->m_script_lang != eScriptLanguagePython)
552 return 0;
553
Caroline Tice67637d82010-12-15 19:51:12 +0000554 FILE *out_fh = reader.GetDebugger().GetOutputFileHandle ();
555 if (out_fh == NULL)
556 out_fh = stdout;
557
Chris Lattner24943d22010-06-08 16:52:24 +0000558 switch (notification)
559 {
560 case eInputReaderActivate:
561 {
Caroline Tice67637d82010-12-15 19:51:12 +0000562 if (out_fh)
563 {
Caroline Ticea81c3672011-02-03 20:08:40 +0000564 ::fprintf (out_fh, "Python Interactive Interpreter. To exit, type 'quit()', 'exit()' or Ctrl-D.\n");
Caroline Tice67637d82010-12-15 19:51:12 +0000565 }
Chris Lattner24943d22010-06-08 16:52:24 +0000566 // Save terminal settings if we can
Caroline Ticec95c6d12010-09-14 22:49:06 +0000567 int input_fd;
Greg Clayton63094e02010-06-23 01:19:29 +0000568 FILE *input_fh = reader.GetDebugger().GetInputFileHandle();
Caroline Ticec95c6d12010-09-14 22:49:06 +0000569 if (input_fh != NULL)
Greg Clayton24b48ff2010-10-17 22:03:32 +0000570 input_fd = ::fileno (input_fh);
Caroline Ticec95c6d12010-09-14 22:49:06 +0000571 else
Greg Clayton24b48ff2010-10-17 22:03:32 +0000572 input_fd = STDIN_FILENO;
Caroline Ticec95c6d12010-09-14 22:49:06 +0000573
Greg Clayton99208582011-02-07 19:04:58 +0000574#if LLDB_CONFIG_TERMIOS_SUPPORTED
Greg Clayton63094e02010-06-23 01:19:29 +0000575 script_interpreter->m_termios_valid = ::tcgetattr (input_fd, &script_interpreter->m_termios) == 0;
Greg Clayton99208582011-02-07 19:04:58 +0000576#endif // #if LLDB_CONFIG_TERMIOS_SUPPORTED
577
Caroline Tice202f6b82011-01-17 21:55:19 +0000578 if (!CurrentThreadHasPythonLock())
579 {
580 while (!GetPythonLock(1))
581 {
582 ::fprintf (out_fh, "Python interpreter locked on another thread; waiting to acquire lock...\n");
583 }
584 script_interpreter->EnterSession ();
585 ReleasePythonLock();
586 }
587 else
588 script_interpreter->EnterSession ();
589
Caroline Tice2ade6112010-11-10 19:18:14 +0000590 char error_str[1024];
591 if (script_interpreter->m_embedded_python_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, error_str,
592 sizeof(error_str)))
593 {
594 if (log)
595 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in opening master pty (fd = %d).",
596 script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor());
597 embedded_interpreter_thread = Host::ThreadCreate ("<lldb.script-interpreter.embedded-python-loop>",
598 ScriptInterpreterPython::RunEmbeddedPythonInterpreter,
599 script_interpreter, NULL);
600 if (embedded_interpreter_thread != LLDB_INVALID_HOST_THREAD)
601 {
602 if (log)
603 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in creating thread (thread = %d)", embedded_interpreter_thread);
604 Error detach_error;
605 Host::ThreadDetach (embedded_interpreter_thread, &detach_error);
606 }
607 else
608 {
609 if (log)
610 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed in creating thread");
611 reader.SetIsDone (true);
612 }
613 }
614 else
615 {
616 if (log)
617 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed to open master pty ");
618 reader.SetIsDone (true);
619 }
Chris Lattner24943d22010-06-08 16:52:24 +0000620 }
621 break;
622
623 case eInputReaderDeactivate:
Caroline Tice0aa2e552011-01-14 00:29:16 +0000624 script_interpreter->LeaveSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000625 break;
626
627 case eInputReaderReactivate:
Caroline Tice202f6b82011-01-17 21:55:19 +0000628 if (!CurrentThreadHasPythonLock())
629 {
630 while (!GetPythonLock(1))
631 {
632 // Wait until lock is acquired.
633 }
634 script_interpreter->EnterSession ();
635 ReleasePythonLock();
636 }
637 else
638 script_interpreter->EnterSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000639 break;
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000640
641 case eInputReaderInterrupt:
642 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "raise KeyboardInterrupt\n", 24);
643 break;
644
645 case eInputReaderEndOfFile:
646 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()\n", 7);
647 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000648
649 case eInputReaderGotToken:
Caroline Tice2ade6112010-11-10 19:18:14 +0000650 if (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor() != -1)
Chris Lattner24943d22010-06-08 16:52:24 +0000651 {
Caroline Tice2ade6112010-11-10 19:18:14 +0000652 if (log)
653 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %d", bytes,
654 bytes_len);
655 if (bytes && bytes_len)
656 {
657 if ((int) bytes[0] == 4)
658 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()", 6);
659 else
660 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), bytes, bytes_len);
661 }
662 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "\n", 1);
Chris Lattner24943d22010-06-08 16:52:24 +0000663 }
Caroline Tice2ade6112010-11-10 19:18:14 +0000664 else
665 {
666 if (log)
667 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %d, Master File Descriptor is bad.",
668 bytes,
669 bytes_len);
670 reader.SetIsDone (true);
671 }
672
Chris Lattner24943d22010-06-08 16:52:24 +0000673 break;
674
675 case eInputReaderDone:
Caroline Tice0aa2e552011-01-14 00:29:16 +0000676 script_interpreter->LeaveSession ();
677
Chris Lattner24943d22010-06-08 16:52:24 +0000678 // Restore terminal settings if they were validly saved
Caroline Tice2ade6112010-11-10 19:18:14 +0000679 if (log)
680 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Done, closing down input reader.");
Greg Clayton99208582011-02-07 19:04:58 +0000681#if LLDB_CONFIG_TERMIOS_SUPPORTED
Greg Clayton63094e02010-06-23 01:19:29 +0000682 if (script_interpreter->m_termios_valid)
Chris Lattner24943d22010-06-08 16:52:24 +0000683 {
Caroline Ticec95c6d12010-09-14 22:49:06 +0000684 int input_fd;
685 FILE *input_fh = reader.GetDebugger().GetInputFileHandle();
686 if (input_fh != NULL)
Greg Clayton24b48ff2010-10-17 22:03:32 +0000687 input_fd = ::fileno (input_fh);
Caroline Ticec95c6d12010-09-14 22:49:06 +0000688 else
Greg Clayton24b48ff2010-10-17 22:03:32 +0000689 input_fd = STDIN_FILENO;
Caroline Ticec95c6d12010-09-14 22:49:06 +0000690
691 ::tcsetattr (input_fd, TCSANOW, &script_interpreter->m_termios);
Chris Lattner24943d22010-06-08 16:52:24 +0000692 }
Greg Clayton99208582011-02-07 19:04:58 +0000693#endif // #if LLDB_CONFIG_TERMIOS_SUPPORTED
Caroline Tice2ade6112010-11-10 19:18:14 +0000694 script_interpreter->m_embedded_python_pty.CloseMasterFileDescriptor();
Chris Lattner24943d22010-06-08 16:52:24 +0000695 break;
696 }
697
698 return bytes_len;
699}
700
701
702void
Greg Clayton238c0a12010-09-18 01:14:36 +0000703ScriptInterpreterPython::ExecuteInterpreterLoop ()
Chris Lattner24943d22010-06-08 16:52:24 +0000704{
705 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
706
Caroline Tice0aa2e552011-01-14 00:29:16 +0000707 Debugger &debugger = GetCommandInterpreter().GetDebugger();
Caroline Ticec95c6d12010-09-14 22:49:06 +0000708
709 // At the moment, the only time the debugger does not have an input file handle is when this is called
710 // directly from Python, in which case it is both dangerous and unnecessary (not to mention confusing) to
711 // try to embed a running interpreter loop inside the already running Python interpreter loop, so we won't
712 // do it.
713
714 if (debugger.GetInputFileHandle() == NULL)
715 return;
716
Greg Clayton63094e02010-06-23 01:19:29 +0000717 InputReaderSP reader_sp (new InputReader(debugger));
Chris Lattner24943d22010-06-08 16:52:24 +0000718 if (reader_sp)
719 {
720 Error error (reader_sp->Initialize (ScriptInterpreterPython::InputReaderCallback,
721 this, // baton
722 eInputReaderGranularityLine, // token size, to pass to callback function
723 NULL, // end token
724 NULL, // prompt
725 true)); // echo input
726
727 if (error.Success())
728 {
Greg Clayton63094e02010-06-23 01:19:29 +0000729 debugger.PushInputReader (reader_sp);
Caroline Tice2ade6112010-11-10 19:18:14 +0000730 m_embedded_thread_input_reader_sp = reader_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000731 }
732 }
733}
734
735bool
736ScriptInterpreterPython::ExecuteOneLineWithReturn (const char *in_string,
737 ScriptInterpreter::ReturnType return_type,
738 void *ret_value)
739{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000740
Caroline Tice202f6b82011-01-17 21:55:19 +0000741 bool need_to_release_lock = true;
742
743 if (CurrentThreadHasPythonLock())
744 need_to_release_lock = false;
745 else if (!GetPythonLock (1))
746 {
747 fprintf ((m_dbg_stdout ? m_dbg_stdout : stdout),
748 "Python interpreter is currently locked by another thread; unable to process command.\n");
749 return false;
750 }
751
752 EnterSession ();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000753
Chris Lattner24943d22010-06-08 16:52:24 +0000754 PyObject *py_return = NULL;
755 PyObject *mainmod = PyImport_AddModule ("__main__");
756 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000757 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000758 PyObject *py_error = NULL;
759 bool ret_success;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000760 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000761 int success;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000762
763 if (PyDict_Check (globals))
764 {
765 PyObject *key, *value;
766 Py_ssize_t pos = 0;
767
768 int i = 0;
769 while (PyDict_Next (globals, &pos, &key, &value))
770 {
771 // We have stolen references to the key and value objects in the dictionary; we need to increment them now
772 // so that Python's garbage collector doesn't collect them out from under us.
773 Py_INCREF (key);
774 Py_INCREF (value);
775 char *c_str = PyString_AsString (key);
776 if (strcmp (c_str, m_dictionary_name.c_str()) == 0)
777 locals = value;
778 ++i;
779 }
780 }
Chris Lattner24943d22010-06-08 16:52:24 +0000781
Caroline Tice0aa2e552011-01-14 00:29:16 +0000782 if (locals == NULL)
783 {
784 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
785 should_decrement_locals = true;
786 }
787
788 if (locals == NULL)
789 {
790 locals = globals;
791 should_decrement_locals = false;
792 }
793
794 py_error = PyErr_Occurred();
795 if (py_error != NULL)
796 PyErr_Clear();
797
Chris Lattner24943d22010-06-08 16:52:24 +0000798 if (in_string != NULL)
799 {
800 py_return = PyRun_String (in_string, Py_eval_input, globals, locals);
801 if (py_return == NULL)
802 {
803 py_error = PyErr_Occurred ();
804 if (py_error != NULL)
805 PyErr_Clear ();
806
807 py_return = PyRun_String (in_string, Py_single_input, globals, locals);
808 }
809
Caroline Tice0aa2e552011-01-14 00:29:16 +0000810 if (locals != NULL
811 && should_decrement_locals)
812 Py_DECREF (locals);
813
Chris Lattner24943d22010-06-08 16:52:24 +0000814 if (py_return != NULL)
815 {
816 switch (return_type)
817 {
818 case eCharPtr: // "char *"
819 {
820 const char format[3] = "s#";
821 success = PyArg_Parse (py_return, format, (char **) &ret_value);
822 break;
823 }
824 case eBool:
825 {
826 const char format[2] = "b";
827 success = PyArg_Parse (py_return, format, (bool *) ret_value);
828 break;
829 }
830 case eShortInt:
831 {
832 const char format[2] = "h";
833 success = PyArg_Parse (py_return, format, (short *) ret_value);
834 break;
835 }
836 case eShortIntUnsigned:
837 {
838 const char format[2] = "H";
839 success = PyArg_Parse (py_return, format, (unsigned short *) ret_value);
840 break;
841 }
842 case eInt:
843 {
844 const char format[2] = "i";
845 success = PyArg_Parse (py_return, format, (int *) ret_value);
846 break;
847 }
848 case eIntUnsigned:
849 {
850 const char format[2] = "I";
851 success = PyArg_Parse (py_return, format, (unsigned int *) ret_value);
852 break;
853 }
854 case eLongInt:
855 {
856 const char format[2] = "l";
857 success = PyArg_Parse (py_return, format, (long *) ret_value);
858 break;
859 }
860 case eLongIntUnsigned:
861 {
862 const char format[2] = "k";
863 success = PyArg_Parse (py_return, format, (unsigned long *) ret_value);
864 break;
865 }
866 case eLongLong:
867 {
868 const char format[2] = "L";
869 success = PyArg_Parse (py_return, format, (long long *) ret_value);
870 break;
871 }
872 case eLongLongUnsigned:
873 {
874 const char format[2] = "K";
875 success = PyArg_Parse (py_return, format, (unsigned long long *) ret_value);
876 break;
877 }
878 case eFloat:
879 {
880 const char format[2] = "f";
881 success = PyArg_Parse (py_return, format, (float *) ret_value);
882 break;
883 }
884 case eDouble:
885 {
886 const char format[2] = "d";
887 success = PyArg_Parse (py_return, format, (double *) ret_value);
888 break;
889 }
890 case eChar:
891 {
892 const char format[2] = "c";
893 success = PyArg_Parse (py_return, format, (char *) ret_value);
894 break;
895 }
896 default:
897 {}
898 }
899 Py_DECREF (py_return);
900 if (success)
901 ret_success = true;
902 else
903 ret_success = false;
904 }
905 }
906
907 py_error = PyErr_Occurred();
908 if (py_error != NULL)
909 {
910 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
911 PyErr_Print ();
912 PyErr_Clear();
913 ret_success = false;
914 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000915
916 LeaveSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000917
Caroline Tice202f6b82011-01-17 21:55:19 +0000918 if (need_to_release_lock)
919 ReleasePythonLock();
920
Chris Lattner24943d22010-06-08 16:52:24 +0000921 return ret_success;
922}
923
924bool
925ScriptInterpreterPython::ExecuteMultipleLines (const char *in_string)
926{
Caroline Tice202f6b82011-01-17 21:55:19 +0000927 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
928 bool need_to_release_lock = true;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000929
Caroline Tice202f6b82011-01-17 21:55:19 +0000930 if (CurrentThreadHasPythonLock())
931 need_to_release_lock = false;
932 else
933 {
934 while (!GetPythonLock (1))
935 fprintf (tmp_fh, "Python interpreter locked on another thread; waiting to acquire lock...\n");
936 }
937
938 EnterSession ();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000939
Chris Lattner24943d22010-06-08 16:52:24 +0000940 bool success = false;
941 PyObject *py_return = NULL;
942 PyObject *mainmod = PyImport_AddModule ("__main__");
943 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000944 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000945 PyObject *py_error = NULL;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000946 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000947
Caroline Tice0aa2e552011-01-14 00:29:16 +0000948 if (PyDict_Check (globals))
949 {
950 PyObject *key, *value;
951 Py_ssize_t pos = 0;
952
953 while (PyDict_Next (globals, &pos, &key, &value))
954 {
955 // We have stolen references to the key and value objects in the dictionary; we need to increment them now
956 // so that Python's garbage collector doesn't collect them out from under us.
957 Py_INCREF (key);
958 Py_INCREF (value);
959 if (strcmp (PyString_AsString (key), m_dictionary_name.c_str()) == 0)
960 locals = value;
961 }
962 }
963
964 if (locals == NULL)
965 {
966 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
967 should_decrement_locals = true;
968 }
969
970 if (locals == NULL)
971 {
972 locals = globals;
973 should_decrement_locals = false;
974 }
975
976 py_error = PyErr_Occurred();
977 if (py_error != NULL)
978 PyErr_Clear();
979
Chris Lattner24943d22010-06-08 16:52:24 +0000980 if (in_string != NULL)
981 {
982 struct _node *compiled_node = PyParser_SimpleParseString (in_string, Py_file_input);
983 if (compiled_node)
984 {
985 PyCodeObject *compiled_code = PyNode_Compile (compiled_node, "temp.py");
986 if (compiled_code)
987 {
988 py_return = PyEval_EvalCode (compiled_code, globals, locals);
989 if (py_return != NULL)
990 {
991 success = true;
992 Py_DECREF (py_return);
993 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000994 if (locals && should_decrement_locals)
995 Py_DECREF (locals);
Chris Lattner24943d22010-06-08 16:52:24 +0000996 }
997 }
998 }
999
1000 py_error = PyErr_Occurred ();
1001 if (py_error != NULL)
1002 {
1003 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
1004 PyErr_Print ();
1005 PyErr_Clear();
1006 success = false;
1007 }
1008
Caroline Tice0aa2e552011-01-14 00:29:16 +00001009 LeaveSession ();
1010
Caroline Tice202f6b82011-01-17 21:55:19 +00001011 if (need_to_release_lock)
1012 ReleasePythonLock();
1013
Chris Lattner24943d22010-06-08 16:52:24 +00001014 return success;
1015}
1016
1017static const char *g_reader_instructions = "Enter your Python command(s). Type 'DONE' to end.";
1018
1019size_t
1020ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback
1021(
1022 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +00001023 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +00001024 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +00001025 const char *bytes,
1026 size_t bytes_len
1027)
1028{
1029 static StringList commands_in_progress;
1030
Greg Clayton63094e02010-06-23 01:19:29 +00001031 FILE *out_fh = reader.GetDebugger().GetOutputFileHandle();
Caroline Ticec95c6d12010-09-14 22:49:06 +00001032 if (out_fh == NULL)
1033 out_fh = stdout;
1034
Chris Lattner24943d22010-06-08 16:52:24 +00001035 switch (notification)
1036 {
1037 case eInputReaderActivate:
1038 {
1039 commands_in_progress.Clear();
1040 if (out_fh)
1041 {
1042 ::fprintf (out_fh, "%s\n", g_reader_instructions);
Greg Clayton63094e02010-06-23 01:19:29 +00001043 if (reader.GetPrompt())
1044 ::fprintf (out_fh, "%s", reader.GetPrompt());
Caroline Ticef81b4c52010-10-27 18:34:42 +00001045 ::fflush (out_fh);
Chris Lattner24943d22010-06-08 16:52:24 +00001046 }
1047 }
1048 break;
1049
1050 case eInputReaderDeactivate:
1051 break;
1052
1053 case eInputReaderReactivate:
Greg Clayton63094e02010-06-23 01:19:29 +00001054 if (reader.GetPrompt() && out_fh)
Caroline Ticef81b4c52010-10-27 18:34:42 +00001055 {
Greg Clayton63094e02010-06-23 01:19:29 +00001056 ::fprintf (out_fh, "%s", reader.GetPrompt());
Caroline Ticef81b4c52010-10-27 18:34:42 +00001057 ::fflush (out_fh);
1058 }
Chris Lattner24943d22010-06-08 16:52:24 +00001059 break;
1060
1061 case eInputReaderGotToken:
1062 {
1063 std::string temp_string (bytes, bytes_len);
1064 commands_in_progress.AppendString (temp_string.c_str());
Greg Clayton63094e02010-06-23 01:19:29 +00001065 if (out_fh && !reader.IsDone() && reader.GetPrompt())
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 }
1071 break;
1072
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001073 case eInputReaderEndOfFile:
1074 case eInputReaderInterrupt:
1075 // Control-c (SIGINT) & control-d both mean finish & exit.
1076 reader.SetIsDone(true);
1077
1078 // Control-c (SIGINT) ALSO means cancel; do NOT create a breakpoint command.
1079 if (notification == eInputReaderInterrupt)
1080 commands_in_progress.Clear();
1081
1082 // Fall through here...
1083
Chris Lattner24943d22010-06-08 16:52:24 +00001084 case eInputReaderDone:
1085 {
1086 BreakpointOptions *bp_options = (BreakpointOptions *)baton;
1087 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1088 data_ap->user_source.AppendList (commands_in_progress);
1089 if (data_ap.get())
1090 {
Greg Clayton63094e02010-06-23 01:19:29 +00001091 ScriptInterpreter *interpreter = reader.GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
Chris Lattner24943d22010-06-08 16:52:24 +00001092 if (interpreter)
1093 {
1094 if (interpreter->GenerateBreakpointCommandCallbackData (data_ap->user_source,
1095 data_ap->script_source))
1096 {
1097 if (data_ap->script_source.GetSize() == 1)
1098 {
1099 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1100 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
1101 }
1102 }
Caroline Ticeb447e842010-09-21 19:25:28 +00001103 else
Caroline Tice5136f942010-09-27 21:35:15 +00001104 ::fprintf (out_fh, "Warning: No command attached to breakpoint.\n");
Chris Lattner24943d22010-06-08 16:52:24 +00001105 }
1106 else
1107 {
1108 // FIXME: Error processing.
1109 }
1110 }
1111 }
1112 break;
1113
1114 }
1115
1116 return bytes_len;
1117}
1118
1119void
Greg Clayton238c0a12010-09-18 01:14:36 +00001120ScriptInterpreterPython::CollectDataForBreakpointCommandCallback (BreakpointOptions *bp_options,
Chris Lattner24943d22010-06-08 16:52:24 +00001121 CommandReturnObject &result)
1122{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001123 Debugger &debugger = GetCommandInterpreter().GetDebugger();
1124
Greg Clayton63094e02010-06-23 01:19:29 +00001125 InputReaderSP reader_sp (new InputReader (debugger));
Chris Lattner24943d22010-06-08 16:52:24 +00001126
1127 if (reader_sp)
1128 {
1129 Error err = reader_sp->Initialize (
1130 ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback,
1131 bp_options, // baton
1132 eInputReaderGranularityLine, // token size, for feeding data to callback function
1133 "DONE", // end token
1134 "> ", // prompt
1135 true); // echo input
1136
1137 if (err.Success())
Greg Clayton63094e02010-06-23 01:19:29 +00001138 debugger.PushInputReader (reader_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001139 else
1140 {
1141 result.AppendError (err.AsCString());
1142 result.SetStatus (eReturnStatusFailed);
1143 }
1144 }
1145 else
1146 {
1147 result.AppendError("out of memory");
1148 result.SetStatus (eReturnStatusFailed);
1149 }
1150}
1151
Johnny Chen3e0571b2010-09-11 00:23:59 +00001152// Set a Python one-liner as the callback for the breakpoint.
Johnny Chend1c2dca2010-09-10 18:21:10 +00001153void
Greg Clayton238c0a12010-09-18 01:14:36 +00001154ScriptInterpreterPython::SetBreakpointCommandCallback (BreakpointOptions *bp_options,
Johnny Chend1c2dca2010-09-10 18:21:10 +00001155 const char *oneliner)
1156{
1157 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1158
1159 // It's necessary to set both user_source and script_source to the oneliner.
1160 // The former is used to generate callback description (as in breakpoint command list)
1161 // while the latter is used for Python to interpret during the actual callback.
Caroline Tice5136f942010-09-27 21:35:15 +00001162
Johnny Chend1c2dca2010-09-10 18:21:10 +00001163 data_ap->user_source.AppendString (oneliner);
Johnny Chend1c2dca2010-09-10 18:21:10 +00001164
Caroline Tice5136f942010-09-27 21:35:15 +00001165 if (GenerateBreakpointCommandCallbackData (data_ap->user_source, data_ap->script_source))
1166 {
1167 if (data_ap->script_source.GetSize() == 1)
1168 {
1169 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1170 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
1171 }
1172 }
1173
Johnny Chend1c2dca2010-09-10 18:21:10 +00001174 return;
1175}
1176
Chris Lattner24943d22010-06-08 16:52:24 +00001177bool
1178ScriptInterpreterPython::ExportFunctionDefinitionToInterpreter (StringList &function_def)
1179{
1180 // Convert StringList to one long, newline delimited, const char *.
1181 std::string function_def_string;
1182
1183 int num_lines = function_def.GetSize();
1184
1185 for (int i = 0; i < num_lines; ++i)
1186 {
1187 function_def_string.append (function_def.GetStringAtIndex(i));
1188 if (function_def_string.at (function_def_string.length() - 1) != '\n')
1189 function_def_string.append ("\n");
1190
1191 }
1192
1193 return ExecuteMultipleLines (function_def_string.c_str());
1194}
1195
1196bool
1197ScriptInterpreterPython::GenerateBreakpointCommandCallbackData (StringList &user_input, StringList &callback_data)
1198{
1199 static int num_created_functions = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001200 user_input.RemoveBlankLines ();
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001201 int num_lines = user_input.GetSize ();
1202 StreamString sstr;
Chris Lattner24943d22010-06-08 16:52:24 +00001203
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001204 // Check to see if we have any data; if not, just return.
1205 if (user_input.GetSize() == 0)
1206 return false;
1207
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001208 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1209 // frame and breakpoint location as parameters to the function.
Caroline Ticeb447e842010-09-21 19:25:28 +00001210
Caroline Ticeb447e842010-09-21 19:25:28 +00001211
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001212 sstr.Printf ("lldb_autogen_python_bp_callback_func_%d", num_created_functions);
1213 ++num_created_functions;
1214 std::string auto_generated_function_name = sstr.GetData();
Caroline Ticeb447e842010-09-21 19:25:28 +00001215
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001216 sstr.Clear();
Caroline Ticeb447e842010-09-21 19:25:28 +00001217 StringList auto_generated_function;
Caroline Ticeb447e842010-09-21 19:25:28 +00001218
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001219 // Create the function name & definition string.
1220
Caroline Tice0aa2e552011-01-14 00:29:16 +00001221 sstr.Printf ("def %s (frame, bp_loc, dict):", auto_generated_function_name.c_str());
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001222 auto_generated_function.AppendString (sstr.GetData());
Caroline Tice0aa2e552011-01-14 00:29:16 +00001223
1224 // Pre-pend code for setting up the session dictionary.
1225
1226 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1227 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1228 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1229 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1230 // global dictionary.
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001231
1232 // Wrap everything up inside the function, increasing the indentation.
Chris Lattner24943d22010-06-08 16:52:24 +00001233
1234 for (int i = 0; i < num_lines; ++i)
1235 {
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001236 sstr.Clear ();
1237 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1238 auto_generated_function.AppendString (sstr.GetData());
Caroline Ticeb447e842010-09-21 19:25:28 +00001239 }
Chris Lattner24943d22010-06-08 16:52:24 +00001240
Caroline Tice0aa2e552011-01-14 00:29:16 +00001241 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1242 // got written to the values in the global dictionary, not the session dictionary).
1243
1244 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1245 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1246 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1247 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1248
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001249 // Verify that the results are valid Python.
Chris Lattner24943d22010-06-08 16:52:24 +00001250
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001251 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
Caroline Ticeb447e842010-09-21 19:25:28 +00001252 {
Caroline Ticeb447e842010-09-21 19:25:28 +00001253 return false;
Chris Lattner24943d22010-06-08 16:52:24 +00001254 }
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001255
1256 // Store the name of the auto-generated function to be called.
1257
1258 callback_data.AppendString (auto_generated_function_name.c_str());
1259 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001260}
1261
Greg Clayton5144f382010-10-07 17:14:24 +00001262bool
1263ScriptInterpreterPython::BreakpointCallbackFunction
1264(
1265 void *baton,
1266 StoppointCallbackContext *context,
1267 user_id_t break_id,
1268 user_id_t break_loc_id
1269)
1270{
1271 BreakpointOptions::CommandData *bp_option_data = (BreakpointOptions::CommandData *) baton;
1272 const char *python_function_name = bp_option_data->script_source.GetStringAtIndex (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001273
1274 if (!context)
1275 return true;
1276
1277 Target *target = context->exe_ctx.target;
1278
1279 if (!target)
1280 return true;
1281
1282 Debugger &debugger = target->GetDebugger();
1283 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1284 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1285
1286 if (!script_interpreter)
1287 return true;
Greg Clayton5144f382010-10-07 17:14:24 +00001288
1289 if (python_function_name != NULL
1290 && python_function_name[0] != '\0')
1291 {
1292 Thread *thread = context->exe_ctx.thread;
Greg Clayton5144f382010-10-07 17:14:24 +00001293 const StackFrameSP stop_frame_sp = thread->GetStackFrameSPForStackFramePtr (context->exe_ctx.frame);
1294 BreakpointSP breakpoint_sp = target->GetBreakpointByID (break_id);
1295 const BreakpointLocationSP bp_loc_sp = breakpoint_sp->FindLocationByID (break_loc_id);
1296
1297 SBFrame sb_frame (stop_frame_sp);
1298 SBBreakpointLocation sb_bp_loc (bp_loc_sp);
1299
1300 if (sb_bp_loc.IsValid() || sb_frame.IsValid())
Caroline Tice0aa2e552011-01-14 00:29:16 +00001301 {
Caroline Tice202f6b82011-01-17 21:55:19 +00001302 bool ret_val = true;
1303 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
1304 if (CurrentThreadHasPythonLock())
1305 {
1306 python_interpreter->EnterSession ();
1307 ret_val = LLDBSWIGPythonBreakpointCallbackFunction(python_function_name,
1308 python_interpreter->m_dictionary_name.c_str(),
1309 sb_frame, sb_bp_loc);
1310 python_interpreter->LeaveSession ();
1311 }
1312 else
1313 {
1314 while (!GetPythonLock (1))
1315 fprintf (tmp_fh,
1316 "Python interpreter locked on another thread; waiting to acquire lock...\n");
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 ReleasePythonLock ();
1323 }
Caroline Tice0aa2e552011-01-14 00:29:16 +00001324 return ret_val;
1325 }
Greg Clayton5144f382010-10-07 17:14:24 +00001326 }
1327 // We currently always true so we stop in case anything goes wrong when
1328 // trying to call the script function
1329 return true;
1330}
Caroline Tice2ade6112010-11-10 19:18:14 +00001331
1332lldb::thread_result_t
1333ScriptInterpreterPython::RunEmbeddedPythonInterpreter (lldb::thread_arg_t baton)
1334{
1335 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
1336
1337 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
1338
1339 if (log)
1340 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread starting...", baton);
1341
1342 char error_str[1024];
1343 const char *pty_slave_name = script_interpreter->m_embedded_python_pty.GetSlaveName (error_str, sizeof (error_str));
Caroline Tice202f6b82011-01-17 21:55:19 +00001344 bool need_to_release_lock = true;
1345 bool safe_to_run = false;
Caroline Tice0aa2e552011-01-14 00:29:16 +00001346
Caroline Tice202f6b82011-01-17 21:55:19 +00001347 if (CurrentThreadHasPythonLock())
1348 {
1349 safe_to_run = true;
1350 need_to_release_lock = false;
1351 }
1352 else
1353 {
1354 int interval = 1;
1355 safe_to_run = GetPythonLock (interval);
1356 while (!safe_to_run)
1357 {
1358 interval = interval * 2;
1359 safe_to_run = GetPythonLock (interval);
1360 }
1361 }
1362
1363 if (pty_slave_name != NULL && safe_to_run)
1364 {
Caroline Tice2ade6112010-11-10 19:18:14 +00001365 StreamString run_string;
Caroline Tice2ade6112010-11-10 19:18:14 +00001366
Caroline Tice202f6b82011-01-17 21:55:19 +00001367 script_interpreter->EnterSession ();
1368
Caroline Tice0aa2e552011-01-14 00:29:16 +00001369 run_string.Printf ("run_one_line (%s, 'save_stderr = sys.stderr')", script_interpreter->m_dictionary_name.c_str());
1370 PyRun_SimpleString (run_string.GetData());
1371 run_string.Clear ();
1372
1373 run_string.Printf ("run_one_line (%s, 'sys.stderr = sys.stdout')", script_interpreter->m_dictionary_name.c_str());
1374 PyRun_SimpleString (run_string.GetData());
1375 run_string.Clear ();
1376
1377 run_string.Printf ("run_one_line (%s, 'save_stdin = sys.stdin')", script_interpreter->m_dictionary_name.c_str());
1378 PyRun_SimpleString (run_string.GetData());
1379 run_string.Clear ();
1380
1381 run_string.Printf ("run_one_line (%s, \"sys.stdin = open ('%s', 'r')\")", script_interpreter->m_dictionary_name.c_str(),
1382 pty_slave_name);
1383 PyRun_SimpleString (run_string.GetData());
1384 run_string.Clear ();
1385
Caroline Tice2ade6112010-11-10 19:18:14 +00001386 // The following call drops into the embedded interpreter loop and stays there until the
1387 // user chooses to exit from the Python interpreter.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001388
1389 run_string.Printf ("run_python_interpreter (%s)", script_interpreter->m_dictionary_name.c_str());
1390 PyRun_SimpleString (run_string.GetData());
1391 run_string.Clear ();
Caroline Tice2ade6112010-11-10 19:18:14 +00001392
Caroline Tice0aa2e552011-01-14 00:29:16 +00001393 run_string.Printf ("run_one_line (%s, 'sys.stdin = save_stdin')", script_interpreter->m_dictionary_name.c_str());
1394 PyRun_SimpleString (run_string.GetData());
1395 run_string.Clear();
1396
1397 run_string.Printf ("run_one_line (%s, 'sys.stderr = save_stderr')", script_interpreter->m_dictionary_name.c_str());
1398 PyRun_SimpleString (run_string.GetData());
1399 run_string.Clear();
Caroline Tice202f6b82011-01-17 21:55:19 +00001400
1401 script_interpreter->LeaveSession ();
1402
Caroline Tice2ade6112010-11-10 19:18:14 +00001403 }
1404
Caroline Tice202f6b82011-01-17 21:55:19 +00001405 if (!safe_to_run)
1406 fprintf ((script_interpreter->m_dbg_stdout ? script_interpreter->m_dbg_stdout : stdout),
1407 "Python interpreter locked on another thread; unable to acquire lock.\n");
1408
1409 if (need_to_release_lock)
1410 ReleasePythonLock ();
1411
Caroline Tice2ade6112010-11-10 19:18:14 +00001412 if (script_interpreter->m_embedded_thread_input_reader_sp)
1413 script_interpreter->m_embedded_thread_input_reader_sp->SetIsDone (true);
1414
1415 script_interpreter->m_embedded_python_pty.CloseSlaveFileDescriptor();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001416
1417 script_interpreter->m_pty_slave_is_open = false;
Caroline Tice2ade6112010-11-10 19:18:14 +00001418
1419 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT);
1420 if (log)
1421 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread exiting...", baton);
1422
1423
Caroline Tice0aa2e552011-01-14 00:29:16 +00001424 // Clean up the input reader and make the debugger pop it off the stack.
1425 Debugger &debugger = script_interpreter->GetCommandInterpreter().GetDebugger();
Caroline Tice2ade6112010-11-10 19:18:14 +00001426 const InputReaderSP reader_sp = script_interpreter->m_embedded_thread_input_reader_sp;
1427 script_interpreter->m_embedded_thread_input_reader_sp.reset();
1428 debugger.PopInputReader (reader_sp);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001429
Caroline Tice2ade6112010-11-10 19:18:14 +00001430 return NULL;
1431}
1432
1433
Caroline Tice0aa2e552011-01-14 00:29:16 +00001434void
1435ScriptInterpreterPython::Initialize ()
1436{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001437 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
1438
Greg Clayton99208582011-02-07 19:04:58 +00001439#if LLDB_CONFIG_TERMIOS_SUPPORTED
Greg Clayton9a7a9472011-02-07 19:22:32 +00001440 int input_fd = STDIN_FILENO;
Caroline Tice0aa2e552011-01-14 00:29:16 +00001441 struct termios stdin_termios;
1442 bool valid_termios = ::tcgetattr (input_fd, &stdin_termios) == 0;
Greg Clayton99208582011-02-07 19:04:58 +00001443#endif // #if LLDB_CONFIG_TERMIOS_SUPPORTED
Caroline Tice0aa2e552011-01-14 00:29:16 +00001444
1445 // Find the module that owns this code and use that path we get to
1446 // set the PYTHONPATH appropriately.
1447
1448 FileSpec file_spec;
1449 char python_dir_path[PATH_MAX];
1450 if (Host::GetLLDBPath (ePathTypePythonDir, file_spec))
1451 {
1452 std::string python_path;
1453 const char *curr_python_path = ::getenv ("PYTHONPATH");
1454 if (curr_python_path)
1455 {
1456 // We have a current value for PYTHONPATH, so lets append to it
1457 python_path.append (curr_python_path);
1458 }
1459
1460 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
1461 {
1462 if (!python_path.empty())
1463 python_path.append (1, ':');
1464 python_path.append (python_dir_path);
1465 }
1466
1467 if (Host::GetLLDBPath (ePathTypeLLDBShlibDir, file_spec))
1468 {
1469 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
1470 {
1471 if (!python_path.empty())
1472 python_path.append (1, ':');
1473 python_path.append (python_dir_path);
1474 }
1475 }
1476 const char *pathon_path_env_cstr = python_path.c_str();
1477 ::setenv ("PYTHONPATH", pathon_path_env_cstr, 1);
1478 }
1479
1480 Py_Initialize ();
1481
1482 PyObject *compiled_module = Py_CompileString (embedded_interpreter_string,
1483 "embedded_interpreter.py",
1484 Py_file_input);
1485
1486 PyObject *py_error = PyErr_Occurred ();
1487 if (py_error != NULL)
1488 {
1489 PyErr_Print();
1490 PyErr_Clear();
1491 }
1492
1493
1494 // This function is in the C++ output file generated by SWIG after it is
1495 // run on all of the headers in "lldb/API/SB*.h"
1496 init_lldb ();
1497
1498 // Update the path python uses to search for modules to include the current directory.
1499
1500 int success = PyRun_SimpleString ("import sys");
1501 success = PyRun_SimpleString ("sys.path.append ('.')");
1502
1503 PyObject *pmod = NULL;
1504
1505 if (compiled_module)
1506 {
1507 pmod = PyImport_ExecCodeModule (const_cast<char*> ("embedded_interpreter"),
1508 compiled_module);
1509 Py_DECREF (compiled_module);
1510 }
1511
1512 if (pmod != NULL)
1513 {
1514 PyRun_SimpleString ("from embedded_interpreter import run_python_interpreter");
1515 PyRun_SimpleString ("from embedded_interpreter import run_one_line");
1516 PyRun_SimpleString ("import sys");
1517 PyRun_SimpleString ("from termios import *");
1518 Py_DECREF (pmod);
1519 }
Greg Clayton99208582011-02-07 19:04:58 +00001520
1521#if LLDB_CONFIG_TERMIOS_SUPPORTED
Caroline Tice0aa2e552011-01-14 00:29:16 +00001522 if (valid_termios)
1523 ::tcsetattr (input_fd, TCSANOW, &stdin_termios);
Greg Clayton99208582011-02-07 19:04:58 +00001524#endif // #if LLDB_CONFIG_TERMIOS_SUPPORTED
Caroline Tice0aa2e552011-01-14 00:29:16 +00001525}
1526
1527void
1528ScriptInterpreterPython::Terminate ()
1529{
1530 // We are intentionally NOT calling Py_Finalize here (this would be the logical place to call it). Calling
1531 // Py_Finalize here causes test suite runs to seg fault: The test suite runs in Python. It registers
1532 // SBDebugger::Terminate to be called 'at_exit'. When the test suite Python harness finishes up, it calls
1533 // Py_Finalize, which calls all the 'at_exit' registered functions. SBDebugger::Terminate calls Debugger::Terminate,
1534 // which calls lldb::Terminate, which calls ScriptInterpreter::Terminate, which calls
1535 // ScriptInterpreterPython::Terminate. So if we call Py_Finalize here, we end up with Py_Finalize being called from
1536 // within Py_Finalize, which results in a seg fault.
1537 //
1538 // Since this function only gets called when lldb is shutting down and going away anyway, the fact that we don't
1539 // actually call Py_Finalize should not cause any problems (everything should shut down/go away anyway when the
1540 // process exits).
1541 //
1542// Py_Finalize ();
1543}