blob: c6d4504b170488d7161d06da26aeac8bb92ff6df [file] [log] [blame]
Chris Lattner24943d22010-06-08 16:52:24 +00001//===-- ScriptInterpreterPython.cpp -----------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10// In order to guarantee correct working with Python, Python.h *MUST* be
11// the *FIRST* header file included:
12
Caroline Tice5790e062010-10-28 21:51:20 +000013#if defined (__APPLE__)
14#include <Python/Python.h>
15#else
Chris Lattner24943d22010-06-08 16:52:24 +000016#include <Python.h>
Caroline Tice5790e062010-10-28 21:51:20 +000017#endif
Chris Lattner24943d22010-06-08 16:52:24 +000018
19#include "lldb/Interpreter/ScriptInterpreterPython.h"
20
21
22#include <sys/ioctl.h>
23#include <termios.h>
24#include <stdlib.h>
25#include <stdio.h>
26
27#include <string>
28
Greg Clayton5144f382010-10-07 17:14:24 +000029#include "lldb/API/SBFrame.h"
30#include "lldb/API/SBBreakpointLocation.h"
Chris Lattner24943d22010-06-08 16:52:24 +000031#include "lldb/Breakpoint/Breakpoint.h"
32#include "lldb/Breakpoint/BreakpointLocation.h"
Greg Clayton63094e02010-06-23 01:19:29 +000033#include "lldb/Breakpoint/StoppointCallbackContext.h"
Chris Lattner24943d22010-06-08 16:52:24 +000034#include "lldb/Core/Debugger.h"
35#include "lldb/Core/FileSpec.h"
36#include "lldb/Core/InputReader.h"
37#include "lldb/Core/Stream.h"
38#include "lldb/Core/StreamString.h"
39#include "lldb/Core/Timer.h"
40#include "lldb/Host/Host.h"
41#include "lldb/Interpreter/CommandInterpreter.h"
42#include "lldb/Interpreter/CommandReturnObject.h"
Greg Clayton63094e02010-06-23 01:19:29 +000043#include "lldb/Core/Debugger.h"
Chris Lattner24943d22010-06-08 16:52:24 +000044#include "lldb/Target/Process.h"
Greg Clayton5144f382010-10-07 17:14:24 +000045#include "lldb/Target/Thread.h"
Chris Lattner24943d22010-06-08 16:52:24 +000046
Greg Clayton121f3312010-07-07 18:40:03 +000047// This function is in the C++ output file generated by SWIG after it is
48// run on all of the headers in "lldb/API/SB*.h"
Chris Lattner24943d22010-06-08 16:52:24 +000049extern "C" void init_lldb (void);
50
Greg Clayton5144f382010-10-07 17:14:24 +000051extern "C" bool
52LLDBSWIGPythonBreakpointCallbackFunction
53(
54 const char *python_function_name,
Caroline Tice0aa2e552011-01-14 00:29:16 +000055 const char *session_dictionary_name,
Greg Clayton5144f382010-10-07 17:14:24 +000056 lldb::SBFrame& sb_frame,
57 lldb::SBBreakpointLocation& sb_bp_loc
58);
59
Chris Lattner24943d22010-06-08 16:52:24 +000060using namespace lldb;
61using namespace lldb_private;
62
63const char embedded_interpreter_string[] =
64"import readline\n\
65import code\n\
66import sys\n\
67import traceback\n\
68\n\
69class SimpleREPL(code.InteractiveConsole):\n\
70 def __init__(self, prompt, dict):\n\
71 code.InteractiveConsole.__init__(self,dict)\n\
72 self.prompt = prompt\n\
73 self.loop_exit = False\n\
74 self.dict = dict\n\
75\n\
76 def interact(self):\n\
77 try:\n\
78 sys.ps1\n\
79 except AttributeError:\n\
80 sys.ps1 = \">>> \"\n\
81 try:\n\
82 sys.ps2\n\
83 except AttributeError:\n\
84 sys.ps2 = \"... \"\n\
85\n\
86 while not self.loop_exit:\n\
87 try:\n\
88 self.read_py_command()\n\
89 except (SystemExit, EOFError):\n\
90 # EOF while in Python just breaks out to top level.\n\
91 self.write('\\n')\n\
92 self.loop_exit = True\n\
93 break\n\
94 except KeyboardInterrupt:\n\
95 self.write(\"\\nKeyboardInterrupt\\n\")\n\
96 self.resetbuffer()\n\
97 more = 0\n\
98 except:\n\
99 traceback.print_exc()\n\
100\n\
101 def process_input (self, in_str):\n\
102 # Canonicalize the format of the input string\n\
103 temp_str = in_str\n\
104 temp_str.strip(' \t')\n\
105 words = temp_str.split()\n\
106 temp_str = ('').join(words)\n\
107\n\
108 # Check the input string to see if it was the quit\n\
109 # command. If so, intercept it, so that it doesn't\n\
110 # close stdin on us!\n\
Jason Molendaa8a5e562010-06-09 21:56:00 +0000111 if (temp_str.lower() == \"quit()\" or temp_str.lower() == \"exit()\"):\n\
Chris Lattner24943d22010-06-08 16:52:24 +0000112 self.loop_exit = True\n\
113 in_str = \"raise SystemExit \"\n\
114 return in_str\n\
115\n\
116 def my_raw_input (self, prompt):\n\
117 stream = sys.stdout\n\
118 stream.write (prompt)\n\
119 stream.flush ()\n\
120 try:\n\
121 line = sys.stdin.readline()\n\
122 except KeyboardInterrupt:\n\
123 line = \" \\n\"\n\
124 except (SystemExit, EOFError):\n\
125 line = \"quit()\\n\"\n\
126 if not line:\n\
127 raise EOFError\n\
128 if line[-1] == '\\n':\n\
129 line = line[:-1]\n\
130 return line\n\
131\n\
132 def read_py_command(self):\n\
133 # Read off a complete Python command.\n\
134 more = 0\n\
135 while 1:\n\
136 if more:\n\
137 prompt = sys.ps2\n\
138 else:\n\
139 prompt = sys.ps1\n\
140 line = self.my_raw_input(prompt)\n\
141 # Can be None if sys.stdin was redefined\n\
142 encoding = getattr(sys.stdin, \"encoding\", None)\n\
143 if encoding and not isinstance(line, unicode):\n\
144 line = line.decode(encoding)\n\
145 line = self.process_input (line)\n\
146 more = self.push(line)\n\
147 if not more:\n\
148 break\n\
149\n\
Caroline Tice0aa2e552011-01-14 00:29:16 +0000150 def one_line (self, input):\n\
151 line = self.process_input (input)\n\
152 more = self.push(line)\n\
153 if more:\n\
154 self.write (\"Input not a complete line.\")\n\
155 self.resetbuffer()\n\
156 more = 0\n\
157\n\
Chris Lattner24943d22010-06-08 16:52:24 +0000158def run_python_interpreter (dict):\n\
159 # Pass in the dictionary, for continuity from one session to the next.\n\
160 repl = SimpleREPL('>>> ', dict)\n\
Caroline Tice0aa2e552011-01-14 00:29:16 +0000161 repl.interact()\n\
162\n\
163def run_one_line (dict, input_string):\n\
164 repl = SimpleREPL ('', dict)\n\
165 repl.one_line (input_string)\n";
Chris Lattner24943d22010-06-08 16:52:24 +0000166
167static int
168_check_and_flush (FILE *stream)
169{
170 int prev_fail = ferror (stream);
171 return fflush (stream) || prev_fail ? EOF : 0;
172}
173
Caroline Tice0aa2e552011-01-14 00:29:16 +0000174static Mutex &
175GetPythonMutex ()
176{
177 static Mutex g_python_mutex (Mutex::eMutexTypeRecursive);
178 return g_python_mutex;
179}
180
Greg Clayton63094e02010-06-23 01:19:29 +0000181ScriptInterpreterPython::ScriptInterpreterPython (CommandInterpreter &interpreter) :
Greg Clayton238c0a12010-09-18 01:14:36 +0000182 ScriptInterpreter (interpreter, eScriptLanguagePython),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000183 m_embedded_python_pty (),
184 m_embedded_thread_input_reader_sp (),
185 m_dbg_stdout (interpreter.GetDebugger().GetOutputFileHandle()),
186 m_new_sysout (NULL),
187 m_dictionary_name (interpreter.GetDebugger().GetInstanceName().AsCString()),
Caroline Tice2ade6112010-11-10 19:18:14 +0000188 m_termios (),
189 m_termios_valid (false),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000190 m_session_is_active (false),
191 m_pty_slave_is_open (false),
192 m_valid_session (true)
Chris Lattner24943d22010-06-08 16:52:24 +0000193{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000194 Mutex::Locker locker (GetPythonMutex());
Chris Lattner24943d22010-06-08 16:52:24 +0000195
Caroline Tice0aa2e552011-01-14 00:29:16 +0000196 m_dictionary_name.append("_dict");
197 StreamString run_string;
198 run_string.Printf ("%s = dict()", m_dictionary_name.c_str());
199 PyRun_SimpleString (run_string.GetData());
Caroline Tice5867f6b2010-10-18 18:24:17 +0000200
Caroline Tice0aa2e552011-01-14 00:29:16 +0000201 run_string.Clear();
202 run_string.Printf ("run_one_line (%s, 'import sys')", m_dictionary_name.c_str());
203 PyRun_SimpleString (run_string.GetData());
204
205 // Importing 'lldb' module calls SBDebugger::Initialize, which calls Debugger::Initialize, which increments a
206 // global debugger ref-count; therefore we need to check the ref-count before and after importing lldb, and if the
207 // ref-count increased we need to call Debugger::Terminate here to decrement the ref-count so that when the final
208 // call to Debugger::Terminate is made, the ref-count has the correct value.
209 //
210 // Bonus question: Why doesn't the ref-count always increase? Because sometimes lldb has already been imported, in
211 // which case the code inside it, including the call to SBDebugger::Initialize(), does not get executed.
Caroline Tice5867f6b2010-10-18 18:24:17 +0000212
Caroline Tice0aa2e552011-01-14 00:29:16 +0000213 int old_count = Debugger::TestDebuggerRefCount();
Chris Lattner24943d22010-06-08 16:52:24 +0000214
Caroline Tice0aa2e552011-01-14 00:29:16 +0000215 run_string.Clear();
216 run_string.Printf ("run_one_line (%s, 'import lldb')", m_dictionary_name.c_str());
217 PyRun_SimpleString (run_string.GetData());
Greg Clayton24b48ff2010-10-17 22:03:32 +0000218
Caroline Tice0aa2e552011-01-14 00:29:16 +0000219 int new_count = Debugger::TestDebuggerRefCount();
Chris Lattner24943d22010-06-08 16:52:24 +0000220
Caroline Tice0aa2e552011-01-14 00:29:16 +0000221 if (new_count > old_count)
222 Debugger::Terminate();
Caroline Tice5867f6b2010-10-18 18:24:17 +0000223
Caroline Tice0aa2e552011-01-14 00:29:16 +0000224 run_string.Clear();
225 run_string.Printf ("run_one_line (%s, 'import copy')", m_dictionary_name.c_str());
226 PyRun_SimpleString (run_string.GetData());
227
228 run_string.Clear();
229 run_string.Printf ("run_one_line (%s, 'lldb.debugger_unique_id = %d')", m_dictionary_name.c_str(),
230 interpreter.GetDebugger().GetID());
231 PyRun_SimpleString (run_string.GetData());
232
233 if (m_dbg_stdout != NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000234 {
Caroline Tice0aa2e552011-01-14 00:29:16 +0000235 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
Caroline Tice5867f6b2010-10-18 18:24:17 +0000236 }
Chris Lattner24943d22010-06-08 16:52:24 +0000237}
238
239ScriptInterpreterPython::~ScriptInterpreterPython ()
240{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000241 Debugger &debugger = GetCommandInterpreter().GetDebugger();
242
243 if (m_embedded_thread_input_reader_sp.get() != NULL)
244 {
245 m_embedded_thread_input_reader_sp->SetIsDone (true);
246 m_embedded_python_pty.CloseSlaveFileDescriptor();
247 m_pty_slave_is_open = false;
248 const InputReaderSP reader_sp = m_embedded_thread_input_reader_sp;
249 m_embedded_thread_input_reader_sp.reset();
250 debugger.PopInputReader (reader_sp);
251 }
252
253 if (m_new_sysout)
254 {
255 Mutex::Locker locker(GetPythonMutex());
256 Py_DECREF (m_new_sysout);
257 }
Chris Lattner24943d22010-06-08 16:52:24 +0000258}
259
Caroline Tice0aa2e552011-01-14 00:29:16 +0000260void
261ScriptInterpreterPython::ResetOutputFileHandle (FILE *fh)
262{
263 if (fh == NULL)
264 return;
265
266 m_dbg_stdout = fh;
267 Mutex::Locker locker (GetPythonMutex());
268
269 EnterSession ();
270 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
271 LeaveSession ();
272}
273
274void
275ScriptInterpreterPython::LeaveSession ()
276{
277 m_session_is_active = false;
278}
279
280void
281ScriptInterpreterPython::EnterSession ()
282{
283 // If we have already entered the session, without having officially 'left' it, then there is no need to
284 // 'enter' it again.
285
286 if (m_session_is_active)
287 return;
288
289 m_session_is_active = true;
290
291 Mutex::Locker locker (GetPythonMutex());
292
293 PyObject *sysmod = PyImport_AddModule ("sys");
294 PyObject *sysdict = PyModule_GetDict (sysmod);
295
296 if ((m_new_sysout != NULL)
297 && (sysmod != NULL)
298 && (sysdict != NULL))
299 PyDict_SetItemString (sysdict, "stdout", m_new_sysout);
300
301 if (PyErr_Occurred())
302 PyErr_Clear ();
303
304 StreamString run_string;
305 if (!m_pty_slave_is_open)
306 {
307 run_string.Printf ("run_one_line (%s, \"new_stdin = open('%s', 'r')\")", m_dictionary_name.c_str(),
308 m_pty_slave_name.c_str());
309 PyRun_SimpleString (run_string.GetData());
310 m_pty_slave_is_open = true;
311
312 run_string.Clear();
313 run_string.Printf ("run_one_line (%s, 'sys.stdin = new_stdin')", m_dictionary_name.c_str());
314 PyRun_SimpleString (run_string.GetData());
315 }
316}
317
318
Johnny Chen60dde642010-07-30 22:33:14 +0000319bool
Greg Clayton238c0a12010-09-18 01:14:36 +0000320ScriptInterpreterPython::ExecuteOneLine (const char *command, CommandReturnObject *result)
Chris Lattner24943d22010-06-08 16:52:24 +0000321{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000322 if (!m_valid_session)
323 return false;
324
325 EnterSession ();
326
327 Mutex::Locker locker (GetPythonMutex());
328
Greg Clayton63094e02010-06-23 01:19:29 +0000329 if (command)
Chris Lattner24943d22010-06-08 16:52:24 +0000330 {
Greg Clayton63094e02010-06-23 01:19:29 +0000331 int success;
332
Caroline Tice0aa2e552011-01-14 00:29:16 +0000333 StreamString sstr;
334 sstr.Printf ("run_one_line (%s, '%s')", m_dictionary_name.c_str(), command);
335 success = PyRun_SimpleString (sstr.GetData());
336
337 LeaveSession ();
338
Johnny Chen60dde642010-07-30 22:33:14 +0000339 if (success == 0)
340 return true;
341
342 // The one-liner failed. Append the error message.
343 if (result)
344 result->AppendErrorWithFormat ("python failed attempting to evaluate '%s'\n", command);
345 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000346 }
Johnny Chen60dde642010-07-30 22:33:14 +0000347
Caroline Tice0aa2e552011-01-14 00:29:16 +0000348 LeaveSession ();
Johnny Chen60dde642010-07-30 22:33:14 +0000349 if (result)
350 result->AppendError ("empty command passed to python\n");
351 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000352}
353
354
355
356size_t
357ScriptInterpreterPython::InputReaderCallback
358(
359 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000360 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000361 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000362 const char *bytes,
363 size_t bytes_len
364)
365{
Caroline Tice2ade6112010-11-10 19:18:14 +0000366 lldb::thread_t embedded_interpreter_thread;
367 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
368
Chris Lattner24943d22010-06-08 16:52:24 +0000369 if (baton == NULL)
370 return 0;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000371
372 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
373
374 if (script_interpreter->m_script_lang != eScriptLanguagePython)
375 return 0;
376
Caroline Tice67637d82010-12-15 19:51:12 +0000377 FILE *out_fh = reader.GetDebugger().GetOutputFileHandle ();
378 if (out_fh == NULL)
379 out_fh = stdout;
380
Chris Lattner24943d22010-06-08 16:52:24 +0000381 switch (notification)
382 {
383 case eInputReaderActivate:
384 {
Caroline Tice67637d82010-12-15 19:51:12 +0000385 if (out_fh)
386 {
387 ::fprintf (out_fh, "Python Interactive Interpreter. To exit Python, type 'quit()' or 'exit()'.\n");
388 ::fprintf (out_fh, "Do NOT use Ctrl-D (EOF) to exit, as that will cause the lldb debugger to hang.\n");
389 }
Chris Lattner24943d22010-06-08 16:52:24 +0000390 // Save terminal settings if we can
Caroline Ticec95c6d12010-09-14 22:49:06 +0000391 int input_fd;
Greg Clayton63094e02010-06-23 01:19:29 +0000392 FILE *input_fh = reader.GetDebugger().GetInputFileHandle();
Caroline Ticec95c6d12010-09-14 22:49:06 +0000393 if (input_fh != NULL)
Greg Clayton24b48ff2010-10-17 22:03:32 +0000394 input_fd = ::fileno (input_fh);
Caroline Ticec95c6d12010-09-14 22:49:06 +0000395 else
Greg Clayton24b48ff2010-10-17 22:03:32 +0000396 input_fd = STDIN_FILENO;
Caroline Ticec95c6d12010-09-14 22:49:06 +0000397
Greg Clayton63094e02010-06-23 01:19:29 +0000398 script_interpreter->m_termios_valid = ::tcgetattr (input_fd, &script_interpreter->m_termios) == 0;
Greg Clayton24b48ff2010-10-17 22:03:32 +0000399
Caroline Tice2ade6112010-11-10 19:18:14 +0000400 char error_str[1024];
401 if (script_interpreter->m_embedded_python_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, error_str,
402 sizeof(error_str)))
403 {
404 if (log)
405 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in opening master pty (fd = %d).",
406 script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor());
407 embedded_interpreter_thread = Host::ThreadCreate ("<lldb.script-interpreter.embedded-python-loop>",
408 ScriptInterpreterPython::RunEmbeddedPythonInterpreter,
409 script_interpreter, NULL);
410 if (embedded_interpreter_thread != LLDB_INVALID_HOST_THREAD)
411 {
412 if (log)
413 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in creating thread (thread = %d)", embedded_interpreter_thread);
414 Error detach_error;
415 Host::ThreadDetach (embedded_interpreter_thread, &detach_error);
416 }
417 else
418 {
419 if (log)
420 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed in creating thread");
421 reader.SetIsDone (true);
422 }
423 }
424 else
425 {
426 if (log)
427 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed to open master pty ");
428 reader.SetIsDone (true);
429 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000430 script_interpreter->EnterSession ();
Caroline Tice2ade6112010-11-10 19:18:14 +0000431
Chris Lattner24943d22010-06-08 16:52:24 +0000432 }
433 break;
434
435 case eInputReaderDeactivate:
Caroline Tice0aa2e552011-01-14 00:29:16 +0000436 script_interpreter->LeaveSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000437 break;
438
439 case eInputReaderReactivate:
Caroline Tice0aa2e552011-01-14 00:29:16 +0000440 script_interpreter->EnterSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000441 break;
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000442
443 case eInputReaderInterrupt:
444 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "raise KeyboardInterrupt\n", 24);
445 break;
446
447 case eInputReaderEndOfFile:
448 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()\n", 7);
449 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000450
451 case eInputReaderGotToken:
Caroline Tice2ade6112010-11-10 19:18:14 +0000452 if (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor() != -1)
Chris Lattner24943d22010-06-08 16:52:24 +0000453 {
Caroline Tice2ade6112010-11-10 19:18:14 +0000454 if (log)
455 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %d", bytes,
456 bytes_len);
457 if (bytes && bytes_len)
458 {
459 if ((int) bytes[0] == 4)
460 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()", 6);
461 else
462 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), bytes, bytes_len);
463 }
464 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "\n", 1);
Chris Lattner24943d22010-06-08 16:52:24 +0000465 }
Caroline Tice2ade6112010-11-10 19:18:14 +0000466 else
467 {
468 if (log)
469 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %d, Master File Descriptor is bad.",
470 bytes,
471 bytes_len);
472 reader.SetIsDone (true);
473 }
474
Chris Lattner24943d22010-06-08 16:52:24 +0000475 break;
476
477 case eInputReaderDone:
Caroline Tice0aa2e552011-01-14 00:29:16 +0000478 script_interpreter->LeaveSession ();
479
Chris Lattner24943d22010-06-08 16:52:24 +0000480 // Restore terminal settings if they were validly saved
Caroline Tice2ade6112010-11-10 19:18:14 +0000481 if (log)
482 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Done, closing down input reader.");
Greg Clayton63094e02010-06-23 01:19:29 +0000483 if (script_interpreter->m_termios_valid)
Chris Lattner24943d22010-06-08 16:52:24 +0000484 {
Caroline Ticec95c6d12010-09-14 22:49:06 +0000485 int input_fd;
486 FILE *input_fh = reader.GetDebugger().GetInputFileHandle();
487 if (input_fh != NULL)
Greg Clayton24b48ff2010-10-17 22:03:32 +0000488 input_fd = ::fileno (input_fh);
Caroline Ticec95c6d12010-09-14 22:49:06 +0000489 else
Greg Clayton24b48ff2010-10-17 22:03:32 +0000490 input_fd = STDIN_FILENO;
Caroline Ticec95c6d12010-09-14 22:49:06 +0000491
492 ::tcsetattr (input_fd, TCSANOW, &script_interpreter->m_termios);
Chris Lattner24943d22010-06-08 16:52:24 +0000493 }
Caroline Tice2ade6112010-11-10 19:18:14 +0000494 script_interpreter->m_embedded_python_pty.CloseMasterFileDescriptor();
Chris Lattner24943d22010-06-08 16:52:24 +0000495 break;
496 }
497
498 return bytes_len;
499}
500
501
502void
Greg Clayton238c0a12010-09-18 01:14:36 +0000503ScriptInterpreterPython::ExecuteInterpreterLoop ()
Chris Lattner24943d22010-06-08 16:52:24 +0000504{
505 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
506
Caroline Tice0aa2e552011-01-14 00:29:16 +0000507 Debugger &debugger = GetCommandInterpreter().GetDebugger();
Caroline Ticec95c6d12010-09-14 22:49:06 +0000508
509 // At the moment, the only time the debugger does not have an input file handle is when this is called
510 // directly from Python, in which case it is both dangerous and unnecessary (not to mention confusing) to
511 // try to embed a running interpreter loop inside the already running Python interpreter loop, so we won't
512 // do it.
513
514 if (debugger.GetInputFileHandle() == NULL)
515 return;
516
Greg Clayton63094e02010-06-23 01:19:29 +0000517 InputReaderSP reader_sp (new InputReader(debugger));
Chris Lattner24943d22010-06-08 16:52:24 +0000518 if (reader_sp)
519 {
520 Error error (reader_sp->Initialize (ScriptInterpreterPython::InputReaderCallback,
521 this, // baton
522 eInputReaderGranularityLine, // token size, to pass to callback function
523 NULL, // end token
524 NULL, // prompt
525 true)); // echo input
526
527 if (error.Success())
528 {
Greg Clayton63094e02010-06-23 01:19:29 +0000529 debugger.PushInputReader (reader_sp);
Caroline Tice2ade6112010-11-10 19:18:14 +0000530 m_embedded_thread_input_reader_sp = reader_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000531 }
532 }
533}
534
535bool
536ScriptInterpreterPython::ExecuteOneLineWithReturn (const char *in_string,
537 ScriptInterpreter::ReturnType return_type,
538 void *ret_value)
539{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000540 EnterSession ();
541
542 Mutex::Locker locker (GetPythonMutex());
543
Chris Lattner24943d22010-06-08 16:52:24 +0000544 PyObject *py_return = NULL;
545 PyObject *mainmod = PyImport_AddModule ("__main__");
546 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000547 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000548 PyObject *py_error = NULL;
549 bool ret_success;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000550 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000551 int success;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000552
553 if (PyDict_Check (globals))
554 {
555 PyObject *key, *value;
556 Py_ssize_t pos = 0;
557
558 int i = 0;
559 while (PyDict_Next (globals, &pos, &key, &value))
560 {
561 // We have stolen references to the key and value objects in the dictionary; we need to increment them now
562 // so that Python's garbage collector doesn't collect them out from under us.
563 Py_INCREF (key);
564 Py_INCREF (value);
565 char *c_str = PyString_AsString (key);
566 if (strcmp (c_str, m_dictionary_name.c_str()) == 0)
567 locals = value;
568 ++i;
569 }
570 }
Chris Lattner24943d22010-06-08 16:52:24 +0000571
Caroline Tice0aa2e552011-01-14 00:29:16 +0000572 if (locals == NULL)
573 {
574 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
575 should_decrement_locals = true;
576 }
577
578 if (locals == NULL)
579 {
580 locals = globals;
581 should_decrement_locals = false;
582 }
583
584 py_error = PyErr_Occurred();
585 if (py_error != NULL)
586 PyErr_Clear();
587
Chris Lattner24943d22010-06-08 16:52:24 +0000588 if (in_string != NULL)
589 {
590 py_return = PyRun_String (in_string, Py_eval_input, globals, locals);
591 if (py_return == NULL)
592 {
593 py_error = PyErr_Occurred ();
594 if (py_error != NULL)
595 PyErr_Clear ();
596
597 py_return = PyRun_String (in_string, Py_single_input, globals, locals);
598 }
599
Caroline Tice0aa2e552011-01-14 00:29:16 +0000600 if (locals != NULL
601 && should_decrement_locals)
602 Py_DECREF (locals);
603
Chris Lattner24943d22010-06-08 16:52:24 +0000604 if (py_return != NULL)
605 {
606 switch (return_type)
607 {
608 case eCharPtr: // "char *"
609 {
610 const char format[3] = "s#";
611 success = PyArg_Parse (py_return, format, (char **) &ret_value);
612 break;
613 }
614 case eBool:
615 {
616 const char format[2] = "b";
617 success = PyArg_Parse (py_return, format, (bool *) ret_value);
618 break;
619 }
620 case eShortInt:
621 {
622 const char format[2] = "h";
623 success = PyArg_Parse (py_return, format, (short *) ret_value);
624 break;
625 }
626 case eShortIntUnsigned:
627 {
628 const char format[2] = "H";
629 success = PyArg_Parse (py_return, format, (unsigned short *) ret_value);
630 break;
631 }
632 case eInt:
633 {
634 const char format[2] = "i";
635 success = PyArg_Parse (py_return, format, (int *) ret_value);
636 break;
637 }
638 case eIntUnsigned:
639 {
640 const char format[2] = "I";
641 success = PyArg_Parse (py_return, format, (unsigned int *) ret_value);
642 break;
643 }
644 case eLongInt:
645 {
646 const char format[2] = "l";
647 success = PyArg_Parse (py_return, format, (long *) ret_value);
648 break;
649 }
650 case eLongIntUnsigned:
651 {
652 const char format[2] = "k";
653 success = PyArg_Parse (py_return, format, (unsigned long *) ret_value);
654 break;
655 }
656 case eLongLong:
657 {
658 const char format[2] = "L";
659 success = PyArg_Parse (py_return, format, (long long *) ret_value);
660 break;
661 }
662 case eLongLongUnsigned:
663 {
664 const char format[2] = "K";
665 success = PyArg_Parse (py_return, format, (unsigned long long *) ret_value);
666 break;
667 }
668 case eFloat:
669 {
670 const char format[2] = "f";
671 success = PyArg_Parse (py_return, format, (float *) ret_value);
672 break;
673 }
674 case eDouble:
675 {
676 const char format[2] = "d";
677 success = PyArg_Parse (py_return, format, (double *) ret_value);
678 break;
679 }
680 case eChar:
681 {
682 const char format[2] = "c";
683 success = PyArg_Parse (py_return, format, (char *) ret_value);
684 break;
685 }
686 default:
687 {}
688 }
689 Py_DECREF (py_return);
690 if (success)
691 ret_success = true;
692 else
693 ret_success = false;
694 }
695 }
696
697 py_error = PyErr_Occurred();
698 if (py_error != NULL)
699 {
700 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
701 PyErr_Print ();
702 PyErr_Clear();
703 ret_success = false;
704 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000705
706 LeaveSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000707
708 return ret_success;
709}
710
711bool
712ScriptInterpreterPython::ExecuteMultipleLines (const char *in_string)
713{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000714 EnterSession ();
715
716 Mutex::Locker locker (GetPythonMutex());
717
Chris Lattner24943d22010-06-08 16:52:24 +0000718 bool success = false;
719 PyObject *py_return = NULL;
720 PyObject *mainmod = PyImport_AddModule ("__main__");
721 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000722 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000723 PyObject *py_error = NULL;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000724 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000725
Caroline Tice0aa2e552011-01-14 00:29:16 +0000726 if (PyDict_Check (globals))
727 {
728 PyObject *key, *value;
729 Py_ssize_t pos = 0;
730
731 while (PyDict_Next (globals, &pos, &key, &value))
732 {
733 // We have stolen references to the key and value objects in the dictionary; we need to increment them now
734 // so that Python's garbage collector doesn't collect them out from under us.
735 Py_INCREF (key);
736 Py_INCREF (value);
737 if (strcmp (PyString_AsString (key), m_dictionary_name.c_str()) == 0)
738 locals = value;
739 }
740 }
741
742 if (locals == NULL)
743 {
744 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
745 should_decrement_locals = true;
746 }
747
748 if (locals == NULL)
749 {
750 locals = globals;
751 should_decrement_locals = false;
752 }
753
754 py_error = PyErr_Occurred();
755 if (py_error != NULL)
756 PyErr_Clear();
757
Chris Lattner24943d22010-06-08 16:52:24 +0000758 if (in_string != NULL)
759 {
760 struct _node *compiled_node = PyParser_SimpleParseString (in_string, Py_file_input);
761 if (compiled_node)
762 {
763 PyCodeObject *compiled_code = PyNode_Compile (compiled_node, "temp.py");
764 if (compiled_code)
765 {
766 py_return = PyEval_EvalCode (compiled_code, globals, locals);
767 if (py_return != NULL)
768 {
769 success = true;
770 Py_DECREF (py_return);
771 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000772 if (locals && should_decrement_locals)
773 Py_DECREF (locals);
Chris Lattner24943d22010-06-08 16:52:24 +0000774 }
775 }
776 }
777
778 py_error = PyErr_Occurred ();
779 if (py_error != NULL)
780 {
781 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
782 PyErr_Print ();
783 PyErr_Clear();
784 success = false;
785 }
786
Caroline Tice0aa2e552011-01-14 00:29:16 +0000787 LeaveSession ();
788
Chris Lattner24943d22010-06-08 16:52:24 +0000789 return success;
790}
791
792static const char *g_reader_instructions = "Enter your Python command(s). Type 'DONE' to end.";
793
794size_t
795ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback
796(
797 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000798 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000799 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000800 const char *bytes,
801 size_t bytes_len
802)
803{
804 static StringList commands_in_progress;
805
Greg Clayton63094e02010-06-23 01:19:29 +0000806 FILE *out_fh = reader.GetDebugger().GetOutputFileHandle();
Caroline Ticec95c6d12010-09-14 22:49:06 +0000807 if (out_fh == NULL)
808 out_fh = stdout;
809
Chris Lattner24943d22010-06-08 16:52:24 +0000810 switch (notification)
811 {
812 case eInputReaderActivate:
813 {
814 commands_in_progress.Clear();
815 if (out_fh)
816 {
817 ::fprintf (out_fh, "%s\n", g_reader_instructions);
Greg Clayton63094e02010-06-23 01:19:29 +0000818 if (reader.GetPrompt())
819 ::fprintf (out_fh, "%s", reader.GetPrompt());
Caroline Ticef81b4c52010-10-27 18:34:42 +0000820 ::fflush (out_fh);
Chris Lattner24943d22010-06-08 16:52:24 +0000821 }
822 }
823 break;
824
825 case eInputReaderDeactivate:
826 break;
827
828 case eInputReaderReactivate:
Greg Clayton63094e02010-06-23 01:19:29 +0000829 if (reader.GetPrompt() && out_fh)
Caroline Ticef81b4c52010-10-27 18:34:42 +0000830 {
Greg Clayton63094e02010-06-23 01:19:29 +0000831 ::fprintf (out_fh, "%s", reader.GetPrompt());
Caroline Ticef81b4c52010-10-27 18:34:42 +0000832 ::fflush (out_fh);
833 }
Chris Lattner24943d22010-06-08 16:52:24 +0000834 break;
835
836 case eInputReaderGotToken:
837 {
838 std::string temp_string (bytes, bytes_len);
839 commands_in_progress.AppendString (temp_string.c_str());
Greg Clayton63094e02010-06-23 01:19:29 +0000840 if (out_fh && !reader.IsDone() && reader.GetPrompt())
Caroline Ticef81b4c52010-10-27 18:34:42 +0000841 {
Greg Clayton63094e02010-06-23 01:19:29 +0000842 ::fprintf (out_fh, "%s", reader.GetPrompt());
Caroline Ticef81b4c52010-10-27 18:34:42 +0000843 ::fflush (out_fh);
844 }
Chris Lattner24943d22010-06-08 16:52:24 +0000845 }
846 break;
847
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000848 case eInputReaderEndOfFile:
849 case eInputReaderInterrupt:
850 // Control-c (SIGINT) & control-d both mean finish & exit.
851 reader.SetIsDone(true);
852
853 // Control-c (SIGINT) ALSO means cancel; do NOT create a breakpoint command.
854 if (notification == eInputReaderInterrupt)
855 commands_in_progress.Clear();
856
857 // Fall through here...
858
Chris Lattner24943d22010-06-08 16:52:24 +0000859 case eInputReaderDone:
860 {
861 BreakpointOptions *bp_options = (BreakpointOptions *)baton;
862 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
863 data_ap->user_source.AppendList (commands_in_progress);
864 if (data_ap.get())
865 {
Greg Clayton63094e02010-06-23 01:19:29 +0000866 ScriptInterpreter *interpreter = reader.GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
Chris Lattner24943d22010-06-08 16:52:24 +0000867 if (interpreter)
868 {
869 if (interpreter->GenerateBreakpointCommandCallbackData (data_ap->user_source,
870 data_ap->script_source))
871 {
872 if (data_ap->script_source.GetSize() == 1)
873 {
874 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
875 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
876 }
877 }
Caroline Ticeb447e842010-09-21 19:25:28 +0000878 else
Caroline Tice5136f942010-09-27 21:35:15 +0000879 ::fprintf (out_fh, "Warning: No command attached to breakpoint.\n");
Chris Lattner24943d22010-06-08 16:52:24 +0000880 }
881 else
882 {
883 // FIXME: Error processing.
884 }
885 }
886 }
887 break;
888
889 }
890
891 return bytes_len;
892}
893
894void
Greg Clayton238c0a12010-09-18 01:14:36 +0000895ScriptInterpreterPython::CollectDataForBreakpointCommandCallback (BreakpointOptions *bp_options,
Chris Lattner24943d22010-06-08 16:52:24 +0000896 CommandReturnObject &result)
897{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000898 Debugger &debugger = GetCommandInterpreter().GetDebugger();
899
Greg Clayton63094e02010-06-23 01:19:29 +0000900 InputReaderSP reader_sp (new InputReader (debugger));
Chris Lattner24943d22010-06-08 16:52:24 +0000901
902 if (reader_sp)
903 {
904 Error err = reader_sp->Initialize (
905 ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback,
906 bp_options, // baton
907 eInputReaderGranularityLine, // token size, for feeding data to callback function
908 "DONE", // end token
909 "> ", // prompt
910 true); // echo input
911
912 if (err.Success())
Greg Clayton63094e02010-06-23 01:19:29 +0000913 debugger.PushInputReader (reader_sp);
Chris Lattner24943d22010-06-08 16:52:24 +0000914 else
915 {
916 result.AppendError (err.AsCString());
917 result.SetStatus (eReturnStatusFailed);
918 }
919 }
920 else
921 {
922 result.AppendError("out of memory");
923 result.SetStatus (eReturnStatusFailed);
924 }
925}
926
Johnny Chen3e0571b2010-09-11 00:23:59 +0000927// Set a Python one-liner as the callback for the breakpoint.
Johnny Chend1c2dca2010-09-10 18:21:10 +0000928void
Greg Clayton238c0a12010-09-18 01:14:36 +0000929ScriptInterpreterPython::SetBreakpointCommandCallback (BreakpointOptions *bp_options,
Johnny Chend1c2dca2010-09-10 18:21:10 +0000930 const char *oneliner)
931{
932 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
933
934 // It's necessary to set both user_source and script_source to the oneliner.
935 // The former is used to generate callback description (as in breakpoint command list)
936 // while the latter is used for Python to interpret during the actual callback.
Caroline Tice5136f942010-09-27 21:35:15 +0000937
Johnny Chend1c2dca2010-09-10 18:21:10 +0000938 data_ap->user_source.AppendString (oneliner);
Johnny Chend1c2dca2010-09-10 18:21:10 +0000939
Caroline Tice5136f942010-09-27 21:35:15 +0000940 if (GenerateBreakpointCommandCallbackData (data_ap->user_source, data_ap->script_source))
941 {
942 if (data_ap->script_source.GetSize() == 1)
943 {
944 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
945 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
946 }
947 }
948
Johnny Chend1c2dca2010-09-10 18:21:10 +0000949 return;
950}
951
Chris Lattner24943d22010-06-08 16:52:24 +0000952bool
953ScriptInterpreterPython::ExportFunctionDefinitionToInterpreter (StringList &function_def)
954{
955 // Convert StringList to one long, newline delimited, const char *.
956 std::string function_def_string;
957
958 int num_lines = function_def.GetSize();
959
960 for (int i = 0; i < num_lines; ++i)
961 {
962 function_def_string.append (function_def.GetStringAtIndex(i));
963 if (function_def_string.at (function_def_string.length() - 1) != '\n')
964 function_def_string.append ("\n");
965
966 }
967
968 return ExecuteMultipleLines (function_def_string.c_str());
969}
970
971bool
972ScriptInterpreterPython::GenerateBreakpointCommandCallbackData (StringList &user_input, StringList &callback_data)
973{
974 static int num_created_functions = 0;
Chris Lattner24943d22010-06-08 16:52:24 +0000975 user_input.RemoveBlankLines ();
Caroline Tice59c5d5d2010-09-27 18:00:20 +0000976 int num_lines = user_input.GetSize ();
977 StreamString sstr;
Chris Lattner24943d22010-06-08 16:52:24 +0000978
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000979 // Check to see if we have any data; if not, just return.
980 if (user_input.GetSize() == 0)
981 return false;
982
Caroline Tice59c5d5d2010-09-27 18:00:20 +0000983 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
984 // frame and breakpoint location as parameters to the function.
Caroline Ticeb447e842010-09-21 19:25:28 +0000985
Caroline Ticeb447e842010-09-21 19:25:28 +0000986
Caroline Tice59c5d5d2010-09-27 18:00:20 +0000987 sstr.Printf ("lldb_autogen_python_bp_callback_func_%d", num_created_functions);
988 ++num_created_functions;
989 std::string auto_generated_function_name = sstr.GetData();
Caroline Ticeb447e842010-09-21 19:25:28 +0000990
Caroline Tice59c5d5d2010-09-27 18:00:20 +0000991 sstr.Clear();
Caroline Ticeb447e842010-09-21 19:25:28 +0000992 StringList auto_generated_function;
Caroline Ticeb447e842010-09-21 19:25:28 +0000993
Caroline Tice59c5d5d2010-09-27 18:00:20 +0000994 // Create the function name & definition string.
995
Caroline Tice0aa2e552011-01-14 00:29:16 +0000996 sstr.Printf ("def %s (frame, bp_loc, dict):", auto_generated_function_name.c_str());
Caroline Tice59c5d5d2010-09-27 18:00:20 +0000997 auto_generated_function.AppendString (sstr.GetData());
Caroline Tice0aa2e552011-01-14 00:29:16 +0000998
999 // Pre-pend code for setting up the session dictionary.
1000
1001 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1002 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1003 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1004 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1005 // global dictionary.
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001006
1007 // Wrap everything up inside the function, increasing the indentation.
Chris Lattner24943d22010-06-08 16:52:24 +00001008
1009 for (int i = 0; i < num_lines; ++i)
1010 {
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001011 sstr.Clear ();
1012 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1013 auto_generated_function.AppendString (sstr.GetData());
Caroline Ticeb447e842010-09-21 19:25:28 +00001014 }
Chris Lattner24943d22010-06-08 16:52:24 +00001015
Caroline Tice0aa2e552011-01-14 00:29:16 +00001016 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1017 // got written to the values in the global dictionary, not the session dictionary).
1018
1019 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1020 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1021 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1022 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1023
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001024 // Verify that the results are valid Python.
Chris Lattner24943d22010-06-08 16:52:24 +00001025
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001026 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
Caroline Ticeb447e842010-09-21 19:25:28 +00001027 {
Caroline Ticeb447e842010-09-21 19:25:28 +00001028 return false;
Chris Lattner24943d22010-06-08 16:52:24 +00001029 }
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001030
1031 // Store the name of the auto-generated function to be called.
1032
1033 callback_data.AppendString (auto_generated_function_name.c_str());
1034 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001035}
1036
Greg Clayton5144f382010-10-07 17:14:24 +00001037bool
1038ScriptInterpreterPython::BreakpointCallbackFunction
1039(
1040 void *baton,
1041 StoppointCallbackContext *context,
1042 user_id_t break_id,
1043 user_id_t break_loc_id
1044)
1045{
1046 BreakpointOptions::CommandData *bp_option_data = (BreakpointOptions::CommandData *) baton;
1047 const char *python_function_name = bp_option_data->script_source.GetStringAtIndex (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001048
1049 if (!context)
1050 return true;
1051
1052 Target *target = context->exe_ctx.target;
1053
1054 if (!target)
1055 return true;
1056
1057 Debugger &debugger = target->GetDebugger();
1058 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1059 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1060
1061 if (!script_interpreter)
1062 return true;
Greg Clayton5144f382010-10-07 17:14:24 +00001063
1064 if (python_function_name != NULL
1065 && python_function_name[0] != '\0')
1066 {
1067 Thread *thread = context->exe_ctx.thread;
1068 Target *target = context->exe_ctx.target;
1069 const StackFrameSP stop_frame_sp = thread->GetStackFrameSPForStackFramePtr (context->exe_ctx.frame);
1070 BreakpointSP breakpoint_sp = target->GetBreakpointByID (break_id);
1071 const BreakpointLocationSP bp_loc_sp = breakpoint_sp->FindLocationByID (break_loc_id);
1072
1073 SBFrame sb_frame (stop_frame_sp);
1074 SBBreakpointLocation sb_bp_loc (bp_loc_sp);
1075
1076 if (sb_bp_loc.IsValid() || sb_frame.IsValid())
Caroline Tice0aa2e552011-01-14 00:29:16 +00001077 {
1078 python_interpreter->EnterSession ();
1079 Mutex::Locker locker (GetPythonMutex());
1080 bool ret_val = LLDBSWIGPythonBreakpointCallbackFunction(python_function_name,
1081 python_interpreter->m_dictionary_name.c_str(),
1082 sb_frame, sb_bp_loc);
1083 python_interpreter->LeaveSession ();
1084 return ret_val;
1085 }
Greg Clayton5144f382010-10-07 17:14:24 +00001086 }
1087 // We currently always true so we stop in case anything goes wrong when
1088 // trying to call the script function
1089 return true;
1090}
Caroline Tice2ade6112010-11-10 19:18:14 +00001091
1092lldb::thread_result_t
1093ScriptInterpreterPython::RunEmbeddedPythonInterpreter (lldb::thread_arg_t baton)
1094{
1095 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
1096
Caroline Tice0aa2e552011-01-14 00:29:16 +00001097 script_interpreter->EnterSession ();
1098
Caroline Tice2ade6112010-11-10 19:18:14 +00001099 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
1100
1101 if (log)
1102 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread starting...", baton);
1103
1104 char error_str[1024];
1105 const char *pty_slave_name = script_interpreter->m_embedded_python_pty.GetSlaveName (error_str, sizeof (error_str));
1106 if (pty_slave_name != NULL)
1107 {
Caroline Tice0aa2e552011-01-14 00:29:16 +00001108 Mutex::Locker locker (GetPythonMutex());
1109
Caroline Tice2ade6112010-11-10 19:18:14 +00001110 StreamString run_string;
Caroline Tice2ade6112010-11-10 19:18:14 +00001111
Caroline Tice0aa2e552011-01-14 00:29:16 +00001112 run_string.Printf ("run_one_line (%s, 'save_stderr = sys.stderr')", script_interpreter->m_dictionary_name.c_str());
1113 PyRun_SimpleString (run_string.GetData());
1114 run_string.Clear ();
1115
1116 run_string.Printf ("run_one_line (%s, 'sys.stderr = sys.stdout')", script_interpreter->m_dictionary_name.c_str());
1117 PyRun_SimpleString (run_string.GetData());
1118 run_string.Clear ();
1119
1120 run_string.Printf ("run_one_line (%s, 'save_stdin = sys.stdin')", script_interpreter->m_dictionary_name.c_str());
1121 PyRun_SimpleString (run_string.GetData());
1122 run_string.Clear ();
1123
1124 run_string.Printf ("run_one_line (%s, \"sys.stdin = open ('%s', 'r')\")", script_interpreter->m_dictionary_name.c_str(),
1125 pty_slave_name);
1126 PyRun_SimpleString (run_string.GetData());
1127 run_string.Clear ();
1128
Caroline Tice2ade6112010-11-10 19:18:14 +00001129 // The following call drops into the embedded interpreter loop and stays there until the
1130 // user chooses to exit from the Python interpreter.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001131
1132 run_string.Printf ("run_python_interpreter (%s)", script_interpreter->m_dictionary_name.c_str());
1133 PyRun_SimpleString (run_string.GetData());
1134 run_string.Clear ();
Caroline Tice2ade6112010-11-10 19:18:14 +00001135
Caroline Tice0aa2e552011-01-14 00:29:16 +00001136 run_string.Printf ("run_one_line (%s, 'sys.stdin = save_stdin')", script_interpreter->m_dictionary_name.c_str());
1137 PyRun_SimpleString (run_string.GetData());
1138 run_string.Clear();
1139
1140 run_string.Printf ("run_one_line (%s, 'sys.stderr = save_stderr')", script_interpreter->m_dictionary_name.c_str());
1141 PyRun_SimpleString (run_string.GetData());
1142 run_string.Clear();
Caroline Tice2ade6112010-11-10 19:18:14 +00001143 }
1144
1145 if (script_interpreter->m_embedded_thread_input_reader_sp)
1146 script_interpreter->m_embedded_thread_input_reader_sp->SetIsDone (true);
1147
1148 script_interpreter->m_embedded_python_pty.CloseSlaveFileDescriptor();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001149
1150 script_interpreter->m_pty_slave_is_open = false;
Caroline Tice2ade6112010-11-10 19:18:14 +00001151
1152 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT);
1153 if (log)
1154 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread exiting...", baton);
1155
1156
Caroline Tice0aa2e552011-01-14 00:29:16 +00001157 // Clean up the input reader and make the debugger pop it off the stack.
1158 Debugger &debugger = script_interpreter->GetCommandInterpreter().GetDebugger();
Caroline Tice2ade6112010-11-10 19:18:14 +00001159 const InputReaderSP reader_sp = script_interpreter->m_embedded_thread_input_reader_sp;
1160 script_interpreter->m_embedded_thread_input_reader_sp.reset();
1161 debugger.PopInputReader (reader_sp);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001162
1163 script_interpreter->LeaveSession ();
Caroline Tice2ade6112010-11-10 19:18:14 +00001164
1165 return NULL;
1166}
1167
1168
Caroline Tice0aa2e552011-01-14 00:29:16 +00001169void
1170ScriptInterpreterPython::Initialize ()
1171{
Caroline Tice2ade6112010-11-10 19:18:14 +00001172
Caroline Tice0aa2e552011-01-14 00:29:16 +00001173 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
1174
1175 int input_fd = STDIN_FILENO;
1176
1177 struct termios stdin_termios;
1178 bool valid_termios = ::tcgetattr (input_fd, &stdin_termios) == 0;
1179
1180 // Find the module that owns this code and use that path we get to
1181 // set the PYTHONPATH appropriately.
1182
1183 FileSpec file_spec;
1184 char python_dir_path[PATH_MAX];
1185 if (Host::GetLLDBPath (ePathTypePythonDir, file_spec))
1186 {
1187 std::string python_path;
1188 const char *curr_python_path = ::getenv ("PYTHONPATH");
1189 if (curr_python_path)
1190 {
1191 // We have a current value for PYTHONPATH, so lets append to it
1192 python_path.append (curr_python_path);
1193 }
1194
1195 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
1196 {
1197 if (!python_path.empty())
1198 python_path.append (1, ':');
1199 python_path.append (python_dir_path);
1200 }
1201
1202 if (Host::GetLLDBPath (ePathTypeLLDBShlibDir, file_spec))
1203 {
1204 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
1205 {
1206 if (!python_path.empty())
1207 python_path.append (1, ':');
1208 python_path.append (python_dir_path);
1209 }
1210 }
1211 const char *pathon_path_env_cstr = python_path.c_str();
1212 ::setenv ("PYTHONPATH", pathon_path_env_cstr, 1);
1213 }
1214
1215 Py_Initialize ();
1216
1217 PyObject *compiled_module = Py_CompileString (embedded_interpreter_string,
1218 "embedded_interpreter.py",
1219 Py_file_input);
1220
1221 PyObject *py_error = PyErr_Occurred ();
1222 if (py_error != NULL)
1223 {
1224 PyErr_Print();
1225 PyErr_Clear();
1226 }
1227
1228
1229 // This function is in the C++ output file generated by SWIG after it is
1230 // run on all of the headers in "lldb/API/SB*.h"
1231 init_lldb ();
1232
1233 // Update the path python uses to search for modules to include the current directory.
1234
1235 int success = PyRun_SimpleString ("import sys");
1236 success = PyRun_SimpleString ("sys.path.append ('.')");
1237
1238 PyObject *pmod = NULL;
1239
1240 if (compiled_module)
1241 {
1242 pmod = PyImport_ExecCodeModule (const_cast<char*> ("embedded_interpreter"),
1243 compiled_module);
1244 Py_DECREF (compiled_module);
1245 }
1246
1247 if (pmod != NULL)
1248 {
1249 PyRun_SimpleString ("from embedded_interpreter import run_python_interpreter");
1250 PyRun_SimpleString ("from embedded_interpreter import run_one_line");
1251 PyRun_SimpleString ("import sys");
1252 PyRun_SimpleString ("from termios import *");
1253 Py_DECREF (pmod);
1254 }
1255
1256 if (valid_termios)
1257 ::tcsetattr (input_fd, TCSANOW, &stdin_termios);
1258}
1259
1260void
1261ScriptInterpreterPython::Terminate ()
1262{
1263 // We are intentionally NOT calling Py_Finalize here (this would be the logical place to call it). Calling
1264 // Py_Finalize here causes test suite runs to seg fault: The test suite runs in Python. It registers
1265 // SBDebugger::Terminate to be called 'at_exit'. When the test suite Python harness finishes up, it calls
1266 // Py_Finalize, which calls all the 'at_exit' registered functions. SBDebugger::Terminate calls Debugger::Terminate,
1267 // which calls lldb::Terminate, which calls ScriptInterpreter::Terminate, which calls
1268 // ScriptInterpreterPython::Terminate. So if we call Py_Finalize here, we end up with Py_Finalize being called from
1269 // within Py_Finalize, which results in a seg fault.
1270 //
1271 // Since this function only gets called when lldb is shutting down and going away anyway, the fact that we don't
1272 // actually call Py_Finalize should not cause any problems (everything should shut down/go away anyway when the
1273 // process exits).
1274 //
1275// Py_Finalize ();
1276}