blob: 61bab4851cf853d0b5e7ac23493bdeb70e88786b [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()),
Caroline Tice2ade6112010-11-10 19:18:14 +0000204 m_termios (),
205 m_termios_valid (false),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000206 m_session_is_active (false),
207 m_pty_slave_is_open (false),
208 m_valid_session (true)
Chris Lattner24943d22010-06-08 16:52:24 +0000209{
210
Greg Clayton7c330d62011-01-27 01:01:10 +0000211 static int g_initialized = false;
212
213 if (!g_initialized)
214 {
215 g_initialized = true;
216 ScriptInterpreterPython::Initialize ();
217 }
218
Caroline Tice202f6b82011-01-17 21:55:19 +0000219 bool safe_to_run = false;
220 bool need_to_release_lock = true;
221 int interval = 5; // Number of seconds to try getting the Python lock before timing out.
222
223 // We don't dare exit this function without finishing setting up the script interpreter, so we must wait until
224 // we can get the Python lock.
225
226 if (CurrentThreadHasPythonLock())
227 {
228 safe_to_run = true;
229 need_to_release_lock = false;
230 }
231
232 while (!safe_to_run)
233 {
234 safe_to_run = GetPythonLock (interval);
235 if (!safe_to_run)
236 {
237 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
238 fprintf (tmp_fh,
239 "Python interpreter is locked on another thread; "
240 "please release interpreter in order to continue.\n");
241 interval = interval * 2;
242 }
243 }
244
Caroline Tice0aa2e552011-01-14 00:29:16 +0000245 m_dictionary_name.append("_dict");
246 StreamString run_string;
247 run_string.Printf ("%s = dict()", m_dictionary_name.c_str());
248 PyRun_SimpleString (run_string.GetData());
Caroline Tice5867f6b2010-10-18 18:24:17 +0000249
Caroline Tice0aa2e552011-01-14 00:29:16 +0000250 run_string.Clear();
251 run_string.Printf ("run_one_line (%s, 'import sys')", m_dictionary_name.c_str());
252 PyRun_SimpleString (run_string.GetData());
253
254 // Importing 'lldb' module calls SBDebugger::Initialize, which calls Debugger::Initialize, which increments a
255 // global debugger ref-count; therefore we need to check the ref-count before and after importing lldb, and if the
256 // ref-count increased we need to call Debugger::Terminate here to decrement the ref-count so that when the final
257 // call to Debugger::Terminate is made, the ref-count has the correct value.
258 //
259 // Bonus question: Why doesn't the ref-count always increase? Because sometimes lldb has already been imported, in
260 // which case the code inside it, including the call to SBDebugger::Initialize(), does not get executed.
Caroline Tice5867f6b2010-10-18 18:24:17 +0000261
Caroline Tice0aa2e552011-01-14 00:29:16 +0000262 int old_count = Debugger::TestDebuggerRefCount();
Chris Lattner24943d22010-06-08 16:52:24 +0000263
Caroline Tice0aa2e552011-01-14 00:29:16 +0000264 run_string.Clear();
265 run_string.Printf ("run_one_line (%s, 'import lldb')", m_dictionary_name.c_str());
266 PyRun_SimpleString (run_string.GetData());
Greg Clayton24b48ff2010-10-17 22:03:32 +0000267
Caroline Tice0aa2e552011-01-14 00:29:16 +0000268 int new_count = Debugger::TestDebuggerRefCount();
Chris Lattner24943d22010-06-08 16:52:24 +0000269
Caroline Tice0aa2e552011-01-14 00:29:16 +0000270 if (new_count > old_count)
271 Debugger::Terminate();
Caroline Tice5867f6b2010-10-18 18:24:17 +0000272
Caroline Tice0aa2e552011-01-14 00:29:16 +0000273 run_string.Clear();
274 run_string.Printf ("run_one_line (%s, 'import copy')", m_dictionary_name.c_str());
275 PyRun_SimpleString (run_string.GetData());
276
277 run_string.Clear();
278 run_string.Printf ("run_one_line (%s, 'lldb.debugger_unique_id = %d')", m_dictionary_name.c_str(),
279 interpreter.GetDebugger().GetID());
280 PyRun_SimpleString (run_string.GetData());
281
282 if (m_dbg_stdout != NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000283 {
Caroline Tice0aa2e552011-01-14 00:29:16 +0000284 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
Caroline Tice5867f6b2010-10-18 18:24:17 +0000285 }
Caroline Tice202f6b82011-01-17 21:55:19 +0000286
287 if (need_to_release_lock)
288 ReleasePythonLock();
Chris Lattner24943d22010-06-08 16:52:24 +0000289}
290
291ScriptInterpreterPython::~ScriptInterpreterPython ()
292{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000293 Debugger &debugger = GetCommandInterpreter().GetDebugger();
294
295 if (m_embedded_thread_input_reader_sp.get() != NULL)
296 {
297 m_embedded_thread_input_reader_sp->SetIsDone (true);
298 m_embedded_python_pty.CloseSlaveFileDescriptor();
299 m_pty_slave_is_open = false;
300 const InputReaderSP reader_sp = m_embedded_thread_input_reader_sp;
301 m_embedded_thread_input_reader_sp.reset();
302 debugger.PopInputReader (reader_sp);
303 }
304
305 if (m_new_sysout)
306 {
Caroline Tice202f6b82011-01-17 21:55:19 +0000307 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
308 if (!CurrentThreadHasPythonLock ())
309 {
310 while (!GetPythonLock (1))
311 fprintf (tmp_fh, "Python interpreter locked on another thread; waiting to acquire lock...\n");
312 Py_DECREF (m_new_sysout);
313 ReleasePythonLock ();
314 }
315 else
316 Py_DECREF (m_new_sysout);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000317 }
Chris Lattner24943d22010-06-08 16:52:24 +0000318}
319
Caroline Tice0aa2e552011-01-14 00:29:16 +0000320void
321ScriptInterpreterPython::ResetOutputFileHandle (FILE *fh)
322{
323 if (fh == NULL)
324 return;
325
326 m_dbg_stdout = fh;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000327
Caroline Tice202f6b82011-01-17 21:55:19 +0000328 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
329 if (!CurrentThreadHasPythonLock ())
330 {
331 while (!GetPythonLock (1))
332 fprintf (tmp_fh, "Python interpreter locked on another thread; waiting to acquire lock...\n");
333 EnterSession ();
334 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
335 LeaveSession ();
336 ReleasePythonLock ();
337 }
338 else
339 {
340 EnterSession ();
341 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
342 LeaveSession ();
343 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000344}
345
346void
347ScriptInterpreterPython::LeaveSession ()
348{
349 m_session_is_active = false;
350}
351
352void
353ScriptInterpreterPython::EnterSession ()
354{
355 // If we have already entered the session, without having officially 'left' it, then there is no need to
356 // 'enter' it again.
357
358 if (m_session_is_active)
359 return;
360
361 m_session_is_active = true;
362
Caroline Tice202f6b82011-01-17 21:55:19 +0000363 StreamString run_string;
364
365 run_string.Printf ("run_one_line (%s, 'lldb.debugger_unique_id = %d')", m_dictionary_name.c_str(),
366 GetCommandInterpreter().GetDebugger().GetID());
367 PyRun_SimpleString (run_string.GetData());
368
Caroline Tice0aa2e552011-01-14 00:29:16 +0000369
370 PyObject *sysmod = PyImport_AddModule ("sys");
371 PyObject *sysdict = PyModule_GetDict (sysmod);
372
373 if ((m_new_sysout != NULL)
374 && (sysmod != NULL)
375 && (sysdict != NULL))
376 PyDict_SetItemString (sysdict, "stdout", m_new_sysout);
377
378 if (PyErr_Occurred())
379 PyErr_Clear ();
380
Caroline Tice0aa2e552011-01-14 00:29:16 +0000381 if (!m_pty_slave_is_open)
382 {
Caroline Tice202f6b82011-01-17 21:55:19 +0000383 run_string.Clear();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000384 run_string.Printf ("run_one_line (%s, \"new_stdin = open('%s', 'r')\")", m_dictionary_name.c_str(),
385 m_pty_slave_name.c_str());
386 PyRun_SimpleString (run_string.GetData());
387 m_pty_slave_is_open = true;
388
389 run_string.Clear();
390 run_string.Printf ("run_one_line (%s, 'sys.stdin = new_stdin')", m_dictionary_name.c_str());
391 PyRun_SimpleString (run_string.GetData());
392 }
393}
394
395
Johnny Chen60dde642010-07-30 22:33:14 +0000396bool
Greg Clayton238c0a12010-09-18 01:14:36 +0000397ScriptInterpreterPython::ExecuteOneLine (const char *command, CommandReturnObject *result)
Chris Lattner24943d22010-06-08 16:52:24 +0000398{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000399 if (!m_valid_session)
400 return false;
401
Caroline Tice0aa2e552011-01-14 00:29:16 +0000402
Caroline Tice0aa2e552011-01-14 00:29:16 +0000403
Caroline Tice4a461da2011-01-14 21:09:29 +0000404 // We want to call run_one_line, passing in the dictionary and the command string. We cannot do this through
405 // PyRun_SimpleString here because the command string may contain escaped characters, and putting it inside
406 // another string to pass to PyRun_SimpleString messes up the escaping. So we use the following more complicated
407 // method to pass the command string directly down to Python.
408
409
Caroline Tice202f6b82011-01-17 21:55:19 +0000410 bool need_to_release_lock = true;
411
412 if (CurrentThreadHasPythonLock())
413 need_to_release_lock = false;
414 else if (!GetPythonLock (1))
415 {
416 fprintf ((m_dbg_stdout ? m_dbg_stdout : stdout),
417 "Python interpreter is currently locked by another thread; unable to process command.\n");
418 return false;
419 }
420
421 EnterSession ();
Caroline Tice4a461da2011-01-14 21:09:29 +0000422 bool success = false;
423
Greg Clayton63094e02010-06-23 01:19:29 +0000424 if (command)
Chris Lattner24943d22010-06-08 16:52:24 +0000425 {
Caroline Tice4a461da2011-01-14 21:09:29 +0000426 // Find the correct script interpreter dictionary in the main module.
427 PyObject *main_mod = PyImport_AddModule ("__main__");
428 PyObject *script_interpreter_dict = NULL;
429 if (main_mod != NULL)
430 {
431 PyObject *main_dict = PyModule_GetDict (main_mod);
432 if ((main_dict != NULL)
433 && PyDict_Check (main_dict))
434 {
435 // Go through the main dictionary looking for the correct python script interpreter dictionary
436 PyObject *key, *value;
437 Py_ssize_t pos = 0;
438
439 while (PyDict_Next (main_dict, &pos, &key, &value))
440 {
441 // We have stolen references to the key and value objects in the dictionary; we need to increment
442 // them now so that Python's garbage collector doesn't collect them out from under us.
443 Py_INCREF (key);
444 Py_INCREF (value);
445 if (strcmp (PyString_AsString (key), m_dictionary_name.c_str()) == 0)
446 {
447 script_interpreter_dict = value;
448 break;
449 }
450 }
451 }
452
453 if (script_interpreter_dict != NULL)
454 {
455 PyObject *pfunc = NULL;
456 PyObject *pmod = PyImport_AddModule ("embedded_interpreter");
457 if (pmod != NULL)
458 {
459 PyObject *pmod_dict = PyModule_GetDict (pmod);
460 if ((pmod_dict != NULL)
461 && PyDict_Check (pmod_dict))
462 {
463 PyObject *key, *value;
464 Py_ssize_t pos = 0;
465
466 while (PyDict_Next (pmod_dict, &pos, &key, &value))
467 {
468 Py_INCREF (key);
469 Py_INCREF (value);
470 if (strcmp (PyString_AsString (key), "run_one_line") == 0)
471 {
472 pfunc = value;
473 break;
474 }
475 }
476
477 PyObject *string_arg = PyString_FromString (command);
478 if (pfunc && string_arg && PyCallable_Check (pfunc))
479 {
480 PyObject *pargs = PyTuple_New (2);
481 if (pargs != NULL)
482 {
483 PyTuple_SetItem (pargs, 0, script_interpreter_dict);
484 PyTuple_SetItem (pargs, 1, string_arg);
485 PyObject *pvalue = PyObject_CallObject (pfunc, pargs);
486 Py_DECREF (pargs);
487 if (pvalue != NULL)
488 {
489 Py_DECREF (pvalue);
490 success = true;
491 }
492 else if (PyErr_Occurred ())
493 {
494 PyErr_Print();
495 PyErr_Clear();
496 }
497 }
498 }
499 }
500 }
501 Py_INCREF (script_interpreter_dict);
502 }
503 }
Greg Clayton63094e02010-06-23 01:19:29 +0000504
Caroline Tice0aa2e552011-01-14 00:29:16 +0000505 LeaveSession ();
506
Caroline Tice202f6b82011-01-17 21:55:19 +0000507 if (need_to_release_lock)
508 ReleasePythonLock();
509
Caroline Tice4a461da2011-01-14 21:09:29 +0000510 if (success)
Johnny Chen60dde642010-07-30 22:33:14 +0000511 return true;
512
513 // The one-liner failed. Append the error message.
514 if (result)
515 result->AppendErrorWithFormat ("python failed attempting to evaluate '%s'\n", command);
516 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000517 }
Johnny Chen60dde642010-07-30 22:33:14 +0000518
Caroline Tice0aa2e552011-01-14 00:29:16 +0000519 LeaveSession ();
Caroline Tice202f6b82011-01-17 21:55:19 +0000520
521 if (need_to_release_lock)
522 ReleasePythonLock ();
523
Johnny Chen60dde642010-07-30 22:33:14 +0000524 if (result)
525 result->AppendError ("empty command passed to python\n");
526 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000527}
528
529
530
531size_t
532ScriptInterpreterPython::InputReaderCallback
533(
534 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000535 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000536 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000537 const char *bytes,
538 size_t bytes_len
539)
540{
Caroline Tice2ade6112010-11-10 19:18:14 +0000541 lldb::thread_t embedded_interpreter_thread;
542 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
543
Chris Lattner24943d22010-06-08 16:52:24 +0000544 if (baton == NULL)
545 return 0;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000546
547 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
548
549 if (script_interpreter->m_script_lang != eScriptLanguagePython)
550 return 0;
551
Caroline Tice67637d82010-12-15 19:51:12 +0000552 FILE *out_fh = reader.GetDebugger().GetOutputFileHandle ();
553 if (out_fh == NULL)
554 out_fh = stdout;
555
Chris Lattner24943d22010-06-08 16:52:24 +0000556 switch (notification)
557 {
558 case eInputReaderActivate:
559 {
Caroline Tice67637d82010-12-15 19:51:12 +0000560 if (out_fh)
561 {
Caroline Ticea81c3672011-02-03 20:08:40 +0000562 ::fprintf (out_fh, "Python Interactive Interpreter. To exit, type 'quit()', 'exit()' or Ctrl-D.\n");
Caroline Tice67637d82010-12-15 19:51:12 +0000563 }
Chris Lattner24943d22010-06-08 16:52:24 +0000564 // Save terminal settings if we can
Caroline Ticec95c6d12010-09-14 22:49:06 +0000565 int input_fd;
Greg Clayton63094e02010-06-23 01:19:29 +0000566 FILE *input_fh = reader.GetDebugger().GetInputFileHandle();
Caroline Ticec95c6d12010-09-14 22:49:06 +0000567 if (input_fh != NULL)
Greg Clayton24b48ff2010-10-17 22:03:32 +0000568 input_fd = ::fileno (input_fh);
Caroline Ticec95c6d12010-09-14 22:49:06 +0000569 else
Greg Clayton24b48ff2010-10-17 22:03:32 +0000570 input_fd = STDIN_FILENO;
Caroline Ticec95c6d12010-09-14 22:49:06 +0000571
Greg Clayton63094e02010-06-23 01:19:29 +0000572 script_interpreter->m_termios_valid = ::tcgetattr (input_fd, &script_interpreter->m_termios) == 0;
Greg Clayton24b48ff2010-10-17 22:03:32 +0000573
Caroline Tice202f6b82011-01-17 21:55:19 +0000574 if (!CurrentThreadHasPythonLock())
575 {
576 while (!GetPythonLock(1))
577 {
578 ::fprintf (out_fh, "Python interpreter locked on another thread; waiting to acquire lock...\n");
579 }
580 script_interpreter->EnterSession ();
581 ReleasePythonLock();
582 }
583 else
584 script_interpreter->EnterSession ();
585
Caroline Tice2ade6112010-11-10 19:18:14 +0000586 char error_str[1024];
587 if (script_interpreter->m_embedded_python_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, error_str,
588 sizeof(error_str)))
589 {
590 if (log)
591 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in opening master pty (fd = %d).",
592 script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor());
593 embedded_interpreter_thread = Host::ThreadCreate ("<lldb.script-interpreter.embedded-python-loop>",
594 ScriptInterpreterPython::RunEmbeddedPythonInterpreter,
595 script_interpreter, NULL);
596 if (embedded_interpreter_thread != LLDB_INVALID_HOST_THREAD)
597 {
598 if (log)
599 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in creating thread (thread = %d)", embedded_interpreter_thread);
600 Error detach_error;
601 Host::ThreadDetach (embedded_interpreter_thread, &detach_error);
602 }
603 else
604 {
605 if (log)
606 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed in creating thread");
607 reader.SetIsDone (true);
608 }
609 }
610 else
611 {
612 if (log)
613 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed to open master pty ");
614 reader.SetIsDone (true);
615 }
Chris Lattner24943d22010-06-08 16:52:24 +0000616 }
617 break;
618
619 case eInputReaderDeactivate:
Caroline Tice0aa2e552011-01-14 00:29:16 +0000620 script_interpreter->LeaveSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000621 break;
622
623 case eInputReaderReactivate:
Caroline Tice202f6b82011-01-17 21:55:19 +0000624 if (!CurrentThreadHasPythonLock())
625 {
626 while (!GetPythonLock(1))
627 {
628 // Wait until lock is acquired.
629 }
630 script_interpreter->EnterSession ();
631 ReleasePythonLock();
632 }
633 else
634 script_interpreter->EnterSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000635 break;
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000636
637 case eInputReaderInterrupt:
638 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "raise KeyboardInterrupt\n", 24);
639 break;
640
641 case eInputReaderEndOfFile:
642 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()\n", 7);
643 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000644
645 case eInputReaderGotToken:
Caroline Tice2ade6112010-11-10 19:18:14 +0000646 if (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor() != -1)
Chris Lattner24943d22010-06-08 16:52:24 +0000647 {
Caroline Tice2ade6112010-11-10 19:18:14 +0000648 if (log)
649 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %d", bytes,
650 bytes_len);
651 if (bytes && bytes_len)
652 {
653 if ((int) bytes[0] == 4)
654 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()", 6);
655 else
656 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), bytes, bytes_len);
657 }
658 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "\n", 1);
Chris Lattner24943d22010-06-08 16:52:24 +0000659 }
Caroline Tice2ade6112010-11-10 19:18:14 +0000660 else
661 {
662 if (log)
663 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %d, Master File Descriptor is bad.",
664 bytes,
665 bytes_len);
666 reader.SetIsDone (true);
667 }
668
Chris Lattner24943d22010-06-08 16:52:24 +0000669 break;
670
671 case eInputReaderDone:
Caroline Tice0aa2e552011-01-14 00:29:16 +0000672 script_interpreter->LeaveSession ();
673
Chris Lattner24943d22010-06-08 16:52:24 +0000674 // Restore terminal settings if they were validly saved
Caroline Tice2ade6112010-11-10 19:18:14 +0000675 if (log)
676 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Done, closing down input reader.");
Greg Clayton63094e02010-06-23 01:19:29 +0000677 if (script_interpreter->m_termios_valid)
Chris Lattner24943d22010-06-08 16:52:24 +0000678 {
Caroline Ticec95c6d12010-09-14 22:49:06 +0000679 int input_fd;
680 FILE *input_fh = reader.GetDebugger().GetInputFileHandle();
681 if (input_fh != NULL)
Greg Clayton24b48ff2010-10-17 22:03:32 +0000682 input_fd = ::fileno (input_fh);
Caroline Ticec95c6d12010-09-14 22:49:06 +0000683 else
Greg Clayton24b48ff2010-10-17 22:03:32 +0000684 input_fd = STDIN_FILENO;
Caroline Ticec95c6d12010-09-14 22:49:06 +0000685
686 ::tcsetattr (input_fd, TCSANOW, &script_interpreter->m_termios);
Chris Lattner24943d22010-06-08 16:52:24 +0000687 }
Caroline Tice2ade6112010-11-10 19:18:14 +0000688 script_interpreter->m_embedded_python_pty.CloseMasterFileDescriptor();
Chris Lattner24943d22010-06-08 16:52:24 +0000689 break;
690 }
691
692 return bytes_len;
693}
694
695
696void
Greg Clayton238c0a12010-09-18 01:14:36 +0000697ScriptInterpreterPython::ExecuteInterpreterLoop ()
Chris Lattner24943d22010-06-08 16:52:24 +0000698{
699 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
700
Caroline Tice0aa2e552011-01-14 00:29:16 +0000701 Debugger &debugger = GetCommandInterpreter().GetDebugger();
Caroline Ticec95c6d12010-09-14 22:49:06 +0000702
703 // At the moment, the only time the debugger does not have an input file handle is when this is called
704 // directly from Python, in which case it is both dangerous and unnecessary (not to mention confusing) to
705 // try to embed a running interpreter loop inside the already running Python interpreter loop, so we won't
706 // do it.
707
708 if (debugger.GetInputFileHandle() == NULL)
709 return;
710
Greg Clayton63094e02010-06-23 01:19:29 +0000711 InputReaderSP reader_sp (new InputReader(debugger));
Chris Lattner24943d22010-06-08 16:52:24 +0000712 if (reader_sp)
713 {
714 Error error (reader_sp->Initialize (ScriptInterpreterPython::InputReaderCallback,
715 this, // baton
716 eInputReaderGranularityLine, // token size, to pass to callback function
717 NULL, // end token
718 NULL, // prompt
719 true)); // echo input
720
721 if (error.Success())
722 {
Greg Clayton63094e02010-06-23 01:19:29 +0000723 debugger.PushInputReader (reader_sp);
Caroline Tice2ade6112010-11-10 19:18:14 +0000724 m_embedded_thread_input_reader_sp = reader_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000725 }
726 }
727}
728
729bool
730ScriptInterpreterPython::ExecuteOneLineWithReturn (const char *in_string,
731 ScriptInterpreter::ReturnType return_type,
732 void *ret_value)
733{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000734
Caroline Tice202f6b82011-01-17 21:55:19 +0000735 bool need_to_release_lock = true;
736
737 if (CurrentThreadHasPythonLock())
738 need_to_release_lock = false;
739 else if (!GetPythonLock (1))
740 {
741 fprintf ((m_dbg_stdout ? m_dbg_stdout : stdout),
742 "Python interpreter is currently locked by another thread; unable to process command.\n");
743 return false;
744 }
745
746 EnterSession ();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000747
Chris Lattner24943d22010-06-08 16:52:24 +0000748 PyObject *py_return = NULL;
749 PyObject *mainmod = PyImport_AddModule ("__main__");
750 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000751 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000752 PyObject *py_error = NULL;
753 bool ret_success;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000754 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000755 int success;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000756
757 if (PyDict_Check (globals))
758 {
759 PyObject *key, *value;
760 Py_ssize_t pos = 0;
761
762 int i = 0;
763 while (PyDict_Next (globals, &pos, &key, &value))
764 {
765 // We have stolen references to the key and value objects in the dictionary; we need to increment them now
766 // so that Python's garbage collector doesn't collect them out from under us.
767 Py_INCREF (key);
768 Py_INCREF (value);
769 char *c_str = PyString_AsString (key);
770 if (strcmp (c_str, m_dictionary_name.c_str()) == 0)
771 locals = value;
772 ++i;
773 }
774 }
Chris Lattner24943d22010-06-08 16:52:24 +0000775
Caroline Tice0aa2e552011-01-14 00:29:16 +0000776 if (locals == NULL)
777 {
778 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
779 should_decrement_locals = true;
780 }
781
782 if (locals == NULL)
783 {
784 locals = globals;
785 should_decrement_locals = false;
786 }
787
788 py_error = PyErr_Occurred();
789 if (py_error != NULL)
790 PyErr_Clear();
791
Chris Lattner24943d22010-06-08 16:52:24 +0000792 if (in_string != NULL)
793 {
794 py_return = PyRun_String (in_string, Py_eval_input, globals, locals);
795 if (py_return == NULL)
796 {
797 py_error = PyErr_Occurred ();
798 if (py_error != NULL)
799 PyErr_Clear ();
800
801 py_return = PyRun_String (in_string, Py_single_input, globals, locals);
802 }
803
Caroline Tice0aa2e552011-01-14 00:29:16 +0000804 if (locals != NULL
805 && should_decrement_locals)
806 Py_DECREF (locals);
807
Chris Lattner24943d22010-06-08 16:52:24 +0000808 if (py_return != NULL)
809 {
810 switch (return_type)
811 {
812 case eCharPtr: // "char *"
813 {
814 const char format[3] = "s#";
815 success = PyArg_Parse (py_return, format, (char **) &ret_value);
816 break;
817 }
818 case eBool:
819 {
820 const char format[2] = "b";
821 success = PyArg_Parse (py_return, format, (bool *) ret_value);
822 break;
823 }
824 case eShortInt:
825 {
826 const char format[2] = "h";
827 success = PyArg_Parse (py_return, format, (short *) ret_value);
828 break;
829 }
830 case eShortIntUnsigned:
831 {
832 const char format[2] = "H";
833 success = PyArg_Parse (py_return, format, (unsigned short *) ret_value);
834 break;
835 }
836 case eInt:
837 {
838 const char format[2] = "i";
839 success = PyArg_Parse (py_return, format, (int *) ret_value);
840 break;
841 }
842 case eIntUnsigned:
843 {
844 const char format[2] = "I";
845 success = PyArg_Parse (py_return, format, (unsigned int *) ret_value);
846 break;
847 }
848 case eLongInt:
849 {
850 const char format[2] = "l";
851 success = PyArg_Parse (py_return, format, (long *) ret_value);
852 break;
853 }
854 case eLongIntUnsigned:
855 {
856 const char format[2] = "k";
857 success = PyArg_Parse (py_return, format, (unsigned long *) ret_value);
858 break;
859 }
860 case eLongLong:
861 {
862 const char format[2] = "L";
863 success = PyArg_Parse (py_return, format, (long long *) ret_value);
864 break;
865 }
866 case eLongLongUnsigned:
867 {
868 const char format[2] = "K";
869 success = PyArg_Parse (py_return, format, (unsigned long long *) ret_value);
870 break;
871 }
872 case eFloat:
873 {
874 const char format[2] = "f";
875 success = PyArg_Parse (py_return, format, (float *) ret_value);
876 break;
877 }
878 case eDouble:
879 {
880 const char format[2] = "d";
881 success = PyArg_Parse (py_return, format, (double *) ret_value);
882 break;
883 }
884 case eChar:
885 {
886 const char format[2] = "c";
887 success = PyArg_Parse (py_return, format, (char *) ret_value);
888 break;
889 }
890 default:
891 {}
892 }
893 Py_DECREF (py_return);
894 if (success)
895 ret_success = true;
896 else
897 ret_success = false;
898 }
899 }
900
901 py_error = PyErr_Occurred();
902 if (py_error != NULL)
903 {
904 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
905 PyErr_Print ();
906 PyErr_Clear();
907 ret_success = false;
908 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000909
910 LeaveSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000911
Caroline Tice202f6b82011-01-17 21:55:19 +0000912 if (need_to_release_lock)
913 ReleasePythonLock();
914
Chris Lattner24943d22010-06-08 16:52:24 +0000915 return ret_success;
916}
917
918bool
919ScriptInterpreterPython::ExecuteMultipleLines (const char *in_string)
920{
Caroline Tice202f6b82011-01-17 21:55:19 +0000921 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
922 bool need_to_release_lock = true;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000923
Caroline Tice202f6b82011-01-17 21:55:19 +0000924 if (CurrentThreadHasPythonLock())
925 need_to_release_lock = false;
926 else
927 {
928 while (!GetPythonLock (1))
929 fprintf (tmp_fh, "Python interpreter locked on another thread; waiting to acquire lock...\n");
930 }
931
932 EnterSession ();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000933
Chris Lattner24943d22010-06-08 16:52:24 +0000934 bool success = false;
935 PyObject *py_return = NULL;
936 PyObject *mainmod = PyImport_AddModule ("__main__");
937 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000938 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000939 PyObject *py_error = NULL;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000940 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000941
Caroline Tice0aa2e552011-01-14 00:29:16 +0000942 if (PyDict_Check (globals))
943 {
944 PyObject *key, *value;
945 Py_ssize_t pos = 0;
946
947 while (PyDict_Next (globals, &pos, &key, &value))
948 {
949 // We have stolen references to the key and value objects in the dictionary; we need to increment them now
950 // so that Python's garbage collector doesn't collect them out from under us.
951 Py_INCREF (key);
952 Py_INCREF (value);
953 if (strcmp (PyString_AsString (key), m_dictionary_name.c_str()) == 0)
954 locals = value;
955 }
956 }
957
958 if (locals == NULL)
959 {
960 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
961 should_decrement_locals = true;
962 }
963
964 if (locals == NULL)
965 {
966 locals = globals;
967 should_decrement_locals = false;
968 }
969
970 py_error = PyErr_Occurred();
971 if (py_error != NULL)
972 PyErr_Clear();
973
Chris Lattner24943d22010-06-08 16:52:24 +0000974 if (in_string != NULL)
975 {
976 struct _node *compiled_node = PyParser_SimpleParseString (in_string, Py_file_input);
977 if (compiled_node)
978 {
979 PyCodeObject *compiled_code = PyNode_Compile (compiled_node, "temp.py");
980 if (compiled_code)
981 {
982 py_return = PyEval_EvalCode (compiled_code, globals, locals);
983 if (py_return != NULL)
984 {
985 success = true;
986 Py_DECREF (py_return);
987 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000988 if (locals && should_decrement_locals)
989 Py_DECREF (locals);
Chris Lattner24943d22010-06-08 16:52:24 +0000990 }
991 }
992 }
993
994 py_error = PyErr_Occurred ();
995 if (py_error != NULL)
996 {
997 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
998 PyErr_Print ();
999 PyErr_Clear();
1000 success = false;
1001 }
1002
Caroline Tice0aa2e552011-01-14 00:29:16 +00001003 LeaveSession ();
1004
Caroline Tice202f6b82011-01-17 21:55:19 +00001005 if (need_to_release_lock)
1006 ReleasePythonLock();
1007
Chris Lattner24943d22010-06-08 16:52:24 +00001008 return success;
1009}
1010
1011static const char *g_reader_instructions = "Enter your Python command(s). Type 'DONE' to end.";
1012
1013size_t
1014ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback
1015(
1016 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +00001017 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +00001018 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +00001019 const char *bytes,
1020 size_t bytes_len
1021)
1022{
1023 static StringList commands_in_progress;
1024
Greg Clayton63094e02010-06-23 01:19:29 +00001025 FILE *out_fh = reader.GetDebugger().GetOutputFileHandle();
Caroline Ticec95c6d12010-09-14 22:49:06 +00001026 if (out_fh == NULL)
1027 out_fh = stdout;
1028
Chris Lattner24943d22010-06-08 16:52:24 +00001029 switch (notification)
1030 {
1031 case eInputReaderActivate:
1032 {
1033 commands_in_progress.Clear();
1034 if (out_fh)
1035 {
1036 ::fprintf (out_fh, "%s\n", g_reader_instructions);
Greg Clayton63094e02010-06-23 01:19:29 +00001037 if (reader.GetPrompt())
1038 ::fprintf (out_fh, "%s", reader.GetPrompt());
Caroline Ticef81b4c52010-10-27 18:34:42 +00001039 ::fflush (out_fh);
Chris Lattner24943d22010-06-08 16:52:24 +00001040 }
1041 }
1042 break;
1043
1044 case eInputReaderDeactivate:
1045 break;
1046
1047 case eInputReaderReactivate:
Greg Clayton63094e02010-06-23 01:19:29 +00001048 if (reader.GetPrompt() && out_fh)
Caroline Ticef81b4c52010-10-27 18:34:42 +00001049 {
Greg Clayton63094e02010-06-23 01:19:29 +00001050 ::fprintf (out_fh, "%s", reader.GetPrompt());
Caroline Ticef81b4c52010-10-27 18:34:42 +00001051 ::fflush (out_fh);
1052 }
Chris Lattner24943d22010-06-08 16:52:24 +00001053 break;
1054
1055 case eInputReaderGotToken:
1056 {
1057 std::string temp_string (bytes, bytes_len);
1058 commands_in_progress.AppendString (temp_string.c_str());
Greg Clayton63094e02010-06-23 01:19:29 +00001059 if (out_fh && !reader.IsDone() && reader.GetPrompt())
Caroline Ticef81b4c52010-10-27 18:34:42 +00001060 {
Greg Clayton63094e02010-06-23 01:19:29 +00001061 ::fprintf (out_fh, "%s", reader.GetPrompt());
Caroline Ticef81b4c52010-10-27 18:34:42 +00001062 ::fflush (out_fh);
1063 }
Chris Lattner24943d22010-06-08 16:52:24 +00001064 }
1065 break;
1066
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001067 case eInputReaderEndOfFile:
1068 case eInputReaderInterrupt:
1069 // Control-c (SIGINT) & control-d both mean finish & exit.
1070 reader.SetIsDone(true);
1071
1072 // Control-c (SIGINT) ALSO means cancel; do NOT create a breakpoint command.
1073 if (notification == eInputReaderInterrupt)
1074 commands_in_progress.Clear();
1075
1076 // Fall through here...
1077
Chris Lattner24943d22010-06-08 16:52:24 +00001078 case eInputReaderDone:
1079 {
1080 BreakpointOptions *bp_options = (BreakpointOptions *)baton;
1081 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1082 data_ap->user_source.AppendList (commands_in_progress);
1083 if (data_ap.get())
1084 {
Greg Clayton63094e02010-06-23 01:19:29 +00001085 ScriptInterpreter *interpreter = reader.GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
Chris Lattner24943d22010-06-08 16:52:24 +00001086 if (interpreter)
1087 {
1088 if (interpreter->GenerateBreakpointCommandCallbackData (data_ap->user_source,
1089 data_ap->script_source))
1090 {
1091 if (data_ap->script_source.GetSize() == 1)
1092 {
1093 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1094 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
1095 }
1096 }
Caroline Ticeb447e842010-09-21 19:25:28 +00001097 else
Caroline Tice5136f942010-09-27 21:35:15 +00001098 ::fprintf (out_fh, "Warning: No command attached to breakpoint.\n");
Chris Lattner24943d22010-06-08 16:52:24 +00001099 }
1100 else
1101 {
1102 // FIXME: Error processing.
1103 }
1104 }
1105 }
1106 break;
1107
1108 }
1109
1110 return bytes_len;
1111}
1112
1113void
Greg Clayton238c0a12010-09-18 01:14:36 +00001114ScriptInterpreterPython::CollectDataForBreakpointCommandCallback (BreakpointOptions *bp_options,
Chris Lattner24943d22010-06-08 16:52:24 +00001115 CommandReturnObject &result)
1116{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001117 Debugger &debugger = GetCommandInterpreter().GetDebugger();
1118
Greg Clayton63094e02010-06-23 01:19:29 +00001119 InputReaderSP reader_sp (new InputReader (debugger));
Chris Lattner24943d22010-06-08 16:52:24 +00001120
1121 if (reader_sp)
1122 {
1123 Error err = reader_sp->Initialize (
1124 ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback,
1125 bp_options, // baton
1126 eInputReaderGranularityLine, // token size, for feeding data to callback function
1127 "DONE", // end token
1128 "> ", // prompt
1129 true); // echo input
1130
1131 if (err.Success())
Greg Clayton63094e02010-06-23 01:19:29 +00001132 debugger.PushInputReader (reader_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001133 else
1134 {
1135 result.AppendError (err.AsCString());
1136 result.SetStatus (eReturnStatusFailed);
1137 }
1138 }
1139 else
1140 {
1141 result.AppendError("out of memory");
1142 result.SetStatus (eReturnStatusFailed);
1143 }
1144}
1145
Johnny Chen3e0571b2010-09-11 00:23:59 +00001146// Set a Python one-liner as the callback for the breakpoint.
Johnny Chend1c2dca2010-09-10 18:21:10 +00001147void
Greg Clayton238c0a12010-09-18 01:14:36 +00001148ScriptInterpreterPython::SetBreakpointCommandCallback (BreakpointOptions *bp_options,
Johnny Chend1c2dca2010-09-10 18:21:10 +00001149 const char *oneliner)
1150{
1151 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1152
1153 // It's necessary to set both user_source and script_source to the oneliner.
1154 // The former is used to generate callback description (as in breakpoint command list)
1155 // while the latter is used for Python to interpret during the actual callback.
Caroline Tice5136f942010-09-27 21:35:15 +00001156
Johnny Chend1c2dca2010-09-10 18:21:10 +00001157 data_ap->user_source.AppendString (oneliner);
Johnny Chend1c2dca2010-09-10 18:21:10 +00001158
Caroline Tice5136f942010-09-27 21:35:15 +00001159 if (GenerateBreakpointCommandCallbackData (data_ap->user_source, data_ap->script_source))
1160 {
1161 if (data_ap->script_source.GetSize() == 1)
1162 {
1163 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1164 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
1165 }
1166 }
1167
Johnny Chend1c2dca2010-09-10 18:21:10 +00001168 return;
1169}
1170
Chris Lattner24943d22010-06-08 16:52:24 +00001171bool
1172ScriptInterpreterPython::ExportFunctionDefinitionToInterpreter (StringList &function_def)
1173{
1174 // Convert StringList to one long, newline delimited, const char *.
1175 std::string function_def_string;
1176
1177 int num_lines = function_def.GetSize();
1178
1179 for (int i = 0; i < num_lines; ++i)
1180 {
1181 function_def_string.append (function_def.GetStringAtIndex(i));
1182 if (function_def_string.at (function_def_string.length() - 1) != '\n')
1183 function_def_string.append ("\n");
1184
1185 }
1186
1187 return ExecuteMultipleLines (function_def_string.c_str());
1188}
1189
1190bool
1191ScriptInterpreterPython::GenerateBreakpointCommandCallbackData (StringList &user_input, StringList &callback_data)
1192{
1193 static int num_created_functions = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001194 user_input.RemoveBlankLines ();
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001195 int num_lines = user_input.GetSize ();
1196 StreamString sstr;
Chris Lattner24943d22010-06-08 16:52:24 +00001197
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001198 // Check to see if we have any data; if not, just return.
1199 if (user_input.GetSize() == 0)
1200 return false;
1201
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001202 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1203 // frame and breakpoint location as parameters to the function.
Caroline Ticeb447e842010-09-21 19:25:28 +00001204
Caroline Ticeb447e842010-09-21 19:25:28 +00001205
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001206 sstr.Printf ("lldb_autogen_python_bp_callback_func_%d", num_created_functions);
1207 ++num_created_functions;
1208 std::string auto_generated_function_name = sstr.GetData();
Caroline Ticeb447e842010-09-21 19:25:28 +00001209
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001210 sstr.Clear();
Caroline Ticeb447e842010-09-21 19:25:28 +00001211 StringList auto_generated_function;
Caroline Ticeb447e842010-09-21 19:25:28 +00001212
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001213 // Create the function name & definition string.
1214
Caroline Tice0aa2e552011-01-14 00:29:16 +00001215 sstr.Printf ("def %s (frame, bp_loc, dict):", auto_generated_function_name.c_str());
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001216 auto_generated_function.AppendString (sstr.GetData());
Caroline Tice0aa2e552011-01-14 00:29:16 +00001217
1218 // Pre-pend code for setting up the session dictionary.
1219
1220 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1221 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1222 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1223 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1224 // global dictionary.
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001225
1226 // Wrap everything up inside the function, increasing the indentation.
Chris Lattner24943d22010-06-08 16:52:24 +00001227
1228 for (int i = 0; i < num_lines; ++i)
1229 {
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001230 sstr.Clear ();
1231 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1232 auto_generated_function.AppendString (sstr.GetData());
Caroline Ticeb447e842010-09-21 19:25:28 +00001233 }
Chris Lattner24943d22010-06-08 16:52:24 +00001234
Caroline Tice0aa2e552011-01-14 00:29:16 +00001235 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1236 // got written to the values in the global dictionary, not the session dictionary).
1237
1238 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1239 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1240 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1241 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1242
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001243 // Verify that the results are valid Python.
Chris Lattner24943d22010-06-08 16:52:24 +00001244
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001245 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
Caroline Ticeb447e842010-09-21 19:25:28 +00001246 {
Caroline Ticeb447e842010-09-21 19:25:28 +00001247 return false;
Chris Lattner24943d22010-06-08 16:52:24 +00001248 }
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001249
1250 // Store the name of the auto-generated function to be called.
1251
1252 callback_data.AppendString (auto_generated_function_name.c_str());
1253 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001254}
1255
Greg Clayton5144f382010-10-07 17:14:24 +00001256bool
1257ScriptInterpreterPython::BreakpointCallbackFunction
1258(
1259 void *baton,
1260 StoppointCallbackContext *context,
1261 user_id_t break_id,
1262 user_id_t break_loc_id
1263)
1264{
1265 BreakpointOptions::CommandData *bp_option_data = (BreakpointOptions::CommandData *) baton;
1266 const char *python_function_name = bp_option_data->script_source.GetStringAtIndex (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001267
1268 if (!context)
1269 return true;
1270
1271 Target *target = context->exe_ctx.target;
1272
1273 if (!target)
1274 return true;
1275
1276 Debugger &debugger = target->GetDebugger();
1277 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1278 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1279
1280 if (!script_interpreter)
1281 return true;
Greg Clayton5144f382010-10-07 17:14:24 +00001282
1283 if (python_function_name != NULL
1284 && python_function_name[0] != '\0')
1285 {
1286 Thread *thread = context->exe_ctx.thread;
Greg Clayton5144f382010-10-07 17:14:24 +00001287 const StackFrameSP stop_frame_sp = thread->GetStackFrameSPForStackFramePtr (context->exe_ctx.frame);
1288 BreakpointSP breakpoint_sp = target->GetBreakpointByID (break_id);
1289 const BreakpointLocationSP bp_loc_sp = breakpoint_sp->FindLocationByID (break_loc_id);
1290
1291 SBFrame sb_frame (stop_frame_sp);
1292 SBBreakpointLocation sb_bp_loc (bp_loc_sp);
1293
1294 if (sb_bp_loc.IsValid() || sb_frame.IsValid())
Caroline Tice0aa2e552011-01-14 00:29:16 +00001295 {
Caroline Tice202f6b82011-01-17 21:55:19 +00001296 bool ret_val = true;
1297 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
1298 if (CurrentThreadHasPythonLock())
1299 {
1300 python_interpreter->EnterSession ();
1301 ret_val = LLDBSWIGPythonBreakpointCallbackFunction(python_function_name,
1302 python_interpreter->m_dictionary_name.c_str(),
1303 sb_frame, sb_bp_loc);
1304 python_interpreter->LeaveSession ();
1305 }
1306 else
1307 {
1308 while (!GetPythonLock (1))
1309 fprintf (tmp_fh,
1310 "Python interpreter locked on another thread; waiting to acquire lock...\n");
1311 python_interpreter->EnterSession ();
1312 ret_val = LLDBSWIGPythonBreakpointCallbackFunction(python_function_name,
1313 python_interpreter->m_dictionary_name.c_str(),
1314 sb_frame, sb_bp_loc);
1315 python_interpreter->LeaveSession ();
1316 ReleasePythonLock ();
1317 }
Caroline Tice0aa2e552011-01-14 00:29:16 +00001318 return ret_val;
1319 }
Greg Clayton5144f382010-10-07 17:14:24 +00001320 }
1321 // We currently always true so we stop in case anything goes wrong when
1322 // trying to call the script function
1323 return true;
1324}
Caroline Tice2ade6112010-11-10 19:18:14 +00001325
1326lldb::thread_result_t
1327ScriptInterpreterPython::RunEmbeddedPythonInterpreter (lldb::thread_arg_t baton)
1328{
1329 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
1330
1331 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
1332
1333 if (log)
1334 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread starting...", baton);
1335
1336 char error_str[1024];
1337 const char *pty_slave_name = script_interpreter->m_embedded_python_pty.GetSlaveName (error_str, sizeof (error_str));
Caroline Tice202f6b82011-01-17 21:55:19 +00001338 bool need_to_release_lock = true;
1339 bool safe_to_run = false;
Caroline Tice0aa2e552011-01-14 00:29:16 +00001340
Caroline Tice202f6b82011-01-17 21:55:19 +00001341 if (CurrentThreadHasPythonLock())
1342 {
1343 safe_to_run = true;
1344 need_to_release_lock = false;
1345 }
1346 else
1347 {
1348 int interval = 1;
1349 safe_to_run = GetPythonLock (interval);
1350 while (!safe_to_run)
1351 {
1352 interval = interval * 2;
1353 safe_to_run = GetPythonLock (interval);
1354 }
1355 }
1356
1357 if (pty_slave_name != NULL && safe_to_run)
1358 {
Caroline Tice2ade6112010-11-10 19:18:14 +00001359 StreamString run_string;
Caroline Tice2ade6112010-11-10 19:18:14 +00001360
Caroline Tice202f6b82011-01-17 21:55:19 +00001361 script_interpreter->EnterSession ();
1362
Caroline Tice0aa2e552011-01-14 00:29:16 +00001363 run_string.Printf ("run_one_line (%s, 'save_stderr = sys.stderr')", script_interpreter->m_dictionary_name.c_str());
1364 PyRun_SimpleString (run_string.GetData());
1365 run_string.Clear ();
1366
1367 run_string.Printf ("run_one_line (%s, 'sys.stderr = sys.stdout')", script_interpreter->m_dictionary_name.c_str());
1368 PyRun_SimpleString (run_string.GetData());
1369 run_string.Clear ();
1370
1371 run_string.Printf ("run_one_line (%s, 'save_stdin = sys.stdin')", script_interpreter->m_dictionary_name.c_str());
1372 PyRun_SimpleString (run_string.GetData());
1373 run_string.Clear ();
1374
1375 run_string.Printf ("run_one_line (%s, \"sys.stdin = open ('%s', 'r')\")", script_interpreter->m_dictionary_name.c_str(),
1376 pty_slave_name);
1377 PyRun_SimpleString (run_string.GetData());
1378 run_string.Clear ();
1379
Caroline Tice2ade6112010-11-10 19:18:14 +00001380 // The following call drops into the embedded interpreter loop and stays there until the
1381 // user chooses to exit from the Python interpreter.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001382
1383 run_string.Printf ("run_python_interpreter (%s)", script_interpreter->m_dictionary_name.c_str());
1384 PyRun_SimpleString (run_string.GetData());
1385 run_string.Clear ();
Caroline Tice2ade6112010-11-10 19:18:14 +00001386
Caroline Tice0aa2e552011-01-14 00:29:16 +00001387 run_string.Printf ("run_one_line (%s, 'sys.stdin = save_stdin')", script_interpreter->m_dictionary_name.c_str());
1388 PyRun_SimpleString (run_string.GetData());
1389 run_string.Clear();
1390
1391 run_string.Printf ("run_one_line (%s, 'sys.stderr = save_stderr')", script_interpreter->m_dictionary_name.c_str());
1392 PyRun_SimpleString (run_string.GetData());
1393 run_string.Clear();
Caroline Tice202f6b82011-01-17 21:55:19 +00001394
1395 script_interpreter->LeaveSession ();
1396
Caroline Tice2ade6112010-11-10 19:18:14 +00001397 }
1398
Caroline Tice202f6b82011-01-17 21:55:19 +00001399 if (!safe_to_run)
1400 fprintf ((script_interpreter->m_dbg_stdout ? script_interpreter->m_dbg_stdout : stdout),
1401 "Python interpreter locked on another thread; unable to acquire lock.\n");
1402
1403 if (need_to_release_lock)
1404 ReleasePythonLock ();
1405
Caroline Tice2ade6112010-11-10 19:18:14 +00001406 if (script_interpreter->m_embedded_thread_input_reader_sp)
1407 script_interpreter->m_embedded_thread_input_reader_sp->SetIsDone (true);
1408
1409 script_interpreter->m_embedded_python_pty.CloseSlaveFileDescriptor();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001410
1411 script_interpreter->m_pty_slave_is_open = false;
Caroline Tice2ade6112010-11-10 19:18:14 +00001412
1413 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT);
1414 if (log)
1415 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread exiting...", baton);
1416
1417
Caroline Tice0aa2e552011-01-14 00:29:16 +00001418 // Clean up the input reader and make the debugger pop it off the stack.
1419 Debugger &debugger = script_interpreter->GetCommandInterpreter().GetDebugger();
Caroline Tice2ade6112010-11-10 19:18:14 +00001420 const InputReaderSP reader_sp = script_interpreter->m_embedded_thread_input_reader_sp;
1421 script_interpreter->m_embedded_thread_input_reader_sp.reset();
1422 debugger.PopInputReader (reader_sp);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001423
Caroline Tice2ade6112010-11-10 19:18:14 +00001424 return NULL;
1425}
1426
1427
Caroline Tice0aa2e552011-01-14 00:29:16 +00001428void
1429ScriptInterpreterPython::Initialize ()
1430{
Caroline Tice2ade6112010-11-10 19:18:14 +00001431
Caroline Tice0aa2e552011-01-14 00:29:16 +00001432 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
1433
1434 int input_fd = STDIN_FILENO;
1435
1436 struct termios stdin_termios;
1437 bool valid_termios = ::tcgetattr (input_fd, &stdin_termios) == 0;
1438
1439 // Find the module that owns this code and use that path we get to
1440 // set the PYTHONPATH appropriately.
1441
1442 FileSpec file_spec;
1443 char python_dir_path[PATH_MAX];
1444 if (Host::GetLLDBPath (ePathTypePythonDir, file_spec))
1445 {
1446 std::string python_path;
1447 const char *curr_python_path = ::getenv ("PYTHONPATH");
1448 if (curr_python_path)
1449 {
1450 // We have a current value for PYTHONPATH, so lets append to it
1451 python_path.append (curr_python_path);
1452 }
1453
1454 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
1455 {
1456 if (!python_path.empty())
1457 python_path.append (1, ':');
1458 python_path.append (python_dir_path);
1459 }
1460
1461 if (Host::GetLLDBPath (ePathTypeLLDBShlibDir, file_spec))
1462 {
1463 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
1464 {
1465 if (!python_path.empty())
1466 python_path.append (1, ':');
1467 python_path.append (python_dir_path);
1468 }
1469 }
1470 const char *pathon_path_env_cstr = python_path.c_str();
1471 ::setenv ("PYTHONPATH", pathon_path_env_cstr, 1);
1472 }
1473
1474 Py_Initialize ();
1475
1476 PyObject *compiled_module = Py_CompileString (embedded_interpreter_string,
1477 "embedded_interpreter.py",
1478 Py_file_input);
1479
1480 PyObject *py_error = PyErr_Occurred ();
1481 if (py_error != NULL)
1482 {
1483 PyErr_Print();
1484 PyErr_Clear();
1485 }
1486
1487
1488 // This function is in the C++ output file generated by SWIG after it is
1489 // run on all of the headers in "lldb/API/SB*.h"
1490 init_lldb ();
1491
1492 // Update the path python uses to search for modules to include the current directory.
1493
1494 int success = PyRun_SimpleString ("import sys");
1495 success = PyRun_SimpleString ("sys.path.append ('.')");
1496
1497 PyObject *pmod = NULL;
1498
1499 if (compiled_module)
1500 {
1501 pmod = PyImport_ExecCodeModule (const_cast<char*> ("embedded_interpreter"),
1502 compiled_module);
1503 Py_DECREF (compiled_module);
1504 }
1505
1506 if (pmod != NULL)
1507 {
1508 PyRun_SimpleString ("from embedded_interpreter import run_python_interpreter");
1509 PyRun_SimpleString ("from embedded_interpreter import run_one_line");
1510 PyRun_SimpleString ("import sys");
1511 PyRun_SimpleString ("from termios import *");
1512 Py_DECREF (pmod);
1513 }
1514
1515 if (valid_termios)
1516 ::tcsetattr (input_fd, TCSANOW, &stdin_termios);
1517}
1518
1519void
1520ScriptInterpreterPython::Terminate ()
1521{
1522 // We are intentionally NOT calling Py_Finalize here (this would be the logical place to call it). Calling
1523 // Py_Finalize here causes test suite runs to seg fault: The test suite runs in Python. It registers
1524 // SBDebugger::Terminate to be called 'at_exit'. When the test suite Python harness finishes up, it calls
1525 // Py_Finalize, which calls all the 'at_exit' registered functions. SBDebugger::Terminate calls Debugger::Terminate,
1526 // which calls lldb::Terminate, which calls ScriptInterpreter::Terminate, which calls
1527 // ScriptInterpreterPython::Terminate. So if we call Py_Finalize here, we end up with Py_Finalize being called from
1528 // within Py_Finalize, which results in a seg fault.
1529 //
1530 // Since this function only gets called when lldb is shutting down and going away anyway, the fact that we don't
1531 // actually call Py_Finalize should not cause any problems (everything should shut down/go away anyway when the
1532 // process exits).
1533 //
1534// Py_Finalize ();
1535}