blob: 610c019cb336183bc82579e2a20c1b57025bfed3 [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
Chris Lattner24943d22010-06-08 16:52:24 +000031using namespace lldb;
32using namespace lldb_private;
33
Greg Claytone86cbb92011-03-22 01:14:58 +000034
35static ScriptInterpreter::SWIGInitCallback g_swig_init_callback = NULL;
36static ScriptInterpreter::SWIGBreakpointCallbackFunction g_swig_breakpoint_callback = NULL;
37
Chris Lattner24943d22010-06-08 16:52:24 +000038
39static int
40_check_and_flush (FILE *stream)
41{
42 int prev_fail = ferror (stream);
43 return fflush (stream) || prev_fail ? EOF : 0;
44}
45
Caroline Tice202f6b82011-01-17 21:55:19 +000046static Predicate<lldb::tid_t> &
47PythonMutexPredicate ()
Caroline Tice0aa2e552011-01-14 00:29:16 +000048{
Caroline Tice202f6b82011-01-17 21:55:19 +000049 static lldb_private::Predicate<lldb::tid_t> g_interpreter_is_running (LLDB_INVALID_THREAD_ID);
50 return g_interpreter_is_running;
51}
52
53static bool
54CurrentThreadHasPythonLock ()
55{
56 TimeValue timeout;
57
58 timeout = TimeValue::Now(); // Don't wait any time.
59
60 return PythonMutexPredicate().WaitForValueEqualTo (Host::GetCurrentThreadID(), &timeout, NULL);
61}
62
63static bool
64GetPythonLock (uint32_t seconds_to_wait)
65{
66
67 TimeValue timeout;
68
69 if (seconds_to_wait != UINT32_MAX)
70 {
71 timeout = TimeValue::Now();
72 timeout.OffsetWithSeconds (seconds_to_wait);
73 }
74
75 return PythonMutexPredicate().WaitForValueEqualToAndSetValueTo (LLDB_INVALID_THREAD_ID,
76 Host::GetCurrentThreadID(), &timeout, NULL);
77}
78
79static void
80ReleasePythonLock ()
81{
82 PythonMutexPredicate().SetValue (LLDB_INVALID_THREAD_ID, eBroadcastAlways);
Caroline Tice0aa2e552011-01-14 00:29:16 +000083}
84
Greg Clayton63094e02010-06-23 01:19:29 +000085ScriptInterpreterPython::ScriptInterpreterPython (CommandInterpreter &interpreter) :
Greg Clayton238c0a12010-09-18 01:14:36 +000086 ScriptInterpreter (interpreter, eScriptLanguagePython),
Caroline Tice0aa2e552011-01-14 00:29:16 +000087 m_embedded_python_pty (),
88 m_embedded_thread_input_reader_sp (),
Greg Clayton58928562011-02-09 01:08:52 +000089 m_dbg_stdout (interpreter.GetDebugger().GetOutputFile().GetStream()),
Caroline Tice0aa2e552011-01-14 00:29:16 +000090 m_new_sysout (NULL),
91 m_dictionary_name (interpreter.GetDebugger().GetInstanceName().AsCString()),
Greg Clayton0fdd4a02011-02-07 23:24:47 +000092 m_terminal_state (),
Caroline Tice0aa2e552011-01-14 00:29:16 +000093 m_session_is_active (false),
94 m_pty_slave_is_open (false),
95 m_valid_session (true)
Chris Lattner24943d22010-06-08 16:52:24 +000096{
97
Greg Clayton7c330d62011-01-27 01:01:10 +000098 static int g_initialized = false;
99
100 if (!g_initialized)
101 {
102 g_initialized = true;
Greg Claytone86cbb92011-03-22 01:14:58 +0000103 ScriptInterpreterPython::InitializePrivate ();
Greg Clayton7c330d62011-01-27 01:01:10 +0000104 }
105
Caroline Tice202f6b82011-01-17 21:55:19 +0000106 bool safe_to_run = false;
107 bool need_to_release_lock = true;
108 int interval = 5; // Number of seconds to try getting the Python lock before timing out.
109
110 // We don't dare exit this function without finishing setting up the script interpreter, so we must wait until
111 // we can get the Python lock.
112
113 if (CurrentThreadHasPythonLock())
114 {
115 safe_to_run = true;
116 need_to_release_lock = false;
117 }
118
119 while (!safe_to_run)
120 {
121 safe_to_run = GetPythonLock (interval);
122 if (!safe_to_run)
123 {
124 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
125 fprintf (tmp_fh,
126 "Python interpreter is locked on another thread; "
127 "please release interpreter in order to continue.\n");
128 interval = interval * 2;
129 }
130 }
131
Caroline Tice0aa2e552011-01-14 00:29:16 +0000132 m_dictionary_name.append("_dict");
133 StreamString run_string;
134 run_string.Printf ("%s = dict()", m_dictionary_name.c_str());
135 PyRun_SimpleString (run_string.GetData());
Caroline Tice5867f6b2010-10-18 18:24:17 +0000136
Caroline Tice0aa2e552011-01-14 00:29:16 +0000137 run_string.Clear();
138 run_string.Printf ("run_one_line (%s, 'import sys')", m_dictionary_name.c_str());
139 PyRun_SimpleString (run_string.GetData());
140
141 // Importing 'lldb' module calls SBDebugger::Initialize, which calls Debugger::Initialize, which increments a
142 // global debugger ref-count; therefore we need to check the ref-count before and after importing lldb, and if the
143 // ref-count increased we need to call Debugger::Terminate here to decrement the ref-count so that when the final
144 // call to Debugger::Terminate is made, the ref-count has the correct value.
145 //
146 // Bonus question: Why doesn't the ref-count always increase? Because sometimes lldb has already been imported, in
147 // which case the code inside it, including the call to SBDebugger::Initialize(), does not get executed.
Caroline Tice5867f6b2010-10-18 18:24:17 +0000148
Caroline Tice0aa2e552011-01-14 00:29:16 +0000149 int old_count = Debugger::TestDebuggerRefCount();
Chris Lattner24943d22010-06-08 16:52:24 +0000150
Caroline Tice0aa2e552011-01-14 00:29:16 +0000151 run_string.Clear();
152 run_string.Printf ("run_one_line (%s, 'import lldb')", m_dictionary_name.c_str());
153 PyRun_SimpleString (run_string.GetData());
Greg Clayton24b48ff2010-10-17 22:03:32 +0000154
Caroline Tice0aa2e552011-01-14 00:29:16 +0000155 int new_count = Debugger::TestDebuggerRefCount();
Chris Lattner24943d22010-06-08 16:52:24 +0000156
Caroline Tice0aa2e552011-01-14 00:29:16 +0000157 if (new_count > old_count)
158 Debugger::Terminate();
Caroline Tice5867f6b2010-10-18 18:24:17 +0000159
Caroline Tice0aa2e552011-01-14 00:29:16 +0000160 run_string.Clear();
161 run_string.Printf ("run_one_line (%s, 'import copy')", m_dictionary_name.c_str());
162 PyRun_SimpleString (run_string.GetData());
163
164 run_string.Clear();
165 run_string.Printf ("run_one_line (%s, 'lldb.debugger_unique_id = %d')", m_dictionary_name.c_str(),
166 interpreter.GetDebugger().GetID());
167 PyRun_SimpleString (run_string.GetData());
168
169 if (m_dbg_stdout != NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000170 {
Caroline Tice0aa2e552011-01-14 00:29:16 +0000171 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
Caroline Tice5867f6b2010-10-18 18:24:17 +0000172 }
Caroline Tice202f6b82011-01-17 21:55:19 +0000173
174 if (need_to_release_lock)
175 ReleasePythonLock();
Chris Lattner24943d22010-06-08 16:52:24 +0000176}
177
178ScriptInterpreterPython::~ScriptInterpreterPython ()
179{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000180 Debugger &debugger = GetCommandInterpreter().GetDebugger();
181
182 if (m_embedded_thread_input_reader_sp.get() != NULL)
183 {
184 m_embedded_thread_input_reader_sp->SetIsDone (true);
185 m_embedded_python_pty.CloseSlaveFileDescriptor();
186 m_pty_slave_is_open = false;
187 const InputReaderSP reader_sp = m_embedded_thread_input_reader_sp;
188 m_embedded_thread_input_reader_sp.reset();
189 debugger.PopInputReader (reader_sp);
190 }
191
192 if (m_new_sysout)
193 {
Caroline Tice202f6b82011-01-17 21:55:19 +0000194 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
195 if (!CurrentThreadHasPythonLock ())
196 {
197 while (!GetPythonLock (1))
198 fprintf (tmp_fh, "Python interpreter locked on another thread; waiting to acquire lock...\n");
199 Py_DECREF (m_new_sysout);
200 ReleasePythonLock ();
201 }
202 else
203 Py_DECREF (m_new_sysout);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000204 }
Chris Lattner24943d22010-06-08 16:52:24 +0000205}
206
Caroline Tice0aa2e552011-01-14 00:29:16 +0000207void
208ScriptInterpreterPython::ResetOutputFileHandle (FILE *fh)
209{
210 if (fh == NULL)
211 return;
212
213 m_dbg_stdout = fh;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000214
Caroline Tice202f6b82011-01-17 21:55:19 +0000215 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
216 if (!CurrentThreadHasPythonLock ())
217 {
218 while (!GetPythonLock (1))
219 fprintf (tmp_fh, "Python interpreter locked on another thread; waiting to acquire lock...\n");
220 EnterSession ();
221 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
222 LeaveSession ();
223 ReleasePythonLock ();
224 }
225 else
226 {
227 EnterSession ();
228 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
229 LeaveSession ();
230 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000231}
232
233void
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000234ScriptInterpreterPython::SaveTerminalState (int fd)
235{
236 // Python mucks with the terminal state of STDIN. If we can possibly avoid
237 // this by setting the file handles up correctly prior to entering the
238 // interpreter we should. For now we save and restore the terminal state
239 // on the input file handle.
240 m_terminal_state.Save (fd, false);
241}
242
243void
244ScriptInterpreterPython::RestoreTerminalState ()
245{
246 // Python mucks with the terminal state of STDIN. If we can possibly avoid
247 // this by setting the file handles up correctly prior to entering the
248 // interpreter we should. For now we save and restore the terminal state
249 // on the input file handle.
250 m_terminal_state.Restore();
251}
252
253
254
255void
Caroline Tice0aa2e552011-01-14 00:29:16 +0000256ScriptInterpreterPython::LeaveSession ()
257{
258 m_session_is_active = false;
259}
260
261void
262ScriptInterpreterPython::EnterSession ()
263{
264 // If we have already entered the session, without having officially 'left' it, then there is no need to
265 // 'enter' it again.
266
267 if (m_session_is_active)
268 return;
269
270 m_session_is_active = true;
271
Caroline Tice202f6b82011-01-17 21:55:19 +0000272 StreamString run_string;
273
274 run_string.Printf ("run_one_line (%s, 'lldb.debugger_unique_id = %d')", m_dictionary_name.c_str(),
275 GetCommandInterpreter().GetDebugger().GetID());
276 PyRun_SimpleString (run_string.GetData());
Caroline Tice6af65cb2011-05-03 21:21:50 +0000277 run_string.Clear();
Caroline Tice202f6b82011-01-17 21:55:19 +0000278
Caroline Tice0aa2e552011-01-14 00:29:16 +0000279
Caroline Tice6af65cb2011-05-03 21:21:50 +0000280 run_string.Printf ("run_one_line (%s, 'lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%d)')",
281 m_dictionary_name.c_str(),
282 GetCommandInterpreter().GetDebugger().GetID());
283 PyRun_SimpleString (run_string.GetData());
284 run_string.Clear();
285
286
287 ExecutionContext exe_ctx = m_interpreter.GetDebugger().GetSelectedExecutionContext();
288
289 if (exe_ctx.target)
290 run_string.Printf ("run_one_line (%s, 'lldb.target = lldb.debugger.GetSelectedTarget()')",
291 m_dictionary_name.c_str());
292 else
293 run_string.Printf ("run_one_line (%s, 'lldb.target = None')", m_dictionary_name.c_str());
294 PyRun_SimpleString (run_string.GetData());
295 run_string.Clear();
296
297 if (exe_ctx.process)
298 run_string.Printf ("run_one_line (%s, 'lldb.process = lldb.target.GetProcess()')", m_dictionary_name.c_str());
299 else
300 run_string.Printf ("run_one_line (%s, 'lldb.process = None')", m_dictionary_name.c_str());
301 PyRun_SimpleString (run_string.GetData());
302 run_string.Clear();
303
304 if (exe_ctx.thread)
305 run_string.Printf ("run_one_line (%s, 'lldb.thread = lldb.process.GetSelectedThread ()')",
306 m_dictionary_name.c_str());
307 else
308 run_string.Printf ("run_one_line (%s, 'lldb.thread = None')", m_dictionary_name.c_str());
309 PyRun_SimpleString (run_string.GetData());
310 run_string.Clear();
311
312 if (exe_ctx.frame)
313 run_string.Printf ("run_one_line (%s, 'lldb.frame = lldb.thread.GetSelectedFrame ()')",
314 m_dictionary_name.c_str());
315 else
316 run_string.Printf ("run_one_line (%s, 'lldb.frame = None')", m_dictionary_name.c_str());
317 PyRun_SimpleString (run_string.GetData());
318 run_string.Clear();
319
Caroline Tice0aa2e552011-01-14 00:29:16 +0000320 PyObject *sysmod = PyImport_AddModule ("sys");
321 PyObject *sysdict = PyModule_GetDict (sysmod);
322
323 if ((m_new_sysout != NULL)
324 && (sysmod != NULL)
325 && (sysdict != NULL))
326 PyDict_SetItemString (sysdict, "stdout", m_new_sysout);
327
328 if (PyErr_Occurred())
329 PyErr_Clear ();
330
Caroline Tice0aa2e552011-01-14 00:29:16 +0000331 if (!m_pty_slave_is_open)
332 {
Caroline Tice202f6b82011-01-17 21:55:19 +0000333 run_string.Clear();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000334 run_string.Printf ("run_one_line (%s, \"new_stdin = open('%s', 'r')\")", m_dictionary_name.c_str(),
335 m_pty_slave_name.c_str());
336 PyRun_SimpleString (run_string.GetData());
337 m_pty_slave_is_open = true;
338
339 run_string.Clear();
340 run_string.Printf ("run_one_line (%s, 'sys.stdin = new_stdin')", m_dictionary_name.c_str());
341 PyRun_SimpleString (run_string.GetData());
342 }
343}
344
345
Johnny Chen60dde642010-07-30 22:33:14 +0000346bool
Greg Clayton238c0a12010-09-18 01:14:36 +0000347ScriptInterpreterPython::ExecuteOneLine (const char *command, CommandReturnObject *result)
Chris Lattner24943d22010-06-08 16:52:24 +0000348{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000349 if (!m_valid_session)
350 return false;
351
Caroline Tice0aa2e552011-01-14 00:29:16 +0000352
Caroline Tice0aa2e552011-01-14 00:29:16 +0000353
Caroline Tice4a461da2011-01-14 21:09:29 +0000354 // We want to call run_one_line, passing in the dictionary and the command string. We cannot do this through
355 // PyRun_SimpleString here because the command string may contain escaped characters, and putting it inside
356 // another string to pass to PyRun_SimpleString messes up the escaping. So we use the following more complicated
357 // method to pass the command string directly down to Python.
358
359
Caroline Tice202f6b82011-01-17 21:55:19 +0000360 bool need_to_release_lock = true;
361
362 if (CurrentThreadHasPythonLock())
363 need_to_release_lock = false;
364 else if (!GetPythonLock (1))
365 {
366 fprintf ((m_dbg_stdout ? m_dbg_stdout : stdout),
367 "Python interpreter is currently locked by another thread; unable to process command.\n");
368 return false;
369 }
370
371 EnterSession ();
Caroline Tice4a461da2011-01-14 21:09:29 +0000372 bool success = false;
373
Greg Clayton63094e02010-06-23 01:19:29 +0000374 if (command)
Chris Lattner24943d22010-06-08 16:52:24 +0000375 {
Caroline Tice4a461da2011-01-14 21:09:29 +0000376 // Find the correct script interpreter dictionary in the main module.
377 PyObject *main_mod = PyImport_AddModule ("__main__");
378 PyObject *script_interpreter_dict = NULL;
379 if (main_mod != NULL)
380 {
381 PyObject *main_dict = PyModule_GetDict (main_mod);
382 if ((main_dict != NULL)
383 && PyDict_Check (main_dict))
384 {
385 // Go through the main dictionary looking for the correct python script interpreter dictionary
386 PyObject *key, *value;
387 Py_ssize_t pos = 0;
388
389 while (PyDict_Next (main_dict, &pos, &key, &value))
390 {
391 // We have stolen references to the key and value objects in the dictionary; we need to increment
392 // them now so that Python's garbage collector doesn't collect them out from under us.
393 Py_INCREF (key);
394 Py_INCREF (value);
395 if (strcmp (PyString_AsString (key), m_dictionary_name.c_str()) == 0)
396 {
397 script_interpreter_dict = value;
398 break;
399 }
400 }
401 }
402
403 if (script_interpreter_dict != NULL)
404 {
405 PyObject *pfunc = NULL;
406 PyObject *pmod = PyImport_AddModule ("embedded_interpreter");
407 if (pmod != NULL)
408 {
409 PyObject *pmod_dict = PyModule_GetDict (pmod);
410 if ((pmod_dict != NULL)
411 && PyDict_Check (pmod_dict))
412 {
413 PyObject *key, *value;
414 Py_ssize_t pos = 0;
415
416 while (PyDict_Next (pmod_dict, &pos, &key, &value))
417 {
418 Py_INCREF (key);
419 Py_INCREF (value);
420 if (strcmp (PyString_AsString (key), "run_one_line") == 0)
421 {
422 pfunc = value;
423 break;
424 }
425 }
426
427 PyObject *string_arg = PyString_FromString (command);
428 if (pfunc && string_arg && PyCallable_Check (pfunc))
429 {
430 PyObject *pargs = PyTuple_New (2);
431 if (pargs != NULL)
432 {
433 PyTuple_SetItem (pargs, 0, script_interpreter_dict);
434 PyTuple_SetItem (pargs, 1, string_arg);
435 PyObject *pvalue = PyObject_CallObject (pfunc, pargs);
436 Py_DECREF (pargs);
437 if (pvalue != NULL)
438 {
439 Py_DECREF (pvalue);
440 success = true;
441 }
442 else if (PyErr_Occurred ())
443 {
444 PyErr_Print();
445 PyErr_Clear();
446 }
447 }
448 }
449 }
450 }
451 Py_INCREF (script_interpreter_dict);
452 }
453 }
Greg Clayton63094e02010-06-23 01:19:29 +0000454
Caroline Tice0aa2e552011-01-14 00:29:16 +0000455 LeaveSession ();
456
Caroline Tice202f6b82011-01-17 21:55:19 +0000457 if (need_to_release_lock)
458 ReleasePythonLock();
459
Caroline Tice4a461da2011-01-14 21:09:29 +0000460 if (success)
Johnny Chen60dde642010-07-30 22:33:14 +0000461 return true;
462
463 // The one-liner failed. Append the error message.
464 if (result)
465 result->AppendErrorWithFormat ("python failed attempting to evaluate '%s'\n", command);
466 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000467 }
Johnny Chen60dde642010-07-30 22:33:14 +0000468
Caroline Tice0aa2e552011-01-14 00:29:16 +0000469 LeaveSession ();
Caroline Tice202f6b82011-01-17 21:55:19 +0000470
471 if (need_to_release_lock)
472 ReleasePythonLock ();
473
Johnny Chen60dde642010-07-30 22:33:14 +0000474 if (result)
475 result->AppendError ("empty command passed to python\n");
476 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000477}
478
479
480
481size_t
482ScriptInterpreterPython::InputReaderCallback
483(
484 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000485 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000486 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000487 const char *bytes,
488 size_t bytes_len
489)
490{
Caroline Tice2ade6112010-11-10 19:18:14 +0000491 lldb::thread_t embedded_interpreter_thread;
492 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
493
Chris Lattner24943d22010-06-08 16:52:24 +0000494 if (baton == NULL)
495 return 0;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000496
497 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
498
499 if (script_interpreter->m_script_lang != eScriptLanguagePython)
500 return 0;
501
Caroline Tice892fadd2011-06-16 16:27:19 +0000502 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
503 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
504
Chris Lattner24943d22010-06-08 16:52:24 +0000505 switch (notification)
506 {
507 case eInputReaderActivate:
508 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000509 if (!batch_mode)
510 {
511 out_stream->Printf ("Python Interactive Interpreter. To exit, type 'quit()', 'exit()' or Ctrl-D.\n");
512 out_stream->Flush();
513 }
Greg Clayton58928562011-02-09 01:08:52 +0000514
Chris Lattner24943d22010-06-08 16:52:24 +0000515 // Save terminal settings if we can
Greg Clayton58928562011-02-09 01:08:52 +0000516 int input_fd = reader.GetDebugger().GetInputFile().GetDescriptor();
517 if (input_fd == File::kInvalidDescriptor)
Greg Clayton24b48ff2010-10-17 22:03:32 +0000518 input_fd = STDIN_FILENO;
Caroline Ticec95c6d12010-09-14 22:49:06 +0000519
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000520 script_interpreter->SaveTerminalState(input_fd);
Greg Clayton99208582011-02-07 19:04:58 +0000521
Caroline Tice202f6b82011-01-17 21:55:19 +0000522 if (!CurrentThreadHasPythonLock())
523 {
524 while (!GetPythonLock(1))
525 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000526 out_stream->Printf ("Python interpreter locked on another thread; waiting to acquire lock...\n");
527 out_stream->Flush();
Caroline Tice202f6b82011-01-17 21:55:19 +0000528 }
529 script_interpreter->EnterSession ();
530 ReleasePythonLock();
531 }
532 else
533 script_interpreter->EnterSession ();
534
Caroline Tice2ade6112010-11-10 19:18:14 +0000535 char error_str[1024];
536 if (script_interpreter->m_embedded_python_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, error_str,
537 sizeof(error_str)))
538 {
539 if (log)
540 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in opening master pty (fd = %d).",
541 script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor());
542 embedded_interpreter_thread = Host::ThreadCreate ("<lldb.script-interpreter.embedded-python-loop>",
543 ScriptInterpreterPython::RunEmbeddedPythonInterpreter,
544 script_interpreter, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +0000545 if (IS_VALID_LLDB_HOST_THREAD(embedded_interpreter_thread))
Caroline Tice2ade6112010-11-10 19:18:14 +0000546 {
547 if (log)
548 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in creating thread (thread = %d)", embedded_interpreter_thread);
549 Error detach_error;
550 Host::ThreadDetach (embedded_interpreter_thread, &detach_error);
551 }
552 else
553 {
554 if (log)
555 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed in creating thread");
556 reader.SetIsDone (true);
557 }
558 }
559 else
560 {
561 if (log)
562 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed to open master pty ");
563 reader.SetIsDone (true);
564 }
Chris Lattner24943d22010-06-08 16:52:24 +0000565 }
566 break;
567
568 case eInputReaderDeactivate:
Caroline Tice0aa2e552011-01-14 00:29:16 +0000569 script_interpreter->LeaveSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000570 break;
571
572 case eInputReaderReactivate:
Caroline Tice202f6b82011-01-17 21:55:19 +0000573 if (!CurrentThreadHasPythonLock())
574 {
575 while (!GetPythonLock(1))
576 {
577 // Wait until lock is acquired.
578 }
579 script_interpreter->EnterSession ();
580 ReleasePythonLock();
581 }
582 else
583 script_interpreter->EnterSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000584 break;
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000585
Caroline Tice4a348082011-05-02 20:41:46 +0000586 case eInputReaderAsynchronousOutputWritten:
587 break;
588
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000589 case eInputReaderInterrupt:
590 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "raise KeyboardInterrupt\n", 24);
591 break;
592
593 case eInputReaderEndOfFile:
594 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()\n", 7);
595 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000596
597 case eInputReaderGotToken:
Caroline Tice2ade6112010-11-10 19:18:14 +0000598 if (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor() != -1)
Chris Lattner24943d22010-06-08 16:52:24 +0000599 {
Caroline Tice2ade6112010-11-10 19:18:14 +0000600 if (log)
601 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %d", bytes,
602 bytes_len);
603 if (bytes && bytes_len)
604 {
605 if ((int) bytes[0] == 4)
606 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()", 6);
607 else
608 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), bytes, bytes_len);
609 }
610 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "\n", 1);
Chris Lattner24943d22010-06-08 16:52:24 +0000611 }
Caroline Tice2ade6112010-11-10 19:18:14 +0000612 else
613 {
614 if (log)
615 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %d, Master File Descriptor is bad.",
616 bytes,
617 bytes_len);
618 reader.SetIsDone (true);
619 }
620
Chris Lattner24943d22010-06-08 16:52:24 +0000621 break;
622
623 case eInputReaderDone:
Caroline Tice0aa2e552011-01-14 00:29:16 +0000624 script_interpreter->LeaveSession ();
625
Chris Lattner24943d22010-06-08 16:52:24 +0000626 // Restore terminal settings if they were validly saved
Caroline Tice2ade6112010-11-10 19:18:14 +0000627 if (log)
628 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Done, closing down input reader.");
Caroline Ticec95c6d12010-09-14 22:49:06 +0000629
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000630 script_interpreter->RestoreTerminalState ();
631
Caroline Tice2ade6112010-11-10 19:18:14 +0000632 script_interpreter->m_embedded_python_pty.CloseMasterFileDescriptor();
Chris Lattner24943d22010-06-08 16:52:24 +0000633 break;
634 }
635
636 return bytes_len;
637}
638
639
640void
Greg Clayton238c0a12010-09-18 01:14:36 +0000641ScriptInterpreterPython::ExecuteInterpreterLoop ()
Chris Lattner24943d22010-06-08 16:52:24 +0000642{
643 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
644
Caroline Tice0aa2e552011-01-14 00:29:16 +0000645 Debugger &debugger = GetCommandInterpreter().GetDebugger();
Caroline Ticec95c6d12010-09-14 22:49:06 +0000646
647 // At the moment, the only time the debugger does not have an input file handle is when this is called
648 // directly from Python, in which case it is both dangerous and unnecessary (not to mention confusing) to
649 // try to embed a running interpreter loop inside the already running Python interpreter loop, so we won't
650 // do it.
651
Greg Clayton58928562011-02-09 01:08:52 +0000652 if (!debugger.GetInputFile().IsValid())
Caroline Ticec95c6d12010-09-14 22:49:06 +0000653 return;
654
Greg Clayton63094e02010-06-23 01:19:29 +0000655 InputReaderSP reader_sp (new InputReader(debugger));
Chris Lattner24943d22010-06-08 16:52:24 +0000656 if (reader_sp)
657 {
658 Error error (reader_sp->Initialize (ScriptInterpreterPython::InputReaderCallback,
659 this, // baton
660 eInputReaderGranularityLine, // token size, to pass to callback function
661 NULL, // end token
662 NULL, // prompt
663 true)); // echo input
664
665 if (error.Success())
666 {
Greg Clayton63094e02010-06-23 01:19:29 +0000667 debugger.PushInputReader (reader_sp);
Caroline Tice2ade6112010-11-10 19:18:14 +0000668 m_embedded_thread_input_reader_sp = reader_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000669 }
670 }
671}
672
673bool
674ScriptInterpreterPython::ExecuteOneLineWithReturn (const char *in_string,
675 ScriptInterpreter::ReturnType return_type,
676 void *ret_value)
677{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000678
Caroline Tice202f6b82011-01-17 21:55:19 +0000679 bool need_to_release_lock = true;
680
681 if (CurrentThreadHasPythonLock())
682 need_to_release_lock = false;
683 else if (!GetPythonLock (1))
684 {
685 fprintf ((m_dbg_stdout ? m_dbg_stdout : stdout),
686 "Python interpreter is currently locked by another thread; unable to process command.\n");
687 return false;
688 }
689
690 EnterSession ();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000691
Chris Lattner24943d22010-06-08 16:52:24 +0000692 PyObject *py_return = NULL;
693 PyObject *mainmod = PyImport_AddModule ("__main__");
694 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000695 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000696 PyObject *py_error = NULL;
697 bool ret_success;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000698 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000699 int success;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000700
701 if (PyDict_Check (globals))
702 {
703 PyObject *key, *value;
704 Py_ssize_t pos = 0;
705
706 int i = 0;
707 while (PyDict_Next (globals, &pos, &key, &value))
708 {
709 // We have stolen references to the key and value objects in the dictionary; we need to increment them now
710 // so that Python's garbage collector doesn't collect them out from under us.
711 Py_INCREF (key);
712 Py_INCREF (value);
713 char *c_str = PyString_AsString (key);
714 if (strcmp (c_str, m_dictionary_name.c_str()) == 0)
715 locals = value;
716 ++i;
717 }
718 }
Chris Lattner24943d22010-06-08 16:52:24 +0000719
Caroline Tice0aa2e552011-01-14 00:29:16 +0000720 if (locals == NULL)
721 {
722 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
723 should_decrement_locals = true;
724 }
725
726 if (locals == NULL)
727 {
728 locals = globals;
729 should_decrement_locals = false;
730 }
731
732 py_error = PyErr_Occurred();
733 if (py_error != NULL)
734 PyErr_Clear();
735
Chris Lattner24943d22010-06-08 16:52:24 +0000736 if (in_string != NULL)
737 {
738 py_return = PyRun_String (in_string, Py_eval_input, globals, locals);
739 if (py_return == NULL)
740 {
741 py_error = PyErr_Occurred ();
742 if (py_error != NULL)
743 PyErr_Clear ();
744
745 py_return = PyRun_String (in_string, Py_single_input, globals, locals);
746 }
747
Caroline Tice0aa2e552011-01-14 00:29:16 +0000748 if (locals != NULL
749 && should_decrement_locals)
750 Py_DECREF (locals);
751
Chris Lattner24943d22010-06-08 16:52:24 +0000752 if (py_return != NULL)
753 {
754 switch (return_type)
755 {
756 case eCharPtr: // "char *"
757 {
758 const char format[3] = "s#";
759 success = PyArg_Parse (py_return, format, (char **) &ret_value);
760 break;
761 }
762 case eBool:
763 {
764 const char format[2] = "b";
765 success = PyArg_Parse (py_return, format, (bool *) ret_value);
766 break;
767 }
768 case eShortInt:
769 {
770 const char format[2] = "h";
771 success = PyArg_Parse (py_return, format, (short *) ret_value);
772 break;
773 }
774 case eShortIntUnsigned:
775 {
776 const char format[2] = "H";
777 success = PyArg_Parse (py_return, format, (unsigned short *) ret_value);
778 break;
779 }
780 case eInt:
781 {
782 const char format[2] = "i";
783 success = PyArg_Parse (py_return, format, (int *) ret_value);
784 break;
785 }
786 case eIntUnsigned:
787 {
788 const char format[2] = "I";
789 success = PyArg_Parse (py_return, format, (unsigned int *) ret_value);
790 break;
791 }
792 case eLongInt:
793 {
794 const char format[2] = "l";
795 success = PyArg_Parse (py_return, format, (long *) ret_value);
796 break;
797 }
798 case eLongIntUnsigned:
799 {
800 const char format[2] = "k";
801 success = PyArg_Parse (py_return, format, (unsigned long *) ret_value);
802 break;
803 }
804 case eLongLong:
805 {
806 const char format[2] = "L";
807 success = PyArg_Parse (py_return, format, (long long *) ret_value);
808 break;
809 }
810 case eLongLongUnsigned:
811 {
812 const char format[2] = "K";
813 success = PyArg_Parse (py_return, format, (unsigned long long *) ret_value);
814 break;
815 }
816 case eFloat:
817 {
818 const char format[2] = "f";
819 success = PyArg_Parse (py_return, format, (float *) ret_value);
820 break;
821 }
822 case eDouble:
823 {
824 const char format[2] = "d";
825 success = PyArg_Parse (py_return, format, (double *) ret_value);
826 break;
827 }
828 case eChar:
829 {
830 const char format[2] = "c";
831 success = PyArg_Parse (py_return, format, (char *) ret_value);
832 break;
833 }
834 default:
835 {}
836 }
837 Py_DECREF (py_return);
838 if (success)
839 ret_success = true;
840 else
841 ret_success = false;
842 }
843 }
844
845 py_error = PyErr_Occurred();
846 if (py_error != NULL)
847 {
848 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
849 PyErr_Print ();
850 PyErr_Clear();
851 ret_success = false;
852 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000853
854 LeaveSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000855
Caroline Tice202f6b82011-01-17 21:55:19 +0000856 if (need_to_release_lock)
857 ReleasePythonLock();
858
Chris Lattner24943d22010-06-08 16:52:24 +0000859 return ret_success;
860}
861
862bool
863ScriptInterpreterPython::ExecuteMultipleLines (const char *in_string)
864{
Caroline Tice202f6b82011-01-17 21:55:19 +0000865 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
866 bool need_to_release_lock = true;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000867
Caroline Tice202f6b82011-01-17 21:55:19 +0000868 if (CurrentThreadHasPythonLock())
869 need_to_release_lock = false;
870 else
871 {
872 while (!GetPythonLock (1))
873 fprintf (tmp_fh, "Python interpreter locked on another thread; waiting to acquire lock...\n");
874 }
875
876 EnterSession ();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000877
Chris Lattner24943d22010-06-08 16:52:24 +0000878 bool success = false;
879 PyObject *py_return = NULL;
880 PyObject *mainmod = PyImport_AddModule ("__main__");
881 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000882 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000883 PyObject *py_error = NULL;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000884 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000885
Caroline Tice0aa2e552011-01-14 00:29:16 +0000886 if (PyDict_Check (globals))
887 {
888 PyObject *key, *value;
889 Py_ssize_t pos = 0;
890
891 while (PyDict_Next (globals, &pos, &key, &value))
892 {
893 // We have stolen references to the key and value objects in the dictionary; we need to increment them now
894 // so that Python's garbage collector doesn't collect them out from under us.
895 Py_INCREF (key);
896 Py_INCREF (value);
897 if (strcmp (PyString_AsString (key), m_dictionary_name.c_str()) == 0)
898 locals = value;
899 }
900 }
901
902 if (locals == NULL)
903 {
904 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
905 should_decrement_locals = true;
906 }
907
908 if (locals == NULL)
909 {
910 locals = globals;
911 should_decrement_locals = false;
912 }
913
914 py_error = PyErr_Occurred();
915 if (py_error != NULL)
916 PyErr_Clear();
917
Chris Lattner24943d22010-06-08 16:52:24 +0000918 if (in_string != NULL)
919 {
920 struct _node *compiled_node = PyParser_SimpleParseString (in_string, Py_file_input);
921 if (compiled_node)
922 {
923 PyCodeObject *compiled_code = PyNode_Compile (compiled_node, "temp.py");
924 if (compiled_code)
925 {
926 py_return = PyEval_EvalCode (compiled_code, globals, locals);
927 if (py_return != NULL)
928 {
929 success = true;
930 Py_DECREF (py_return);
931 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000932 if (locals && should_decrement_locals)
933 Py_DECREF (locals);
Chris Lattner24943d22010-06-08 16:52:24 +0000934 }
935 }
936 }
937
938 py_error = PyErr_Occurred ();
939 if (py_error != NULL)
940 {
941 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
942 PyErr_Print ();
943 PyErr_Clear();
944 success = false;
945 }
946
Caroline Tice0aa2e552011-01-14 00:29:16 +0000947 LeaveSession ();
948
Caroline Tice202f6b82011-01-17 21:55:19 +0000949 if (need_to_release_lock)
950 ReleasePythonLock();
951
Chris Lattner24943d22010-06-08 16:52:24 +0000952 return success;
953}
954
955static const char *g_reader_instructions = "Enter your Python command(s). Type 'DONE' to end.";
956
957size_t
958ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback
959(
960 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000961 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000962 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000963 const char *bytes,
964 size_t bytes_len
965)
966{
Caroline Tice892fadd2011-06-16 16:27:19 +0000967 static StringList commands_in_progress;
968
969 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
970 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
971
Chris Lattner24943d22010-06-08 16:52:24 +0000972 switch (notification)
973 {
974 case eInputReaderActivate:
975 {
976 commands_in_progress.Clear();
Caroline Tice892fadd2011-06-16 16:27:19 +0000977 if (!batch_mode)
Chris Lattner24943d22010-06-08 16:52:24 +0000978 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000979 out_stream->Printf ("%s\n", g_reader_instructions);
Greg Clayton63094e02010-06-23 01:19:29 +0000980 if (reader.GetPrompt())
Caroline Tice892fadd2011-06-16 16:27:19 +0000981 out_stream->Printf ("%s", reader.GetPrompt());
982 out_stream->Flush ();
Chris Lattner24943d22010-06-08 16:52:24 +0000983 }
984 }
985 break;
986
987 case eInputReaderDeactivate:
988 break;
989
990 case eInputReaderReactivate:
Caroline Tice892fadd2011-06-16 16:27:19 +0000991 if (reader.GetPrompt() && !batch_mode)
Caroline Ticef81b4c52010-10-27 18:34:42 +0000992 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000993 out_stream->Printf ("%s", reader.GetPrompt());
994 out_stream->Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +0000995 }
Chris Lattner24943d22010-06-08 16:52:24 +0000996 break;
997
Caroline Tice4a348082011-05-02 20:41:46 +0000998 case eInputReaderAsynchronousOutputWritten:
999 break;
1000
Chris Lattner24943d22010-06-08 16:52:24 +00001001 case eInputReaderGotToken:
1002 {
1003 std::string temp_string (bytes, bytes_len);
1004 commands_in_progress.AppendString (temp_string.c_str());
Caroline Tice892fadd2011-06-16 16:27:19 +00001005 if (!reader.IsDone() && reader.GetPrompt() && !batch_mode)
Caroline Ticef81b4c52010-10-27 18:34:42 +00001006 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001007 out_stream->Printf ("%s", reader.GetPrompt());
1008 out_stream->Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +00001009 }
Chris Lattner24943d22010-06-08 16:52:24 +00001010 }
1011 break;
1012
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001013 case eInputReaderEndOfFile:
1014 case eInputReaderInterrupt:
1015 // Control-c (SIGINT) & control-d both mean finish & exit.
1016 reader.SetIsDone(true);
1017
1018 // Control-c (SIGINT) ALSO means cancel; do NOT create a breakpoint command.
1019 if (notification == eInputReaderInterrupt)
1020 commands_in_progress.Clear();
1021
1022 // Fall through here...
1023
Chris Lattner24943d22010-06-08 16:52:24 +00001024 case eInputReaderDone:
1025 {
1026 BreakpointOptions *bp_options = (BreakpointOptions *)baton;
1027 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1028 data_ap->user_source.AppendList (commands_in_progress);
1029 if (data_ap.get())
1030 {
Greg Clayton63094e02010-06-23 01:19:29 +00001031 ScriptInterpreter *interpreter = reader.GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
Chris Lattner24943d22010-06-08 16:52:24 +00001032 if (interpreter)
1033 {
1034 if (interpreter->GenerateBreakpointCommandCallbackData (data_ap->user_source,
1035 data_ap->script_source))
1036 {
1037 if (data_ap->script_source.GetSize() == 1)
1038 {
1039 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1040 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
1041 }
1042 }
Caroline Tice892fadd2011-06-16 16:27:19 +00001043 else if (!batch_mode)
1044 {
1045 out_stream->Printf ("Warning: No command attached to breakpoint.\n");
1046 out_stream->Flush();
1047 }
Chris Lattner24943d22010-06-08 16:52:24 +00001048 }
1049 else
1050 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001051 if (!batch_mode)
1052 {
1053 out_stream->Printf ("Warning: Unable to find script intepreter; no command attached to breakpoint.\n");
1054 out_stream->Flush();
1055 }
Chris Lattner24943d22010-06-08 16:52:24 +00001056 }
1057 }
1058 }
1059 break;
1060
1061 }
1062
1063 return bytes_len;
1064}
1065
1066void
Greg Clayton238c0a12010-09-18 01:14:36 +00001067ScriptInterpreterPython::CollectDataForBreakpointCommandCallback (BreakpointOptions *bp_options,
Chris Lattner24943d22010-06-08 16:52:24 +00001068 CommandReturnObject &result)
1069{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001070 Debugger &debugger = GetCommandInterpreter().GetDebugger();
1071
Greg Clayton63094e02010-06-23 01:19:29 +00001072 InputReaderSP reader_sp (new InputReader (debugger));
Chris Lattner24943d22010-06-08 16:52:24 +00001073
1074 if (reader_sp)
1075 {
1076 Error err = reader_sp->Initialize (
1077 ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback,
1078 bp_options, // baton
1079 eInputReaderGranularityLine, // token size, for feeding data to callback function
1080 "DONE", // end token
1081 "> ", // prompt
1082 true); // echo input
1083
1084 if (err.Success())
Greg Clayton63094e02010-06-23 01:19:29 +00001085 debugger.PushInputReader (reader_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001086 else
1087 {
1088 result.AppendError (err.AsCString());
1089 result.SetStatus (eReturnStatusFailed);
1090 }
1091 }
1092 else
1093 {
1094 result.AppendError("out of memory");
1095 result.SetStatus (eReturnStatusFailed);
1096 }
1097}
1098
Johnny Chen3e0571b2010-09-11 00:23:59 +00001099// Set a Python one-liner as the callback for the breakpoint.
Johnny Chend1c2dca2010-09-10 18:21:10 +00001100void
Greg Clayton238c0a12010-09-18 01:14:36 +00001101ScriptInterpreterPython::SetBreakpointCommandCallback (BreakpointOptions *bp_options,
Johnny Chend1c2dca2010-09-10 18:21:10 +00001102 const char *oneliner)
1103{
1104 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1105
1106 // It's necessary to set both user_source and script_source to the oneliner.
1107 // The former is used to generate callback description (as in breakpoint command list)
1108 // while the latter is used for Python to interpret during the actual callback.
Caroline Tice5136f942010-09-27 21:35:15 +00001109
Johnny Chend1c2dca2010-09-10 18:21:10 +00001110 data_ap->user_source.AppendString (oneliner);
Johnny Chend1c2dca2010-09-10 18:21:10 +00001111
Caroline Tice5136f942010-09-27 21:35:15 +00001112 if (GenerateBreakpointCommandCallbackData (data_ap->user_source, data_ap->script_source))
1113 {
1114 if (data_ap->script_source.GetSize() == 1)
1115 {
1116 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1117 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
1118 }
1119 }
1120
Johnny Chend1c2dca2010-09-10 18:21:10 +00001121 return;
1122}
1123
Chris Lattner24943d22010-06-08 16:52:24 +00001124bool
1125ScriptInterpreterPython::ExportFunctionDefinitionToInterpreter (StringList &function_def)
1126{
1127 // Convert StringList to one long, newline delimited, const char *.
1128 std::string function_def_string;
1129
1130 int num_lines = function_def.GetSize();
1131
1132 for (int i = 0; i < num_lines; ++i)
1133 {
1134 function_def_string.append (function_def.GetStringAtIndex(i));
1135 if (function_def_string.at (function_def_string.length() - 1) != '\n')
1136 function_def_string.append ("\n");
1137
1138 }
1139
1140 return ExecuteMultipleLines (function_def_string.c_str());
1141}
1142
1143bool
1144ScriptInterpreterPython::GenerateBreakpointCommandCallbackData (StringList &user_input, StringList &callback_data)
1145{
1146 static int num_created_functions = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001147 user_input.RemoveBlankLines ();
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001148 int num_lines = user_input.GetSize ();
1149 StreamString sstr;
Chris Lattner24943d22010-06-08 16:52:24 +00001150
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001151 // Check to see if we have any data; if not, just return.
1152 if (user_input.GetSize() == 0)
1153 return false;
1154
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001155 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1156 // frame and breakpoint location as parameters to the function.
Caroline Ticeb447e842010-09-21 19:25:28 +00001157
Caroline Ticeb447e842010-09-21 19:25:28 +00001158
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001159 sstr.Printf ("lldb_autogen_python_bp_callback_func_%d", num_created_functions);
1160 ++num_created_functions;
1161 std::string auto_generated_function_name = sstr.GetData();
Caroline Ticeb447e842010-09-21 19:25:28 +00001162
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001163 sstr.Clear();
Caroline Ticeb447e842010-09-21 19:25:28 +00001164 StringList auto_generated_function;
Caroline Ticeb447e842010-09-21 19:25:28 +00001165
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001166 // Create the function name & definition string.
1167
Caroline Tice0aa2e552011-01-14 00:29:16 +00001168 sstr.Printf ("def %s (frame, bp_loc, dict):", auto_generated_function_name.c_str());
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001169 auto_generated_function.AppendString (sstr.GetData());
Caroline Tice0aa2e552011-01-14 00:29:16 +00001170
1171 // Pre-pend code for setting up the session dictionary.
1172
1173 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1174 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1175 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1176 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1177 // global dictionary.
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001178
1179 // Wrap everything up inside the function, increasing the indentation.
Chris Lattner24943d22010-06-08 16:52:24 +00001180
1181 for (int i = 0; i < num_lines; ++i)
1182 {
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001183 sstr.Clear ();
1184 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1185 auto_generated_function.AppendString (sstr.GetData());
Caroline Ticeb447e842010-09-21 19:25:28 +00001186 }
Chris Lattner24943d22010-06-08 16:52:24 +00001187
Caroline Tice0aa2e552011-01-14 00:29:16 +00001188 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1189 // got written to the values in the global dictionary, not the session dictionary).
1190
1191 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1192 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1193 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1194 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1195
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001196 // Verify that the results are valid Python.
Chris Lattner24943d22010-06-08 16:52:24 +00001197
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001198 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
Caroline Ticeb447e842010-09-21 19:25:28 +00001199 {
Caroline Ticeb447e842010-09-21 19:25:28 +00001200 return false;
Chris Lattner24943d22010-06-08 16:52:24 +00001201 }
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001202
1203 // Store the name of the auto-generated function to be called.
1204
1205 callback_data.AppendString (auto_generated_function_name.c_str());
1206 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001207}
1208
Greg Clayton5144f382010-10-07 17:14:24 +00001209bool
1210ScriptInterpreterPython::BreakpointCallbackFunction
1211(
1212 void *baton,
1213 StoppointCallbackContext *context,
1214 user_id_t break_id,
1215 user_id_t break_loc_id
1216)
1217{
1218 BreakpointOptions::CommandData *bp_option_data = (BreakpointOptions::CommandData *) baton;
1219 const char *python_function_name = bp_option_data->script_source.GetStringAtIndex (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001220
1221 if (!context)
1222 return true;
1223
1224 Target *target = context->exe_ctx.target;
1225
1226 if (!target)
1227 return true;
1228
1229 Debugger &debugger = target->GetDebugger();
1230 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1231 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1232
1233 if (!script_interpreter)
1234 return true;
Greg Clayton5144f382010-10-07 17:14:24 +00001235
1236 if (python_function_name != NULL
1237 && python_function_name[0] != '\0')
1238 {
1239 Thread *thread = context->exe_ctx.thread;
Greg Claytone86cbb92011-03-22 01:14:58 +00001240 const StackFrameSP stop_frame_sp (thread->GetStackFrameSPForStackFramePtr (context->exe_ctx.frame));
Greg Clayton5144f382010-10-07 17:14:24 +00001241 BreakpointSP breakpoint_sp = target->GetBreakpointByID (break_id);
Greg Claytone86cbb92011-03-22 01:14:58 +00001242 if (breakpoint_sp)
Caroline Tice0aa2e552011-01-14 00:29:16 +00001243 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001244 const BreakpointLocationSP bp_loc_sp (breakpoint_sp->FindLocationByID (break_loc_id));
1245
1246 if (stop_frame_sp && bp_loc_sp)
Caroline Tice202f6b82011-01-17 21:55:19 +00001247 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001248 bool ret_val = true;
1249 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
1250 if (CurrentThreadHasPythonLock())
1251 {
1252 python_interpreter->EnterSession ();
1253 ret_val = g_swig_breakpoint_callback (python_function_name,
1254 python_interpreter->m_dictionary_name.c_str(),
1255 stop_frame_sp,
1256 bp_loc_sp);
1257 python_interpreter->LeaveSession ();
1258 }
1259 else
1260 {
1261 while (!GetPythonLock (1))
1262 fprintf (tmp_fh,
1263 "Python interpreter locked on another thread; waiting to acquire lock...\n");
1264 python_interpreter->EnterSession ();
1265 ret_val = g_swig_breakpoint_callback (python_function_name,
1266 python_interpreter->m_dictionary_name.c_str(),
1267 stop_frame_sp,
1268 bp_loc_sp);
1269 python_interpreter->LeaveSession ();
1270 ReleasePythonLock ();
1271 }
1272 return ret_val;
Caroline Tice202f6b82011-01-17 21:55:19 +00001273 }
Caroline Tice0aa2e552011-01-14 00:29:16 +00001274 }
Greg Clayton5144f382010-10-07 17:14:24 +00001275 }
1276 // We currently always true so we stop in case anything goes wrong when
1277 // trying to call the script function
1278 return true;
1279}
Caroline Tice2ade6112010-11-10 19:18:14 +00001280
1281lldb::thread_result_t
1282ScriptInterpreterPython::RunEmbeddedPythonInterpreter (lldb::thread_arg_t baton)
1283{
1284 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
1285
1286 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
1287
1288 if (log)
1289 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread starting...", baton);
1290
1291 char error_str[1024];
1292 const char *pty_slave_name = script_interpreter->m_embedded_python_pty.GetSlaveName (error_str, sizeof (error_str));
Caroline Tice202f6b82011-01-17 21:55:19 +00001293 bool need_to_release_lock = true;
1294 bool safe_to_run = false;
Caroline Tice0aa2e552011-01-14 00:29:16 +00001295
Caroline Tice202f6b82011-01-17 21:55:19 +00001296 if (CurrentThreadHasPythonLock())
1297 {
1298 safe_to_run = true;
1299 need_to_release_lock = false;
1300 }
1301 else
1302 {
1303 int interval = 1;
1304 safe_to_run = GetPythonLock (interval);
1305 while (!safe_to_run)
1306 {
1307 interval = interval * 2;
1308 safe_to_run = GetPythonLock (interval);
1309 }
1310 }
1311
1312 if (pty_slave_name != NULL && safe_to_run)
1313 {
Caroline Tice2ade6112010-11-10 19:18:14 +00001314 StreamString run_string;
Caroline Tice2ade6112010-11-10 19:18:14 +00001315
Caroline Tice202f6b82011-01-17 21:55:19 +00001316 script_interpreter->EnterSession ();
1317
Caroline Tice0aa2e552011-01-14 00:29:16 +00001318 run_string.Printf ("run_one_line (%s, 'save_stderr = sys.stderr')", script_interpreter->m_dictionary_name.c_str());
1319 PyRun_SimpleString (run_string.GetData());
1320 run_string.Clear ();
1321
1322 run_string.Printf ("run_one_line (%s, 'sys.stderr = sys.stdout')", script_interpreter->m_dictionary_name.c_str());
1323 PyRun_SimpleString (run_string.GetData());
1324 run_string.Clear ();
1325
1326 run_string.Printf ("run_one_line (%s, 'save_stdin = sys.stdin')", script_interpreter->m_dictionary_name.c_str());
1327 PyRun_SimpleString (run_string.GetData());
1328 run_string.Clear ();
1329
1330 run_string.Printf ("run_one_line (%s, \"sys.stdin = open ('%s', 'r')\")", script_interpreter->m_dictionary_name.c_str(),
1331 pty_slave_name);
1332 PyRun_SimpleString (run_string.GetData());
1333 run_string.Clear ();
1334
Johnny Chen8054ba32011-03-11 00:28:50 +00001335 // The following call drops into the embedded interpreter loop and stays there until the
1336 // user chooses to exit from the Python interpreter.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001337
Caroline Ticece207c12011-03-11 00:21:55 +00001338 // When in the embedded interpreter, the user can call arbitrary system and Python stuff, which may require
Johnny Chen8054ba32011-03-11 00:28:50 +00001339 // the ability to run multi-threaded stuff, so we need to surround the call to the embedded interpreter with
Caroline Ticece207c12011-03-11 00:21:55 +00001340 // calls to Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS.
1341
1342 // We ALSO need to surround the call to the embedded interpreter with calls to PyGILState_Ensure and
1343 // PyGILState_Release. This is because this embedded interpreter is being run on a DIFFERENT THREAD than
1344 // the thread on which the call to Py_Initialize (and PyEval_InitThreads) was called. Those initializations
1345 // called PyGILState_Ensure on *that* thread, but it also needs to be called on *this* thread. Otherwise,
1346 // if the user calls Python code that does threading stuff, the interpreter state will be off, and things could
1347 // hang (it's happened before).
1348
Caroline Tice9d352ce2011-03-07 23:24:28 +00001349 Py_BEGIN_ALLOW_THREADS
1350 PyGILState_STATE gstate = PyGILState_Ensure();
1351
Caroline Tice0aa2e552011-01-14 00:29:16 +00001352 run_string.Printf ("run_python_interpreter (%s)", script_interpreter->m_dictionary_name.c_str());
1353 PyRun_SimpleString (run_string.GetData());
1354 run_string.Clear ();
Caroline Tice2ade6112010-11-10 19:18:14 +00001355
Caroline Tice9d352ce2011-03-07 23:24:28 +00001356 PyGILState_Release (gstate);
1357 Py_END_ALLOW_THREADS
1358
Caroline Tice0aa2e552011-01-14 00:29:16 +00001359 run_string.Printf ("run_one_line (%s, 'sys.stdin = save_stdin')", script_interpreter->m_dictionary_name.c_str());
1360 PyRun_SimpleString (run_string.GetData());
1361 run_string.Clear();
1362
1363 run_string.Printf ("run_one_line (%s, 'sys.stderr = save_stderr')", script_interpreter->m_dictionary_name.c_str());
1364 PyRun_SimpleString (run_string.GetData());
1365 run_string.Clear();
Caroline Tice202f6b82011-01-17 21:55:19 +00001366
1367 script_interpreter->LeaveSession ();
1368
Caroline Tice2ade6112010-11-10 19:18:14 +00001369 }
1370
Caroline Tice202f6b82011-01-17 21:55:19 +00001371 if (!safe_to_run)
1372 fprintf ((script_interpreter->m_dbg_stdout ? script_interpreter->m_dbg_stdout : stdout),
1373 "Python interpreter locked on another thread; unable to acquire lock.\n");
1374
1375 if (need_to_release_lock)
1376 ReleasePythonLock ();
1377
Caroline Tice2ade6112010-11-10 19:18:14 +00001378 if (script_interpreter->m_embedded_thread_input_reader_sp)
1379 script_interpreter->m_embedded_thread_input_reader_sp->SetIsDone (true);
1380
1381 script_interpreter->m_embedded_python_pty.CloseSlaveFileDescriptor();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001382
1383 script_interpreter->m_pty_slave_is_open = false;
Caroline Tice2ade6112010-11-10 19:18:14 +00001384
1385 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT);
1386 if (log)
1387 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread exiting...", baton);
1388
1389
Johnny Chen8054ba32011-03-11 00:28:50 +00001390 // Clean up the input reader and make the debugger pop it off the stack.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001391 Debugger &debugger = script_interpreter->GetCommandInterpreter().GetDebugger();
Caroline Tice2ade6112010-11-10 19:18:14 +00001392 const InputReaderSP reader_sp = script_interpreter->m_embedded_thread_input_reader_sp;
1393 script_interpreter->m_embedded_thread_input_reader_sp.reset();
1394 debugger.PopInputReader (reader_sp);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001395
Caroline Tice2ade6112010-11-10 19:18:14 +00001396 return NULL;
1397}
1398
1399
Caroline Tice0aa2e552011-01-14 00:29:16 +00001400void
Greg Claytone86cbb92011-03-22 01:14:58 +00001401ScriptInterpreterPython::InitializeInterpreter (SWIGInitCallback python_swig_init_callback,
1402 SWIGBreakpointCallbackFunction python_swig_breakpoint_callback)
1403{
1404 g_swig_init_callback = python_swig_init_callback;
1405 g_swig_breakpoint_callback = python_swig_breakpoint_callback;
1406}
1407
1408void
1409ScriptInterpreterPython::InitializePrivate ()
Caroline Tice0aa2e552011-01-14 00:29:16 +00001410{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001411 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
1412
Greg Clayton0fdd4a02011-02-07 23:24:47 +00001413 // Python will muck with STDIN terminal state, so save off any current TTY
1414 // settings so we can restore them.
1415 TerminalState stdin_tty_state;
1416 stdin_tty_state.Save(STDIN_FILENO, false);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001417
1418 // Find the module that owns this code and use that path we get to
1419 // set the PYTHONPATH appropriately.
1420
1421 FileSpec file_spec;
1422 char python_dir_path[PATH_MAX];
1423 if (Host::GetLLDBPath (ePathTypePythonDir, file_spec))
1424 {
1425 std::string python_path;
1426 const char *curr_python_path = ::getenv ("PYTHONPATH");
1427 if (curr_python_path)
1428 {
1429 // We have a current value for PYTHONPATH, so lets append to it
1430 python_path.append (curr_python_path);
1431 }
1432
1433 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
1434 {
1435 if (!python_path.empty())
1436 python_path.append (1, ':');
1437 python_path.append (python_dir_path);
1438 }
1439
1440 if (Host::GetLLDBPath (ePathTypeLLDBShlibDir, file_spec))
1441 {
1442 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
1443 {
1444 if (!python_path.empty())
1445 python_path.append (1, ':');
1446 python_path.append (python_dir_path);
1447 }
1448 }
1449 const char *pathon_path_env_cstr = python_path.c_str();
1450 ::setenv ("PYTHONPATH", pathon_path_env_cstr, 1);
1451 }
1452
Caroline Tice9d352ce2011-03-07 23:24:28 +00001453 PyEval_InitThreads ();
Caroline Ticea54461d2011-06-02 22:09:43 +00001454 Py_InitializeEx (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001455
Greg Claytone86cbb92011-03-22 01:14:58 +00001456 // Initialize SWIG after setting up python
1457 assert (g_swig_init_callback != NULL);
1458 g_swig_init_callback ();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001459
1460 // Update the path python uses to search for modules to include the current directory.
1461
Caroline Ticed4d92832011-06-13 21:33:00 +00001462 PyRun_SimpleString ("import sys");
1463 PyRun_SimpleString ("sys.path.append ('.')");
Caroline Tice0aa2e552011-01-14 00:29:16 +00001464
Caroline Ticed4d92832011-06-13 21:33:00 +00001465 PyRun_SimpleString ("import embedded_interpreter");
Caroline Tice0aa2e552011-01-14 00:29:16 +00001466
Caroline Ticed4d92832011-06-13 21:33:00 +00001467 PyRun_SimpleString ("from embedded_interpreter import run_python_interpreter");
1468 PyRun_SimpleString ("from embedded_interpreter import run_one_line");
1469 PyRun_SimpleString ("import sys");
1470 PyRun_SimpleString ("from termios import *");
Greg Clayton99208582011-02-07 19:04:58 +00001471
Greg Clayton0fdd4a02011-02-07 23:24:47 +00001472 stdin_tty_state.Restore();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001473}
1474
Greg Claytone86cbb92011-03-22 01:14:58 +00001475//void
1476//ScriptInterpreterPython::Terminate ()
1477//{
1478// // We are intentionally NOT calling Py_Finalize here (this would be the logical place to call it). Calling
1479// // Py_Finalize here causes test suite runs to seg fault: The test suite runs in Python. It registers
1480// // SBDebugger::Terminate to be called 'at_exit'. When the test suite Python harness finishes up, it calls
1481// // Py_Finalize, which calls all the 'at_exit' registered functions. SBDebugger::Terminate calls Debugger::Terminate,
1482// // which calls lldb::Terminate, which calls ScriptInterpreter::Terminate, which calls
1483// // ScriptInterpreterPython::Terminate. So if we call Py_Finalize here, we end up with Py_Finalize being called from
1484// // within Py_Finalize, which results in a seg fault.
1485// //
1486// // Since this function only gets called when lldb is shutting down and going away anyway, the fact that we don't
1487// // actually call Py_Finalize should not cause any problems (everything should shut down/go away anyway when the
1488// // process exits).
1489// //
1490//// Py_Finalize ();
1491//}