blob: 88f42233789cc2c19d2ae6b708bff3a542ed9ec1 [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 Clayton0fdd4a02011-02-07 23:24:47 +0000204 m_terminal_state (),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000205 m_session_is_active (false),
206 m_pty_slave_is_open (false),
207 m_valid_session (true)
Chris Lattner24943d22010-06-08 16:52:24 +0000208{
209
Greg Clayton7c330d62011-01-27 01:01:10 +0000210 static int g_initialized = false;
211
212 if (!g_initialized)
213 {
214 g_initialized = true;
215 ScriptInterpreterPython::Initialize ();
216 }
217
Caroline Tice202f6b82011-01-17 21:55:19 +0000218 bool safe_to_run = false;
219 bool need_to_release_lock = true;
220 int interval = 5; // Number of seconds to try getting the Python lock before timing out.
221
222 // We don't dare exit this function without finishing setting up the script interpreter, so we must wait until
223 // we can get the Python lock.
224
225 if (CurrentThreadHasPythonLock())
226 {
227 safe_to_run = true;
228 need_to_release_lock = false;
229 }
230
231 while (!safe_to_run)
232 {
233 safe_to_run = GetPythonLock (interval);
234 if (!safe_to_run)
235 {
236 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
237 fprintf (tmp_fh,
238 "Python interpreter is locked on another thread; "
239 "please release interpreter in order to continue.\n");
240 interval = interval * 2;
241 }
242 }
243
Caroline Tice0aa2e552011-01-14 00:29:16 +0000244 m_dictionary_name.append("_dict");
245 StreamString run_string;
246 run_string.Printf ("%s = dict()", m_dictionary_name.c_str());
247 PyRun_SimpleString (run_string.GetData());
Caroline Tice5867f6b2010-10-18 18:24:17 +0000248
Caroline Tice0aa2e552011-01-14 00:29:16 +0000249 run_string.Clear();
250 run_string.Printf ("run_one_line (%s, 'import sys')", m_dictionary_name.c_str());
251 PyRun_SimpleString (run_string.GetData());
252
253 // Importing 'lldb' module calls SBDebugger::Initialize, which calls Debugger::Initialize, which increments a
254 // global debugger ref-count; therefore we need to check the ref-count before and after importing lldb, and if the
255 // ref-count increased we need to call Debugger::Terminate here to decrement the ref-count so that when the final
256 // call to Debugger::Terminate is made, the ref-count has the correct value.
257 //
258 // Bonus question: Why doesn't the ref-count always increase? Because sometimes lldb has already been imported, in
259 // which case the code inside it, including the call to SBDebugger::Initialize(), does not get executed.
Caroline Tice5867f6b2010-10-18 18:24:17 +0000260
Caroline Tice0aa2e552011-01-14 00:29:16 +0000261 int old_count = Debugger::TestDebuggerRefCount();
Chris Lattner24943d22010-06-08 16:52:24 +0000262
Caroline Tice0aa2e552011-01-14 00:29:16 +0000263 run_string.Clear();
264 run_string.Printf ("run_one_line (%s, 'import lldb')", m_dictionary_name.c_str());
265 PyRun_SimpleString (run_string.GetData());
Greg Clayton24b48ff2010-10-17 22:03:32 +0000266
Caroline Tice0aa2e552011-01-14 00:29:16 +0000267 int new_count = Debugger::TestDebuggerRefCount();
Chris Lattner24943d22010-06-08 16:52:24 +0000268
Caroline Tice0aa2e552011-01-14 00:29:16 +0000269 if (new_count > old_count)
270 Debugger::Terminate();
Caroline Tice5867f6b2010-10-18 18:24:17 +0000271
Caroline Tice0aa2e552011-01-14 00:29:16 +0000272 run_string.Clear();
273 run_string.Printf ("run_one_line (%s, 'import copy')", m_dictionary_name.c_str());
274 PyRun_SimpleString (run_string.GetData());
275
276 run_string.Clear();
277 run_string.Printf ("run_one_line (%s, 'lldb.debugger_unique_id = %d')", m_dictionary_name.c_str(),
278 interpreter.GetDebugger().GetID());
279 PyRun_SimpleString (run_string.GetData());
280
281 if (m_dbg_stdout != NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000282 {
Caroline Tice0aa2e552011-01-14 00:29:16 +0000283 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
Caroline Tice5867f6b2010-10-18 18:24:17 +0000284 }
Caroline Tice202f6b82011-01-17 21:55:19 +0000285
286 if (need_to_release_lock)
287 ReleasePythonLock();
Chris Lattner24943d22010-06-08 16:52:24 +0000288}
289
290ScriptInterpreterPython::~ScriptInterpreterPython ()
291{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000292 Debugger &debugger = GetCommandInterpreter().GetDebugger();
293
294 if (m_embedded_thread_input_reader_sp.get() != NULL)
295 {
296 m_embedded_thread_input_reader_sp->SetIsDone (true);
297 m_embedded_python_pty.CloseSlaveFileDescriptor();
298 m_pty_slave_is_open = false;
299 const InputReaderSP reader_sp = m_embedded_thread_input_reader_sp;
300 m_embedded_thread_input_reader_sp.reset();
301 debugger.PopInputReader (reader_sp);
302 }
303
304 if (m_new_sysout)
305 {
Caroline Tice202f6b82011-01-17 21:55:19 +0000306 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
307 if (!CurrentThreadHasPythonLock ())
308 {
309 while (!GetPythonLock (1))
310 fprintf (tmp_fh, "Python interpreter locked on another thread; waiting to acquire lock...\n");
311 Py_DECREF (m_new_sysout);
312 ReleasePythonLock ();
313 }
314 else
315 Py_DECREF (m_new_sysout);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000316 }
Chris Lattner24943d22010-06-08 16:52:24 +0000317}
318
Caroline Tice0aa2e552011-01-14 00:29:16 +0000319void
320ScriptInterpreterPython::ResetOutputFileHandle (FILE *fh)
321{
322 if (fh == NULL)
323 return;
324
325 m_dbg_stdout = fh;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000326
Caroline Tice202f6b82011-01-17 21:55:19 +0000327 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
328 if (!CurrentThreadHasPythonLock ())
329 {
330 while (!GetPythonLock (1))
331 fprintf (tmp_fh, "Python interpreter locked on another thread; waiting to acquire lock...\n");
332 EnterSession ();
333 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
334 LeaveSession ();
335 ReleasePythonLock ();
336 }
337 else
338 {
339 EnterSession ();
340 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
341 LeaveSession ();
342 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000343}
344
345void
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000346ScriptInterpreterPython::SaveTerminalState (int fd)
347{
348 // Python mucks with the terminal state of STDIN. If we can possibly avoid
349 // this by setting the file handles up correctly prior to entering the
350 // interpreter we should. For now we save and restore the terminal state
351 // on the input file handle.
352 m_terminal_state.Save (fd, false);
353}
354
355void
356ScriptInterpreterPython::RestoreTerminalState ()
357{
358 // Python mucks with the terminal state of STDIN. If we can possibly avoid
359 // this by setting the file handles up correctly prior to entering the
360 // interpreter we should. For now we save and restore the terminal state
361 // on the input file handle.
362 m_terminal_state.Restore();
363}
364
365
366
367void
Caroline Tice0aa2e552011-01-14 00:29:16 +0000368ScriptInterpreterPython::LeaveSession ()
369{
370 m_session_is_active = false;
371}
372
373void
374ScriptInterpreterPython::EnterSession ()
375{
376 // If we have already entered the session, without having officially 'left' it, then there is no need to
377 // 'enter' it again.
378
379 if (m_session_is_active)
380 return;
381
382 m_session_is_active = true;
383
Caroline Tice202f6b82011-01-17 21:55:19 +0000384 StreamString run_string;
385
386 run_string.Printf ("run_one_line (%s, 'lldb.debugger_unique_id = %d')", m_dictionary_name.c_str(),
387 GetCommandInterpreter().GetDebugger().GetID());
388 PyRun_SimpleString (run_string.GetData());
389
Caroline Tice0aa2e552011-01-14 00:29:16 +0000390
391 PyObject *sysmod = PyImport_AddModule ("sys");
392 PyObject *sysdict = PyModule_GetDict (sysmod);
393
394 if ((m_new_sysout != NULL)
395 && (sysmod != NULL)
396 && (sysdict != NULL))
397 PyDict_SetItemString (sysdict, "stdout", m_new_sysout);
398
399 if (PyErr_Occurred())
400 PyErr_Clear ();
401
Caroline Tice0aa2e552011-01-14 00:29:16 +0000402 if (!m_pty_slave_is_open)
403 {
Caroline Tice202f6b82011-01-17 21:55:19 +0000404 run_string.Clear();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000405 run_string.Printf ("run_one_line (%s, \"new_stdin = open('%s', 'r')\")", m_dictionary_name.c_str(),
406 m_pty_slave_name.c_str());
407 PyRun_SimpleString (run_string.GetData());
408 m_pty_slave_is_open = true;
409
410 run_string.Clear();
411 run_string.Printf ("run_one_line (%s, 'sys.stdin = new_stdin')", m_dictionary_name.c_str());
412 PyRun_SimpleString (run_string.GetData());
413 }
414}
415
416
Johnny Chen60dde642010-07-30 22:33:14 +0000417bool
Greg Clayton238c0a12010-09-18 01:14:36 +0000418ScriptInterpreterPython::ExecuteOneLine (const char *command, CommandReturnObject *result)
Chris Lattner24943d22010-06-08 16:52:24 +0000419{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000420 if (!m_valid_session)
421 return false;
422
Caroline Tice0aa2e552011-01-14 00:29:16 +0000423
Caroline Tice0aa2e552011-01-14 00:29:16 +0000424
Caroline Tice4a461da2011-01-14 21:09:29 +0000425 // We want to call run_one_line, passing in the dictionary and the command string. We cannot do this through
426 // PyRun_SimpleString here because the command string may contain escaped characters, and putting it inside
427 // another string to pass to PyRun_SimpleString messes up the escaping. So we use the following more complicated
428 // method to pass the command string directly down to Python.
429
430
Caroline Tice202f6b82011-01-17 21:55:19 +0000431 bool need_to_release_lock = true;
432
433 if (CurrentThreadHasPythonLock())
434 need_to_release_lock = false;
435 else if (!GetPythonLock (1))
436 {
437 fprintf ((m_dbg_stdout ? m_dbg_stdout : stdout),
438 "Python interpreter is currently locked by another thread; unable to process command.\n");
439 return false;
440 }
441
442 EnterSession ();
Caroline Tice4a461da2011-01-14 21:09:29 +0000443 bool success = false;
444
Greg Clayton63094e02010-06-23 01:19:29 +0000445 if (command)
Chris Lattner24943d22010-06-08 16:52:24 +0000446 {
Caroline Tice4a461da2011-01-14 21:09:29 +0000447 // Find the correct script interpreter dictionary in the main module.
448 PyObject *main_mod = PyImport_AddModule ("__main__");
449 PyObject *script_interpreter_dict = NULL;
450 if (main_mod != NULL)
451 {
452 PyObject *main_dict = PyModule_GetDict (main_mod);
453 if ((main_dict != NULL)
454 && PyDict_Check (main_dict))
455 {
456 // Go through the main dictionary looking for the correct python script interpreter dictionary
457 PyObject *key, *value;
458 Py_ssize_t pos = 0;
459
460 while (PyDict_Next (main_dict, &pos, &key, &value))
461 {
462 // We have stolen references to the key and value objects in the dictionary; we need to increment
463 // them now so that Python's garbage collector doesn't collect them out from under us.
464 Py_INCREF (key);
465 Py_INCREF (value);
466 if (strcmp (PyString_AsString (key), m_dictionary_name.c_str()) == 0)
467 {
468 script_interpreter_dict = value;
469 break;
470 }
471 }
472 }
473
474 if (script_interpreter_dict != NULL)
475 {
476 PyObject *pfunc = NULL;
477 PyObject *pmod = PyImport_AddModule ("embedded_interpreter");
478 if (pmod != NULL)
479 {
480 PyObject *pmod_dict = PyModule_GetDict (pmod);
481 if ((pmod_dict != NULL)
482 && PyDict_Check (pmod_dict))
483 {
484 PyObject *key, *value;
485 Py_ssize_t pos = 0;
486
487 while (PyDict_Next (pmod_dict, &pos, &key, &value))
488 {
489 Py_INCREF (key);
490 Py_INCREF (value);
491 if (strcmp (PyString_AsString (key), "run_one_line") == 0)
492 {
493 pfunc = value;
494 break;
495 }
496 }
497
498 PyObject *string_arg = PyString_FromString (command);
499 if (pfunc && string_arg && PyCallable_Check (pfunc))
500 {
501 PyObject *pargs = PyTuple_New (2);
502 if (pargs != NULL)
503 {
504 PyTuple_SetItem (pargs, 0, script_interpreter_dict);
505 PyTuple_SetItem (pargs, 1, string_arg);
506 PyObject *pvalue = PyObject_CallObject (pfunc, pargs);
507 Py_DECREF (pargs);
508 if (pvalue != NULL)
509 {
510 Py_DECREF (pvalue);
511 success = true;
512 }
513 else if (PyErr_Occurred ())
514 {
515 PyErr_Print();
516 PyErr_Clear();
517 }
518 }
519 }
520 }
521 }
522 Py_INCREF (script_interpreter_dict);
523 }
524 }
Greg Clayton63094e02010-06-23 01:19:29 +0000525
Caroline Tice0aa2e552011-01-14 00:29:16 +0000526 LeaveSession ();
527
Caroline Tice202f6b82011-01-17 21:55:19 +0000528 if (need_to_release_lock)
529 ReleasePythonLock();
530
Caroline Tice4a461da2011-01-14 21:09:29 +0000531 if (success)
Johnny Chen60dde642010-07-30 22:33:14 +0000532 return true;
533
534 // The one-liner failed. Append the error message.
535 if (result)
536 result->AppendErrorWithFormat ("python failed attempting to evaluate '%s'\n", command);
537 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000538 }
Johnny Chen60dde642010-07-30 22:33:14 +0000539
Caroline Tice0aa2e552011-01-14 00:29:16 +0000540 LeaveSession ();
Caroline Tice202f6b82011-01-17 21:55:19 +0000541
542 if (need_to_release_lock)
543 ReleasePythonLock ();
544
Johnny Chen60dde642010-07-30 22:33:14 +0000545 if (result)
546 result->AppendError ("empty command passed to python\n");
547 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000548}
549
550
551
552size_t
553ScriptInterpreterPython::InputReaderCallback
554(
555 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000556 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000557 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000558 const char *bytes,
559 size_t bytes_len
560)
561{
Caroline Tice2ade6112010-11-10 19:18:14 +0000562 lldb::thread_t embedded_interpreter_thread;
563 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
564
Chris Lattner24943d22010-06-08 16:52:24 +0000565 if (baton == NULL)
566 return 0;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000567
568 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
569
570 if (script_interpreter->m_script_lang != eScriptLanguagePython)
571 return 0;
572
Caroline Tice67637d82010-12-15 19:51:12 +0000573 FILE *out_fh = reader.GetDebugger().GetOutputFileHandle ();
574 if (out_fh == NULL)
575 out_fh = stdout;
576
Chris Lattner24943d22010-06-08 16:52:24 +0000577 switch (notification)
578 {
579 case eInputReaderActivate:
580 {
Caroline Tice67637d82010-12-15 19:51:12 +0000581 if (out_fh)
582 {
Caroline Ticea81c3672011-02-03 20:08:40 +0000583 ::fprintf (out_fh, "Python Interactive Interpreter. To exit, type 'quit()', 'exit()' or Ctrl-D.\n");
Caroline Tice67637d82010-12-15 19:51:12 +0000584 }
Chris Lattner24943d22010-06-08 16:52:24 +0000585 // Save terminal settings if we can
Caroline Ticec95c6d12010-09-14 22:49:06 +0000586 int input_fd;
Greg Clayton63094e02010-06-23 01:19:29 +0000587 FILE *input_fh = reader.GetDebugger().GetInputFileHandle();
Caroline Ticec95c6d12010-09-14 22:49:06 +0000588 if (input_fh != NULL)
Greg Clayton24b48ff2010-10-17 22:03:32 +0000589 input_fd = ::fileno (input_fh);
Caroline Ticec95c6d12010-09-14 22:49:06 +0000590 else
Greg Clayton24b48ff2010-10-17 22:03:32 +0000591 input_fd = STDIN_FILENO;
Caroline Ticec95c6d12010-09-14 22:49:06 +0000592
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000593 script_interpreter->SaveTerminalState(input_fd);
Greg Clayton99208582011-02-07 19:04:58 +0000594
Caroline Tice202f6b82011-01-17 21:55:19 +0000595 if (!CurrentThreadHasPythonLock())
596 {
597 while (!GetPythonLock(1))
598 {
599 ::fprintf (out_fh, "Python interpreter locked on another thread; waiting to acquire lock...\n");
600 }
601 script_interpreter->EnterSession ();
602 ReleasePythonLock();
603 }
604 else
605 script_interpreter->EnterSession ();
606
Caroline Tice2ade6112010-11-10 19:18:14 +0000607 char error_str[1024];
608 if (script_interpreter->m_embedded_python_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, error_str,
609 sizeof(error_str)))
610 {
611 if (log)
612 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in opening master pty (fd = %d).",
613 script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor());
614 embedded_interpreter_thread = Host::ThreadCreate ("<lldb.script-interpreter.embedded-python-loop>",
615 ScriptInterpreterPython::RunEmbeddedPythonInterpreter,
616 script_interpreter, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +0000617 if (IS_VALID_LLDB_HOST_THREAD(embedded_interpreter_thread))
Caroline Tice2ade6112010-11-10 19:18:14 +0000618 {
619 if (log)
620 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in creating thread (thread = %d)", embedded_interpreter_thread);
621 Error detach_error;
622 Host::ThreadDetach (embedded_interpreter_thread, &detach_error);
623 }
624 else
625 {
626 if (log)
627 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed in creating thread");
628 reader.SetIsDone (true);
629 }
630 }
631 else
632 {
633 if (log)
634 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed to open master pty ");
635 reader.SetIsDone (true);
636 }
Chris Lattner24943d22010-06-08 16:52:24 +0000637 }
638 break;
639
640 case eInputReaderDeactivate:
Caroline Tice0aa2e552011-01-14 00:29:16 +0000641 script_interpreter->LeaveSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000642 break;
643
644 case eInputReaderReactivate:
Caroline Tice202f6b82011-01-17 21:55:19 +0000645 if (!CurrentThreadHasPythonLock())
646 {
647 while (!GetPythonLock(1))
648 {
649 // Wait until lock is acquired.
650 }
651 script_interpreter->EnterSession ();
652 ReleasePythonLock();
653 }
654 else
655 script_interpreter->EnterSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000656 break;
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000657
658 case eInputReaderInterrupt:
659 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "raise KeyboardInterrupt\n", 24);
660 break;
661
662 case eInputReaderEndOfFile:
663 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()\n", 7);
664 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000665
666 case eInputReaderGotToken:
Caroline Tice2ade6112010-11-10 19:18:14 +0000667 if (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor() != -1)
Chris Lattner24943d22010-06-08 16:52:24 +0000668 {
Caroline Tice2ade6112010-11-10 19:18:14 +0000669 if (log)
670 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %d", bytes,
671 bytes_len);
672 if (bytes && bytes_len)
673 {
674 if ((int) bytes[0] == 4)
675 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()", 6);
676 else
677 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), bytes, bytes_len);
678 }
679 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "\n", 1);
Chris Lattner24943d22010-06-08 16:52:24 +0000680 }
Caroline Tice2ade6112010-11-10 19:18:14 +0000681 else
682 {
683 if (log)
684 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %d, Master File Descriptor is bad.",
685 bytes,
686 bytes_len);
687 reader.SetIsDone (true);
688 }
689
Chris Lattner24943d22010-06-08 16:52:24 +0000690 break;
691
692 case eInputReaderDone:
Caroline Tice0aa2e552011-01-14 00:29:16 +0000693 script_interpreter->LeaveSession ();
694
Chris Lattner24943d22010-06-08 16:52:24 +0000695 // Restore terminal settings if they were validly saved
Caroline Tice2ade6112010-11-10 19:18:14 +0000696 if (log)
697 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Done, closing down input reader.");
Caroline Ticec95c6d12010-09-14 22:49:06 +0000698
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000699 script_interpreter->RestoreTerminalState ();
700
Caroline Tice2ade6112010-11-10 19:18:14 +0000701 script_interpreter->m_embedded_python_pty.CloseMasterFileDescriptor();
Chris Lattner24943d22010-06-08 16:52:24 +0000702 break;
703 }
704
705 return bytes_len;
706}
707
708
709void
Greg Clayton238c0a12010-09-18 01:14:36 +0000710ScriptInterpreterPython::ExecuteInterpreterLoop ()
Chris Lattner24943d22010-06-08 16:52:24 +0000711{
712 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
713
Caroline Tice0aa2e552011-01-14 00:29:16 +0000714 Debugger &debugger = GetCommandInterpreter().GetDebugger();
Caroline Ticec95c6d12010-09-14 22:49:06 +0000715
716 // At the moment, the only time the debugger does not have an input file handle is when this is called
717 // directly from Python, in which case it is both dangerous and unnecessary (not to mention confusing) to
718 // try to embed a running interpreter loop inside the already running Python interpreter loop, so we won't
719 // do it.
720
721 if (debugger.GetInputFileHandle() == NULL)
722 return;
723
Greg Clayton63094e02010-06-23 01:19:29 +0000724 InputReaderSP reader_sp (new InputReader(debugger));
Chris Lattner24943d22010-06-08 16:52:24 +0000725 if (reader_sp)
726 {
727 Error error (reader_sp->Initialize (ScriptInterpreterPython::InputReaderCallback,
728 this, // baton
729 eInputReaderGranularityLine, // token size, to pass to callback function
730 NULL, // end token
731 NULL, // prompt
732 true)); // echo input
733
734 if (error.Success())
735 {
Greg Clayton63094e02010-06-23 01:19:29 +0000736 debugger.PushInputReader (reader_sp);
Caroline Tice2ade6112010-11-10 19:18:14 +0000737 m_embedded_thread_input_reader_sp = reader_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000738 }
739 }
740}
741
742bool
743ScriptInterpreterPython::ExecuteOneLineWithReturn (const char *in_string,
744 ScriptInterpreter::ReturnType return_type,
745 void *ret_value)
746{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000747
Caroline Tice202f6b82011-01-17 21:55:19 +0000748 bool need_to_release_lock = true;
749
750 if (CurrentThreadHasPythonLock())
751 need_to_release_lock = false;
752 else if (!GetPythonLock (1))
753 {
754 fprintf ((m_dbg_stdout ? m_dbg_stdout : stdout),
755 "Python interpreter is currently locked by another thread; unable to process command.\n");
756 return false;
757 }
758
759 EnterSession ();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000760
Chris Lattner24943d22010-06-08 16:52:24 +0000761 PyObject *py_return = NULL;
762 PyObject *mainmod = PyImport_AddModule ("__main__");
763 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000764 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000765 PyObject *py_error = NULL;
766 bool ret_success;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000767 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000768 int success;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000769
770 if (PyDict_Check (globals))
771 {
772 PyObject *key, *value;
773 Py_ssize_t pos = 0;
774
775 int i = 0;
776 while (PyDict_Next (globals, &pos, &key, &value))
777 {
778 // We have stolen references to the key and value objects in the dictionary; we need to increment them now
779 // so that Python's garbage collector doesn't collect them out from under us.
780 Py_INCREF (key);
781 Py_INCREF (value);
782 char *c_str = PyString_AsString (key);
783 if (strcmp (c_str, m_dictionary_name.c_str()) == 0)
784 locals = value;
785 ++i;
786 }
787 }
Chris Lattner24943d22010-06-08 16:52:24 +0000788
Caroline Tice0aa2e552011-01-14 00:29:16 +0000789 if (locals == NULL)
790 {
791 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
792 should_decrement_locals = true;
793 }
794
795 if (locals == NULL)
796 {
797 locals = globals;
798 should_decrement_locals = false;
799 }
800
801 py_error = PyErr_Occurred();
802 if (py_error != NULL)
803 PyErr_Clear();
804
Chris Lattner24943d22010-06-08 16:52:24 +0000805 if (in_string != NULL)
806 {
807 py_return = PyRun_String (in_string, Py_eval_input, globals, locals);
808 if (py_return == NULL)
809 {
810 py_error = PyErr_Occurred ();
811 if (py_error != NULL)
812 PyErr_Clear ();
813
814 py_return = PyRun_String (in_string, Py_single_input, globals, locals);
815 }
816
Caroline Tice0aa2e552011-01-14 00:29:16 +0000817 if (locals != NULL
818 && should_decrement_locals)
819 Py_DECREF (locals);
820
Chris Lattner24943d22010-06-08 16:52:24 +0000821 if (py_return != NULL)
822 {
823 switch (return_type)
824 {
825 case eCharPtr: // "char *"
826 {
827 const char format[3] = "s#";
828 success = PyArg_Parse (py_return, format, (char **) &ret_value);
829 break;
830 }
831 case eBool:
832 {
833 const char format[2] = "b";
834 success = PyArg_Parse (py_return, format, (bool *) ret_value);
835 break;
836 }
837 case eShortInt:
838 {
839 const char format[2] = "h";
840 success = PyArg_Parse (py_return, format, (short *) ret_value);
841 break;
842 }
843 case eShortIntUnsigned:
844 {
845 const char format[2] = "H";
846 success = PyArg_Parse (py_return, format, (unsigned short *) ret_value);
847 break;
848 }
849 case eInt:
850 {
851 const char format[2] = "i";
852 success = PyArg_Parse (py_return, format, (int *) ret_value);
853 break;
854 }
855 case eIntUnsigned:
856 {
857 const char format[2] = "I";
858 success = PyArg_Parse (py_return, format, (unsigned int *) ret_value);
859 break;
860 }
861 case eLongInt:
862 {
863 const char format[2] = "l";
864 success = PyArg_Parse (py_return, format, (long *) ret_value);
865 break;
866 }
867 case eLongIntUnsigned:
868 {
869 const char format[2] = "k";
870 success = PyArg_Parse (py_return, format, (unsigned long *) ret_value);
871 break;
872 }
873 case eLongLong:
874 {
875 const char format[2] = "L";
876 success = PyArg_Parse (py_return, format, (long long *) ret_value);
877 break;
878 }
879 case eLongLongUnsigned:
880 {
881 const char format[2] = "K";
882 success = PyArg_Parse (py_return, format, (unsigned long long *) ret_value);
883 break;
884 }
885 case eFloat:
886 {
887 const char format[2] = "f";
888 success = PyArg_Parse (py_return, format, (float *) ret_value);
889 break;
890 }
891 case eDouble:
892 {
893 const char format[2] = "d";
894 success = PyArg_Parse (py_return, format, (double *) ret_value);
895 break;
896 }
897 case eChar:
898 {
899 const char format[2] = "c";
900 success = PyArg_Parse (py_return, format, (char *) ret_value);
901 break;
902 }
903 default:
904 {}
905 }
906 Py_DECREF (py_return);
907 if (success)
908 ret_success = true;
909 else
910 ret_success = false;
911 }
912 }
913
914 py_error = PyErr_Occurred();
915 if (py_error != NULL)
916 {
917 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
918 PyErr_Print ();
919 PyErr_Clear();
920 ret_success = false;
921 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000922
923 LeaveSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000924
Caroline Tice202f6b82011-01-17 21:55:19 +0000925 if (need_to_release_lock)
926 ReleasePythonLock();
927
Chris Lattner24943d22010-06-08 16:52:24 +0000928 return ret_success;
929}
930
931bool
932ScriptInterpreterPython::ExecuteMultipleLines (const char *in_string)
933{
Caroline Tice202f6b82011-01-17 21:55:19 +0000934 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
935 bool need_to_release_lock = true;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000936
Caroline Tice202f6b82011-01-17 21:55:19 +0000937 if (CurrentThreadHasPythonLock())
938 need_to_release_lock = false;
939 else
940 {
941 while (!GetPythonLock (1))
942 fprintf (tmp_fh, "Python interpreter locked on another thread; waiting to acquire lock...\n");
943 }
944
945 EnterSession ();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000946
Chris Lattner24943d22010-06-08 16:52:24 +0000947 bool success = false;
948 PyObject *py_return = NULL;
949 PyObject *mainmod = PyImport_AddModule ("__main__");
950 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000951 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000952 PyObject *py_error = NULL;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000953 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000954
Caroline Tice0aa2e552011-01-14 00:29:16 +0000955 if (PyDict_Check (globals))
956 {
957 PyObject *key, *value;
958 Py_ssize_t pos = 0;
959
960 while (PyDict_Next (globals, &pos, &key, &value))
961 {
962 // We have stolen references to the key and value objects in the dictionary; we need to increment them now
963 // so that Python's garbage collector doesn't collect them out from under us.
964 Py_INCREF (key);
965 Py_INCREF (value);
966 if (strcmp (PyString_AsString (key), m_dictionary_name.c_str()) == 0)
967 locals = value;
968 }
969 }
970
971 if (locals == NULL)
972 {
973 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
974 should_decrement_locals = true;
975 }
976
977 if (locals == NULL)
978 {
979 locals = globals;
980 should_decrement_locals = false;
981 }
982
983 py_error = PyErr_Occurred();
984 if (py_error != NULL)
985 PyErr_Clear();
986
Chris Lattner24943d22010-06-08 16:52:24 +0000987 if (in_string != NULL)
988 {
989 struct _node *compiled_node = PyParser_SimpleParseString (in_string, Py_file_input);
990 if (compiled_node)
991 {
992 PyCodeObject *compiled_code = PyNode_Compile (compiled_node, "temp.py");
993 if (compiled_code)
994 {
995 py_return = PyEval_EvalCode (compiled_code, globals, locals);
996 if (py_return != NULL)
997 {
998 success = true;
999 Py_DECREF (py_return);
1000 }
Caroline Tice0aa2e552011-01-14 00:29:16 +00001001 if (locals && should_decrement_locals)
1002 Py_DECREF (locals);
Chris Lattner24943d22010-06-08 16:52:24 +00001003 }
1004 }
1005 }
1006
1007 py_error = PyErr_Occurred ();
1008 if (py_error != NULL)
1009 {
1010 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
1011 PyErr_Print ();
1012 PyErr_Clear();
1013 success = false;
1014 }
1015
Caroline Tice0aa2e552011-01-14 00:29:16 +00001016 LeaveSession ();
1017
Caroline Tice202f6b82011-01-17 21:55:19 +00001018 if (need_to_release_lock)
1019 ReleasePythonLock();
1020
Chris Lattner24943d22010-06-08 16:52:24 +00001021 return success;
1022}
1023
1024static const char *g_reader_instructions = "Enter your Python command(s). Type 'DONE' to end.";
1025
1026size_t
1027ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback
1028(
1029 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +00001030 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +00001031 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +00001032 const char *bytes,
1033 size_t bytes_len
1034)
1035{
1036 static StringList commands_in_progress;
1037
Greg Clayton63094e02010-06-23 01:19:29 +00001038 FILE *out_fh = reader.GetDebugger().GetOutputFileHandle();
Caroline Ticec95c6d12010-09-14 22:49:06 +00001039 if (out_fh == NULL)
1040 out_fh = stdout;
1041
Chris Lattner24943d22010-06-08 16:52:24 +00001042 switch (notification)
1043 {
1044 case eInputReaderActivate:
1045 {
1046 commands_in_progress.Clear();
1047 if (out_fh)
1048 {
1049 ::fprintf (out_fh, "%s\n", g_reader_instructions);
Greg Clayton63094e02010-06-23 01:19:29 +00001050 if (reader.GetPrompt())
1051 ::fprintf (out_fh, "%s", reader.GetPrompt());
Caroline Ticef81b4c52010-10-27 18:34:42 +00001052 ::fflush (out_fh);
Chris Lattner24943d22010-06-08 16:52:24 +00001053 }
1054 }
1055 break;
1056
1057 case eInputReaderDeactivate:
1058 break;
1059
1060 case eInputReaderReactivate:
Greg Clayton63094e02010-06-23 01:19:29 +00001061 if (reader.GetPrompt() && out_fh)
Caroline Ticef81b4c52010-10-27 18:34:42 +00001062 {
Greg Clayton63094e02010-06-23 01:19:29 +00001063 ::fprintf (out_fh, "%s", reader.GetPrompt());
Caroline Ticef81b4c52010-10-27 18:34:42 +00001064 ::fflush (out_fh);
1065 }
Chris Lattner24943d22010-06-08 16:52:24 +00001066 break;
1067
1068 case eInputReaderGotToken:
1069 {
1070 std::string temp_string (bytes, bytes_len);
1071 commands_in_progress.AppendString (temp_string.c_str());
Greg Clayton63094e02010-06-23 01:19:29 +00001072 if (out_fh && !reader.IsDone() && reader.GetPrompt())
Caroline Ticef81b4c52010-10-27 18:34:42 +00001073 {
Greg Clayton63094e02010-06-23 01:19:29 +00001074 ::fprintf (out_fh, "%s", reader.GetPrompt());
Caroline Ticef81b4c52010-10-27 18:34:42 +00001075 ::fflush (out_fh);
1076 }
Chris Lattner24943d22010-06-08 16:52:24 +00001077 }
1078 break;
1079
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001080 case eInputReaderEndOfFile:
1081 case eInputReaderInterrupt:
1082 // Control-c (SIGINT) & control-d both mean finish & exit.
1083 reader.SetIsDone(true);
1084
1085 // Control-c (SIGINT) ALSO means cancel; do NOT create a breakpoint command.
1086 if (notification == eInputReaderInterrupt)
1087 commands_in_progress.Clear();
1088
1089 // Fall through here...
1090
Chris Lattner24943d22010-06-08 16:52:24 +00001091 case eInputReaderDone:
1092 {
1093 BreakpointOptions *bp_options = (BreakpointOptions *)baton;
1094 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1095 data_ap->user_source.AppendList (commands_in_progress);
1096 if (data_ap.get())
1097 {
Greg Clayton63094e02010-06-23 01:19:29 +00001098 ScriptInterpreter *interpreter = reader.GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
Chris Lattner24943d22010-06-08 16:52:24 +00001099 if (interpreter)
1100 {
1101 if (interpreter->GenerateBreakpointCommandCallbackData (data_ap->user_source,
1102 data_ap->script_source))
1103 {
1104 if (data_ap->script_source.GetSize() == 1)
1105 {
1106 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1107 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
1108 }
1109 }
Caroline Ticeb447e842010-09-21 19:25:28 +00001110 else
Caroline Tice5136f942010-09-27 21:35:15 +00001111 ::fprintf (out_fh, "Warning: No command attached to breakpoint.\n");
Chris Lattner24943d22010-06-08 16:52:24 +00001112 }
1113 else
1114 {
1115 // FIXME: Error processing.
1116 }
1117 }
1118 }
1119 break;
1120
1121 }
1122
1123 return bytes_len;
1124}
1125
1126void
Greg Clayton238c0a12010-09-18 01:14:36 +00001127ScriptInterpreterPython::CollectDataForBreakpointCommandCallback (BreakpointOptions *bp_options,
Chris Lattner24943d22010-06-08 16:52:24 +00001128 CommandReturnObject &result)
1129{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001130 Debugger &debugger = GetCommandInterpreter().GetDebugger();
1131
Greg Clayton63094e02010-06-23 01:19:29 +00001132 InputReaderSP reader_sp (new InputReader (debugger));
Chris Lattner24943d22010-06-08 16:52:24 +00001133
1134 if (reader_sp)
1135 {
1136 Error err = reader_sp->Initialize (
1137 ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback,
1138 bp_options, // baton
1139 eInputReaderGranularityLine, // token size, for feeding data to callback function
1140 "DONE", // end token
1141 "> ", // prompt
1142 true); // echo input
1143
1144 if (err.Success())
Greg Clayton63094e02010-06-23 01:19:29 +00001145 debugger.PushInputReader (reader_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001146 else
1147 {
1148 result.AppendError (err.AsCString());
1149 result.SetStatus (eReturnStatusFailed);
1150 }
1151 }
1152 else
1153 {
1154 result.AppendError("out of memory");
1155 result.SetStatus (eReturnStatusFailed);
1156 }
1157}
1158
Johnny Chen3e0571b2010-09-11 00:23:59 +00001159// Set a Python one-liner as the callback for the breakpoint.
Johnny Chend1c2dca2010-09-10 18:21:10 +00001160void
Greg Clayton238c0a12010-09-18 01:14:36 +00001161ScriptInterpreterPython::SetBreakpointCommandCallback (BreakpointOptions *bp_options,
Johnny Chend1c2dca2010-09-10 18:21:10 +00001162 const char *oneliner)
1163{
1164 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1165
1166 // It's necessary to set both user_source and script_source to the oneliner.
1167 // The former is used to generate callback description (as in breakpoint command list)
1168 // while the latter is used for Python to interpret during the actual callback.
Caroline Tice5136f942010-09-27 21:35:15 +00001169
Johnny Chend1c2dca2010-09-10 18:21:10 +00001170 data_ap->user_source.AppendString (oneliner);
Johnny Chend1c2dca2010-09-10 18:21:10 +00001171
Caroline Tice5136f942010-09-27 21:35:15 +00001172 if (GenerateBreakpointCommandCallbackData (data_ap->user_source, data_ap->script_source))
1173 {
1174 if (data_ap->script_source.GetSize() == 1)
1175 {
1176 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1177 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
1178 }
1179 }
1180
Johnny Chend1c2dca2010-09-10 18:21:10 +00001181 return;
1182}
1183
Chris Lattner24943d22010-06-08 16:52:24 +00001184bool
1185ScriptInterpreterPython::ExportFunctionDefinitionToInterpreter (StringList &function_def)
1186{
1187 // Convert StringList to one long, newline delimited, const char *.
1188 std::string function_def_string;
1189
1190 int num_lines = function_def.GetSize();
1191
1192 for (int i = 0; i < num_lines; ++i)
1193 {
1194 function_def_string.append (function_def.GetStringAtIndex(i));
1195 if (function_def_string.at (function_def_string.length() - 1) != '\n')
1196 function_def_string.append ("\n");
1197
1198 }
1199
1200 return ExecuteMultipleLines (function_def_string.c_str());
1201}
1202
1203bool
1204ScriptInterpreterPython::GenerateBreakpointCommandCallbackData (StringList &user_input, StringList &callback_data)
1205{
1206 static int num_created_functions = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001207 user_input.RemoveBlankLines ();
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001208 int num_lines = user_input.GetSize ();
1209 StreamString sstr;
Chris Lattner24943d22010-06-08 16:52:24 +00001210
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001211 // Check to see if we have any data; if not, just return.
1212 if (user_input.GetSize() == 0)
1213 return false;
1214
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001215 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1216 // frame and breakpoint location as parameters to the function.
Caroline Ticeb447e842010-09-21 19:25:28 +00001217
Caroline Ticeb447e842010-09-21 19:25:28 +00001218
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001219 sstr.Printf ("lldb_autogen_python_bp_callback_func_%d", num_created_functions);
1220 ++num_created_functions;
1221 std::string auto_generated_function_name = sstr.GetData();
Caroline Ticeb447e842010-09-21 19:25:28 +00001222
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001223 sstr.Clear();
Caroline Ticeb447e842010-09-21 19:25:28 +00001224 StringList auto_generated_function;
Caroline Ticeb447e842010-09-21 19:25:28 +00001225
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001226 // Create the function name & definition string.
1227
Caroline Tice0aa2e552011-01-14 00:29:16 +00001228 sstr.Printf ("def %s (frame, bp_loc, dict):", auto_generated_function_name.c_str());
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001229 auto_generated_function.AppendString (sstr.GetData());
Caroline Tice0aa2e552011-01-14 00:29:16 +00001230
1231 // Pre-pend code for setting up the session dictionary.
1232
1233 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1234 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1235 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1236 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1237 // global dictionary.
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001238
1239 // Wrap everything up inside the function, increasing the indentation.
Chris Lattner24943d22010-06-08 16:52:24 +00001240
1241 for (int i = 0; i < num_lines; ++i)
1242 {
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001243 sstr.Clear ();
1244 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1245 auto_generated_function.AppendString (sstr.GetData());
Caroline Ticeb447e842010-09-21 19:25:28 +00001246 }
Chris Lattner24943d22010-06-08 16:52:24 +00001247
Caroline Tice0aa2e552011-01-14 00:29:16 +00001248 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1249 // got written to the values in the global dictionary, not the session dictionary).
1250
1251 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1252 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1253 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1254 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1255
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001256 // Verify that the results are valid Python.
Chris Lattner24943d22010-06-08 16:52:24 +00001257
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001258 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
Caroline Ticeb447e842010-09-21 19:25:28 +00001259 {
Caroline Ticeb447e842010-09-21 19:25:28 +00001260 return false;
Chris Lattner24943d22010-06-08 16:52:24 +00001261 }
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001262
1263 // Store the name of the auto-generated function to be called.
1264
1265 callback_data.AppendString (auto_generated_function_name.c_str());
1266 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001267}
1268
Greg Clayton5144f382010-10-07 17:14:24 +00001269bool
1270ScriptInterpreterPython::BreakpointCallbackFunction
1271(
1272 void *baton,
1273 StoppointCallbackContext *context,
1274 user_id_t break_id,
1275 user_id_t break_loc_id
1276)
1277{
1278 BreakpointOptions::CommandData *bp_option_data = (BreakpointOptions::CommandData *) baton;
1279 const char *python_function_name = bp_option_data->script_source.GetStringAtIndex (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001280
1281 if (!context)
1282 return true;
1283
1284 Target *target = context->exe_ctx.target;
1285
1286 if (!target)
1287 return true;
1288
1289 Debugger &debugger = target->GetDebugger();
1290 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1291 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1292
1293 if (!script_interpreter)
1294 return true;
Greg Clayton5144f382010-10-07 17:14:24 +00001295
1296 if (python_function_name != NULL
1297 && python_function_name[0] != '\0')
1298 {
1299 Thread *thread = context->exe_ctx.thread;
Greg Clayton5144f382010-10-07 17:14:24 +00001300 const StackFrameSP stop_frame_sp = thread->GetStackFrameSPForStackFramePtr (context->exe_ctx.frame);
1301 BreakpointSP breakpoint_sp = target->GetBreakpointByID (break_id);
1302 const BreakpointLocationSP bp_loc_sp = breakpoint_sp->FindLocationByID (break_loc_id);
1303
1304 SBFrame sb_frame (stop_frame_sp);
1305 SBBreakpointLocation sb_bp_loc (bp_loc_sp);
1306
1307 if (sb_bp_loc.IsValid() || sb_frame.IsValid())
Caroline Tice0aa2e552011-01-14 00:29:16 +00001308 {
Caroline Tice202f6b82011-01-17 21:55:19 +00001309 bool ret_val = true;
1310 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
1311 if (CurrentThreadHasPythonLock())
1312 {
1313 python_interpreter->EnterSession ();
1314 ret_val = LLDBSWIGPythonBreakpointCallbackFunction(python_function_name,
1315 python_interpreter->m_dictionary_name.c_str(),
1316 sb_frame, sb_bp_loc);
1317 python_interpreter->LeaveSession ();
1318 }
1319 else
1320 {
1321 while (!GetPythonLock (1))
1322 fprintf (tmp_fh,
1323 "Python interpreter locked on another thread; waiting to acquire lock...\n");
1324 python_interpreter->EnterSession ();
1325 ret_val = LLDBSWIGPythonBreakpointCallbackFunction(python_function_name,
1326 python_interpreter->m_dictionary_name.c_str(),
1327 sb_frame, sb_bp_loc);
1328 python_interpreter->LeaveSession ();
1329 ReleasePythonLock ();
1330 }
Caroline Tice0aa2e552011-01-14 00:29:16 +00001331 return ret_val;
1332 }
Greg Clayton5144f382010-10-07 17:14:24 +00001333 }
1334 // We currently always true so we stop in case anything goes wrong when
1335 // trying to call the script function
1336 return true;
1337}
Caroline Tice2ade6112010-11-10 19:18:14 +00001338
1339lldb::thread_result_t
1340ScriptInterpreterPython::RunEmbeddedPythonInterpreter (lldb::thread_arg_t baton)
1341{
1342 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
1343
1344 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
1345
1346 if (log)
1347 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread starting...", baton);
1348
1349 char error_str[1024];
1350 const char *pty_slave_name = script_interpreter->m_embedded_python_pty.GetSlaveName (error_str, sizeof (error_str));
Caroline Tice202f6b82011-01-17 21:55:19 +00001351 bool need_to_release_lock = true;
1352 bool safe_to_run = false;
Caroline Tice0aa2e552011-01-14 00:29:16 +00001353
Caroline Tice202f6b82011-01-17 21:55:19 +00001354 if (CurrentThreadHasPythonLock())
1355 {
1356 safe_to_run = true;
1357 need_to_release_lock = false;
1358 }
1359 else
1360 {
1361 int interval = 1;
1362 safe_to_run = GetPythonLock (interval);
1363 while (!safe_to_run)
1364 {
1365 interval = interval * 2;
1366 safe_to_run = GetPythonLock (interval);
1367 }
1368 }
1369
1370 if (pty_slave_name != NULL && safe_to_run)
1371 {
Caroline Tice2ade6112010-11-10 19:18:14 +00001372 StreamString run_string;
Caroline Tice2ade6112010-11-10 19:18:14 +00001373
Caroline Tice202f6b82011-01-17 21:55:19 +00001374 script_interpreter->EnterSession ();
1375
Caroline Tice0aa2e552011-01-14 00:29:16 +00001376 run_string.Printf ("run_one_line (%s, 'save_stderr = sys.stderr')", script_interpreter->m_dictionary_name.c_str());
1377 PyRun_SimpleString (run_string.GetData());
1378 run_string.Clear ();
1379
1380 run_string.Printf ("run_one_line (%s, 'sys.stderr = sys.stdout')", 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, 'save_stdin = sys.stdin')", 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, \"sys.stdin = open ('%s', 'r')\")", script_interpreter->m_dictionary_name.c_str(),
1389 pty_slave_name);
1390 PyRun_SimpleString (run_string.GetData());
1391 run_string.Clear ();
1392
Caroline Tice2ade6112010-11-10 19:18:14 +00001393 // The following call drops into the embedded interpreter loop and stays there until the
1394 // user chooses to exit from the Python interpreter.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001395
1396 run_string.Printf ("run_python_interpreter (%s)", script_interpreter->m_dictionary_name.c_str());
1397 PyRun_SimpleString (run_string.GetData());
1398 run_string.Clear ();
Caroline Tice2ade6112010-11-10 19:18:14 +00001399
Caroline Tice0aa2e552011-01-14 00:29:16 +00001400 run_string.Printf ("run_one_line (%s, 'sys.stdin = save_stdin')", script_interpreter->m_dictionary_name.c_str());
1401 PyRun_SimpleString (run_string.GetData());
1402 run_string.Clear();
1403
1404 run_string.Printf ("run_one_line (%s, 'sys.stderr = save_stderr')", script_interpreter->m_dictionary_name.c_str());
1405 PyRun_SimpleString (run_string.GetData());
1406 run_string.Clear();
Caroline Tice202f6b82011-01-17 21:55:19 +00001407
1408 script_interpreter->LeaveSession ();
1409
Caroline Tice2ade6112010-11-10 19:18:14 +00001410 }
1411
Caroline Tice202f6b82011-01-17 21:55:19 +00001412 if (!safe_to_run)
1413 fprintf ((script_interpreter->m_dbg_stdout ? script_interpreter->m_dbg_stdout : stdout),
1414 "Python interpreter locked on another thread; unable to acquire lock.\n");
1415
1416 if (need_to_release_lock)
1417 ReleasePythonLock ();
1418
Caroline Tice2ade6112010-11-10 19:18:14 +00001419 if (script_interpreter->m_embedded_thread_input_reader_sp)
1420 script_interpreter->m_embedded_thread_input_reader_sp->SetIsDone (true);
1421
1422 script_interpreter->m_embedded_python_pty.CloseSlaveFileDescriptor();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001423
1424 script_interpreter->m_pty_slave_is_open = false;
Caroline Tice2ade6112010-11-10 19:18:14 +00001425
1426 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT);
1427 if (log)
1428 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread exiting...", baton);
1429
1430
Caroline Tice0aa2e552011-01-14 00:29:16 +00001431 // Clean up the input reader and make the debugger pop it off the stack.
1432 Debugger &debugger = script_interpreter->GetCommandInterpreter().GetDebugger();
Caroline Tice2ade6112010-11-10 19:18:14 +00001433 const InputReaderSP reader_sp = script_interpreter->m_embedded_thread_input_reader_sp;
1434 script_interpreter->m_embedded_thread_input_reader_sp.reset();
1435 debugger.PopInputReader (reader_sp);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001436
Caroline Tice2ade6112010-11-10 19:18:14 +00001437 return NULL;
1438}
1439
1440
Caroline Tice0aa2e552011-01-14 00:29:16 +00001441void
1442ScriptInterpreterPython::Initialize ()
1443{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001444 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
1445
Greg Clayton0fdd4a02011-02-07 23:24:47 +00001446 // Python will muck with STDIN terminal state, so save off any current TTY
1447 // settings so we can restore them.
1448 TerminalState stdin_tty_state;
1449 stdin_tty_state.Save(STDIN_FILENO, false);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001450
1451 // Find the module that owns this code and use that path we get to
1452 // set the PYTHONPATH appropriately.
1453
1454 FileSpec file_spec;
1455 char python_dir_path[PATH_MAX];
1456 if (Host::GetLLDBPath (ePathTypePythonDir, file_spec))
1457 {
1458 std::string python_path;
1459 const char *curr_python_path = ::getenv ("PYTHONPATH");
1460 if (curr_python_path)
1461 {
1462 // We have a current value for PYTHONPATH, so lets append to it
1463 python_path.append (curr_python_path);
1464 }
1465
1466 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
1467 {
1468 if (!python_path.empty())
1469 python_path.append (1, ':');
1470 python_path.append (python_dir_path);
1471 }
1472
1473 if (Host::GetLLDBPath (ePathTypeLLDBShlibDir, file_spec))
1474 {
1475 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
1476 {
1477 if (!python_path.empty())
1478 python_path.append (1, ':');
1479 python_path.append (python_dir_path);
1480 }
1481 }
1482 const char *pathon_path_env_cstr = python_path.c_str();
1483 ::setenv ("PYTHONPATH", pathon_path_env_cstr, 1);
1484 }
1485
1486 Py_Initialize ();
1487
1488 PyObject *compiled_module = Py_CompileString (embedded_interpreter_string,
1489 "embedded_interpreter.py",
1490 Py_file_input);
1491
1492 PyObject *py_error = PyErr_Occurred ();
1493 if (py_error != NULL)
1494 {
1495 PyErr_Print();
1496 PyErr_Clear();
1497 }
1498
1499
1500 // This function is in the C++ output file generated by SWIG after it is
1501 // run on all of the headers in "lldb/API/SB*.h"
1502 init_lldb ();
1503
1504 // Update the path python uses to search for modules to include the current directory.
1505
1506 int success = PyRun_SimpleString ("import sys");
1507 success = PyRun_SimpleString ("sys.path.append ('.')");
1508
1509 PyObject *pmod = NULL;
1510
1511 if (compiled_module)
1512 {
1513 pmod = PyImport_ExecCodeModule (const_cast<char*> ("embedded_interpreter"),
1514 compiled_module);
1515 Py_DECREF (compiled_module);
1516 }
1517
1518 if (pmod != NULL)
1519 {
1520 PyRun_SimpleString ("from embedded_interpreter import run_python_interpreter");
1521 PyRun_SimpleString ("from embedded_interpreter import run_one_line");
1522 PyRun_SimpleString ("import sys");
1523 PyRun_SimpleString ("from termios import *");
1524 Py_DECREF (pmod);
1525 }
Greg Clayton99208582011-02-07 19:04:58 +00001526
Greg Clayton0fdd4a02011-02-07 23:24:47 +00001527 stdin_tty_state.Restore();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001528}
1529
1530void
1531ScriptInterpreterPython::Terminate ()
1532{
1533 // We are intentionally NOT calling Py_Finalize here (this would be the logical place to call it). Calling
1534 // Py_Finalize here causes test suite runs to seg fault: The test suite runs in Python. It registers
1535 // SBDebugger::Terminate to be called 'at_exit'. When the test suite Python harness finishes up, it calls
1536 // Py_Finalize, which calls all the 'at_exit' registered functions. SBDebugger::Terminate calls Debugger::Terminate,
1537 // which calls lldb::Terminate, which calls ScriptInterpreter::Terminate, which calls
1538 // ScriptInterpreterPython::Terminate. So if we call Py_Finalize here, we end up with Py_Finalize being called from
1539 // within Py_Finalize, which results in a seg fault.
1540 //
1541 // Since this function only gets called when lldb is shutting down and going away anyway, the fact that we don't
1542 // actually call Py_Finalize should not cause any problems (everything should shut down/go away anyway when the
1543 // process exits).
1544 //
1545// Py_Finalize ();
1546}