blob: 57a5929fc585949553e4f4a858f8911963642a34 [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;
Enrico Granataf7a9b142011-07-15 02:26:42 +000037static ScriptInterpreter::SWIGPythonTypeScriptCallbackFunction g_swig_typescript_callback = NULL;
Greg Claytone86cbb92011-03-22 01:14:58 +000038
Chris Lattner24943d22010-06-08 16:52:24 +000039
40static int
41_check_and_flush (FILE *stream)
42{
43 int prev_fail = ferror (stream);
44 return fflush (stream) || prev_fail ? EOF : 0;
45}
46
Caroline Tice202f6b82011-01-17 21:55:19 +000047static Predicate<lldb::tid_t> &
48PythonMutexPredicate ()
Caroline Tice0aa2e552011-01-14 00:29:16 +000049{
Caroline Tice202f6b82011-01-17 21:55:19 +000050 static lldb_private::Predicate<lldb::tid_t> g_interpreter_is_running (LLDB_INVALID_THREAD_ID);
51 return g_interpreter_is_running;
52}
53
54static bool
55CurrentThreadHasPythonLock ()
56{
57 TimeValue timeout;
58
59 timeout = TimeValue::Now(); // Don't wait any time.
60
61 return PythonMutexPredicate().WaitForValueEqualTo (Host::GetCurrentThreadID(), &timeout, NULL);
62}
63
64static bool
65GetPythonLock (uint32_t seconds_to_wait)
66{
67
68 TimeValue timeout;
69
70 if (seconds_to_wait != UINT32_MAX)
71 {
72 timeout = TimeValue::Now();
73 timeout.OffsetWithSeconds (seconds_to_wait);
74 }
75
76 return PythonMutexPredicate().WaitForValueEqualToAndSetValueTo (LLDB_INVALID_THREAD_ID,
77 Host::GetCurrentThreadID(), &timeout, NULL);
78}
79
80static void
81ReleasePythonLock ()
82{
83 PythonMutexPredicate().SetValue (LLDB_INVALID_THREAD_ID, eBroadcastAlways);
Caroline Tice0aa2e552011-01-14 00:29:16 +000084}
85
Greg Clayton63094e02010-06-23 01:19:29 +000086ScriptInterpreterPython::ScriptInterpreterPython (CommandInterpreter &interpreter) :
Greg Clayton238c0a12010-09-18 01:14:36 +000087 ScriptInterpreter (interpreter, eScriptLanguagePython),
Caroline Tice0aa2e552011-01-14 00:29:16 +000088 m_embedded_python_pty (),
89 m_embedded_thread_input_reader_sp (),
Greg Clayton58928562011-02-09 01:08:52 +000090 m_dbg_stdout (interpreter.GetDebugger().GetOutputFile().GetStream()),
Caroline Tice0aa2e552011-01-14 00:29:16 +000091 m_new_sysout (NULL),
92 m_dictionary_name (interpreter.GetDebugger().GetInstanceName().AsCString()),
Greg Clayton0fdd4a02011-02-07 23:24:47 +000093 m_terminal_state (),
Caroline Tice0aa2e552011-01-14 00:29:16 +000094 m_session_is_active (false),
95 m_pty_slave_is_open (false),
96 m_valid_session (true)
Chris Lattner24943d22010-06-08 16:52:24 +000097{
98
Greg Clayton7c330d62011-01-27 01:01:10 +000099 static int g_initialized = false;
100
101 if (!g_initialized)
102 {
103 g_initialized = true;
Greg Claytone86cbb92011-03-22 01:14:58 +0000104 ScriptInterpreterPython::InitializePrivate ();
Greg Clayton7c330d62011-01-27 01:01:10 +0000105 }
106
Caroline Tice202f6b82011-01-17 21:55:19 +0000107 bool safe_to_run = false;
108 bool need_to_release_lock = true;
109 int interval = 5; // Number of seconds to try getting the Python lock before timing out.
110
111 // We don't dare exit this function without finishing setting up the script interpreter, so we must wait until
112 // we can get the Python lock.
113
114 if (CurrentThreadHasPythonLock())
115 {
116 safe_to_run = true;
117 need_to_release_lock = false;
118 }
119
120 while (!safe_to_run)
121 {
122 safe_to_run = GetPythonLock (interval);
123 if (!safe_to_run)
124 {
125 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
126 fprintf (tmp_fh,
127 "Python interpreter is locked on another thread; "
128 "please release interpreter in order to continue.\n");
129 interval = interval * 2;
130 }
131 }
132
Caroline Tice0aa2e552011-01-14 00:29:16 +0000133 m_dictionary_name.append("_dict");
134 StreamString run_string;
135 run_string.Printf ("%s = dict()", m_dictionary_name.c_str());
136 PyRun_SimpleString (run_string.GetData());
Caroline Tice5867f6b2010-10-18 18:24:17 +0000137
Caroline Tice0aa2e552011-01-14 00:29:16 +0000138 run_string.Clear();
139 run_string.Printf ("run_one_line (%s, 'import sys')", m_dictionary_name.c_str());
140 PyRun_SimpleString (run_string.GetData());
141
142 // Importing 'lldb' module calls SBDebugger::Initialize, which calls Debugger::Initialize, which increments a
143 // global debugger ref-count; therefore we need to check the ref-count before and after importing lldb, and if the
144 // ref-count increased we need to call Debugger::Terminate here to decrement the ref-count so that when the final
145 // call to Debugger::Terminate is made, the ref-count has the correct value.
146 //
147 // Bonus question: Why doesn't the ref-count always increase? Because sometimes lldb has already been imported, in
148 // which case the code inside it, including the call to SBDebugger::Initialize(), does not get executed.
Caroline Tice5867f6b2010-10-18 18:24:17 +0000149
Caroline Tice0aa2e552011-01-14 00:29:16 +0000150 int old_count = Debugger::TestDebuggerRefCount();
Chris Lattner24943d22010-06-08 16:52:24 +0000151
Caroline Tice0aa2e552011-01-14 00:29:16 +0000152 run_string.Clear();
153 run_string.Printf ("run_one_line (%s, 'import lldb')", m_dictionary_name.c_str());
154 PyRun_SimpleString (run_string.GetData());
Greg Clayton24b48ff2010-10-17 22:03:32 +0000155
Caroline Tice0aa2e552011-01-14 00:29:16 +0000156 int new_count = Debugger::TestDebuggerRefCount();
Chris Lattner24943d22010-06-08 16:52:24 +0000157
Caroline Tice0aa2e552011-01-14 00:29:16 +0000158 if (new_count > old_count)
159 Debugger::Terminate();
Caroline Tice5867f6b2010-10-18 18:24:17 +0000160
Caroline Tice0aa2e552011-01-14 00:29:16 +0000161 run_string.Clear();
162 run_string.Printf ("run_one_line (%s, 'import copy')", m_dictionary_name.c_str());
163 PyRun_SimpleString (run_string.GetData());
164
165 run_string.Clear();
166 run_string.Printf ("run_one_line (%s, 'lldb.debugger_unique_id = %d')", m_dictionary_name.c_str(),
167 interpreter.GetDebugger().GetID());
168 PyRun_SimpleString (run_string.GetData());
169
170 if (m_dbg_stdout != NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000171 {
Caroline Tice0aa2e552011-01-14 00:29:16 +0000172 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
Caroline Tice5867f6b2010-10-18 18:24:17 +0000173 }
Caroline Tice202f6b82011-01-17 21:55:19 +0000174
175 if (need_to_release_lock)
176 ReleasePythonLock();
Chris Lattner24943d22010-06-08 16:52:24 +0000177}
178
179ScriptInterpreterPython::~ScriptInterpreterPython ()
180{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000181 Debugger &debugger = GetCommandInterpreter().GetDebugger();
182
183 if (m_embedded_thread_input_reader_sp.get() != NULL)
184 {
185 m_embedded_thread_input_reader_sp->SetIsDone (true);
186 m_embedded_python_pty.CloseSlaveFileDescriptor();
187 m_pty_slave_is_open = false;
188 const InputReaderSP reader_sp = m_embedded_thread_input_reader_sp;
189 m_embedded_thread_input_reader_sp.reset();
190 debugger.PopInputReader (reader_sp);
191 }
192
193 if (m_new_sysout)
194 {
Caroline Tice202f6b82011-01-17 21:55:19 +0000195 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
196 if (!CurrentThreadHasPythonLock ())
197 {
198 while (!GetPythonLock (1))
199 fprintf (tmp_fh, "Python interpreter locked on another thread; waiting to acquire lock...\n");
200 Py_DECREF (m_new_sysout);
201 ReleasePythonLock ();
202 }
203 else
204 Py_DECREF (m_new_sysout);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000205 }
Chris Lattner24943d22010-06-08 16:52:24 +0000206}
207
Caroline Tice0aa2e552011-01-14 00:29:16 +0000208void
209ScriptInterpreterPython::ResetOutputFileHandle (FILE *fh)
210{
211 if (fh == NULL)
212 return;
213
214 m_dbg_stdout = fh;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000215
Caroline Tice202f6b82011-01-17 21:55:19 +0000216 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
217 if (!CurrentThreadHasPythonLock ())
218 {
219 while (!GetPythonLock (1))
220 fprintf (tmp_fh, "Python interpreter locked on another thread; waiting to acquire lock...\n");
221 EnterSession ();
222 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
223 LeaveSession ();
224 ReleasePythonLock ();
225 }
226 else
227 {
228 EnterSession ();
229 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
230 LeaveSession ();
231 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000232}
233
234void
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000235ScriptInterpreterPython::SaveTerminalState (int fd)
236{
237 // Python mucks with the terminal state of STDIN. If we can possibly avoid
238 // this by setting the file handles up correctly prior to entering the
239 // interpreter we should. For now we save and restore the terminal state
240 // on the input file handle.
241 m_terminal_state.Save (fd, false);
242}
243
244void
245ScriptInterpreterPython::RestoreTerminalState ()
246{
247 // Python mucks with the terminal state of STDIN. If we can possibly avoid
248 // this by setting the file handles up correctly prior to entering the
249 // interpreter we should. For now we save and restore the terminal state
250 // on the input file handle.
251 m_terminal_state.Restore();
252}
253
254
255
256void
Caroline Tice0aa2e552011-01-14 00:29:16 +0000257ScriptInterpreterPython::LeaveSession ()
258{
259 m_session_is_active = false;
260}
261
262void
263ScriptInterpreterPython::EnterSession ()
264{
265 // If we have already entered the session, without having officially 'left' it, then there is no need to
266 // 'enter' it again.
267
268 if (m_session_is_active)
269 return;
270
271 m_session_is_active = true;
272
Caroline Tice202f6b82011-01-17 21:55:19 +0000273 StreamString run_string;
274
275 run_string.Printf ("run_one_line (%s, 'lldb.debugger_unique_id = %d')", m_dictionary_name.c_str(),
276 GetCommandInterpreter().GetDebugger().GetID());
277 PyRun_SimpleString (run_string.GetData());
Caroline Tice6af65cb2011-05-03 21:21:50 +0000278 run_string.Clear();
Caroline Tice202f6b82011-01-17 21:55:19 +0000279
Caroline Tice0aa2e552011-01-14 00:29:16 +0000280
Caroline Tice6af65cb2011-05-03 21:21:50 +0000281 run_string.Printf ("run_one_line (%s, 'lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%d)')",
282 m_dictionary_name.c_str(),
283 GetCommandInterpreter().GetDebugger().GetID());
284 PyRun_SimpleString (run_string.GetData());
285 run_string.Clear();
286
287
288 ExecutionContext exe_ctx = m_interpreter.GetDebugger().GetSelectedExecutionContext();
289
290 if (exe_ctx.target)
291 run_string.Printf ("run_one_line (%s, 'lldb.target = lldb.debugger.GetSelectedTarget()')",
292 m_dictionary_name.c_str());
293 else
294 run_string.Printf ("run_one_line (%s, 'lldb.target = None')", m_dictionary_name.c_str());
295 PyRun_SimpleString (run_string.GetData());
296 run_string.Clear();
297
298 if (exe_ctx.process)
299 run_string.Printf ("run_one_line (%s, 'lldb.process = lldb.target.GetProcess()')", m_dictionary_name.c_str());
300 else
301 run_string.Printf ("run_one_line (%s, 'lldb.process = None')", m_dictionary_name.c_str());
302 PyRun_SimpleString (run_string.GetData());
303 run_string.Clear();
304
305 if (exe_ctx.thread)
306 run_string.Printf ("run_one_line (%s, 'lldb.thread = lldb.process.GetSelectedThread ()')",
307 m_dictionary_name.c_str());
308 else
309 run_string.Printf ("run_one_line (%s, 'lldb.thread = None')", m_dictionary_name.c_str());
310 PyRun_SimpleString (run_string.GetData());
311 run_string.Clear();
312
313 if (exe_ctx.frame)
314 run_string.Printf ("run_one_line (%s, 'lldb.frame = lldb.thread.GetSelectedFrame ()')",
315 m_dictionary_name.c_str());
316 else
317 run_string.Printf ("run_one_line (%s, 'lldb.frame = None')", m_dictionary_name.c_str());
318 PyRun_SimpleString (run_string.GetData());
319 run_string.Clear();
320
Caroline Tice0aa2e552011-01-14 00:29:16 +0000321 PyObject *sysmod = PyImport_AddModule ("sys");
322 PyObject *sysdict = PyModule_GetDict (sysmod);
323
324 if ((m_new_sysout != NULL)
325 && (sysmod != NULL)
326 && (sysdict != NULL))
327 PyDict_SetItemString (sysdict, "stdout", m_new_sysout);
328
329 if (PyErr_Occurred())
330 PyErr_Clear ();
331
Caroline Tice0aa2e552011-01-14 00:29:16 +0000332 if (!m_pty_slave_is_open)
333 {
Caroline Tice202f6b82011-01-17 21:55:19 +0000334 run_string.Clear();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000335 run_string.Printf ("run_one_line (%s, \"new_stdin = open('%s', 'r')\")", m_dictionary_name.c_str(),
336 m_pty_slave_name.c_str());
337 PyRun_SimpleString (run_string.GetData());
338 m_pty_slave_is_open = true;
339
340 run_string.Clear();
341 run_string.Printf ("run_one_line (%s, 'sys.stdin = new_stdin')", m_dictionary_name.c_str());
342 PyRun_SimpleString (run_string.GetData());
343 }
344}
345
346
Johnny Chen60dde642010-07-30 22:33:14 +0000347bool
Greg Clayton238c0a12010-09-18 01:14:36 +0000348ScriptInterpreterPython::ExecuteOneLine (const char *command, CommandReturnObject *result)
Chris Lattner24943d22010-06-08 16:52:24 +0000349{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000350 if (!m_valid_session)
351 return false;
352
Caroline Tice0aa2e552011-01-14 00:29:16 +0000353
Caroline Tice0aa2e552011-01-14 00:29:16 +0000354
Caroline Tice4a461da2011-01-14 21:09:29 +0000355 // We want to call run_one_line, passing in the dictionary and the command string. We cannot do this through
356 // PyRun_SimpleString here because the command string may contain escaped characters, and putting it inside
357 // another string to pass to PyRun_SimpleString messes up the escaping. So we use the following more complicated
358 // method to pass the command string directly down to Python.
359
360
Caroline Tice202f6b82011-01-17 21:55:19 +0000361 bool need_to_release_lock = true;
362
363 if (CurrentThreadHasPythonLock())
364 need_to_release_lock = false;
365 else if (!GetPythonLock (1))
366 {
367 fprintf ((m_dbg_stdout ? m_dbg_stdout : stdout),
368 "Python interpreter is currently locked by another thread; unable to process command.\n");
369 return false;
370 }
371
372 EnterSession ();
Caroline Tice4a461da2011-01-14 21:09:29 +0000373 bool success = false;
374
Greg Clayton63094e02010-06-23 01:19:29 +0000375 if (command)
Chris Lattner24943d22010-06-08 16:52:24 +0000376 {
Caroline Tice4a461da2011-01-14 21:09:29 +0000377 // Find the correct script interpreter dictionary in the main module.
378 PyObject *main_mod = PyImport_AddModule ("__main__");
379 PyObject *script_interpreter_dict = NULL;
380 if (main_mod != NULL)
381 {
382 PyObject *main_dict = PyModule_GetDict (main_mod);
383 if ((main_dict != NULL)
384 && PyDict_Check (main_dict))
385 {
386 // Go through the main dictionary looking for the correct python script interpreter dictionary
387 PyObject *key, *value;
388 Py_ssize_t pos = 0;
389
390 while (PyDict_Next (main_dict, &pos, &key, &value))
391 {
392 // We have stolen references to the key and value objects in the dictionary; we need to increment
393 // them now so that Python's garbage collector doesn't collect them out from under us.
394 Py_INCREF (key);
395 Py_INCREF (value);
396 if (strcmp (PyString_AsString (key), m_dictionary_name.c_str()) == 0)
397 {
398 script_interpreter_dict = value;
399 break;
400 }
401 }
402 }
403
404 if (script_interpreter_dict != NULL)
405 {
406 PyObject *pfunc = NULL;
407 PyObject *pmod = PyImport_AddModule ("embedded_interpreter");
408 if (pmod != NULL)
409 {
410 PyObject *pmod_dict = PyModule_GetDict (pmod);
411 if ((pmod_dict != NULL)
412 && PyDict_Check (pmod_dict))
413 {
414 PyObject *key, *value;
415 Py_ssize_t pos = 0;
416
417 while (PyDict_Next (pmod_dict, &pos, &key, &value))
418 {
419 Py_INCREF (key);
420 Py_INCREF (value);
421 if (strcmp (PyString_AsString (key), "run_one_line") == 0)
422 {
423 pfunc = value;
424 break;
425 }
426 }
427
428 PyObject *string_arg = PyString_FromString (command);
429 if (pfunc && string_arg && PyCallable_Check (pfunc))
430 {
431 PyObject *pargs = PyTuple_New (2);
432 if (pargs != NULL)
433 {
434 PyTuple_SetItem (pargs, 0, script_interpreter_dict);
435 PyTuple_SetItem (pargs, 1, string_arg);
436 PyObject *pvalue = PyObject_CallObject (pfunc, pargs);
437 Py_DECREF (pargs);
438 if (pvalue != NULL)
439 {
440 Py_DECREF (pvalue);
441 success = true;
442 }
443 else if (PyErr_Occurred ())
444 {
445 PyErr_Print();
446 PyErr_Clear();
447 }
448 }
449 }
450 }
451 }
452 Py_INCREF (script_interpreter_dict);
453 }
454 }
Greg Clayton63094e02010-06-23 01:19:29 +0000455
Caroline Tice0aa2e552011-01-14 00:29:16 +0000456 LeaveSession ();
457
Caroline Tice202f6b82011-01-17 21:55:19 +0000458 if (need_to_release_lock)
459 ReleasePythonLock();
460
Caroline Tice4a461da2011-01-14 21:09:29 +0000461 if (success)
Johnny Chen60dde642010-07-30 22:33:14 +0000462 return true;
463
464 // The one-liner failed. Append the error message.
465 if (result)
466 result->AppendErrorWithFormat ("python failed attempting to evaluate '%s'\n", command);
467 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000468 }
Johnny Chen60dde642010-07-30 22:33:14 +0000469
Caroline Tice0aa2e552011-01-14 00:29:16 +0000470 LeaveSession ();
Caroline Tice202f6b82011-01-17 21:55:19 +0000471
472 if (need_to_release_lock)
473 ReleasePythonLock ();
474
Johnny Chen60dde642010-07-30 22:33:14 +0000475 if (result)
476 result->AppendError ("empty command passed to python\n");
477 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000478}
479
480
481
482size_t
483ScriptInterpreterPython::InputReaderCallback
484(
485 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000486 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000487 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000488 const char *bytes,
489 size_t bytes_len
490)
491{
Caroline Tice2ade6112010-11-10 19:18:14 +0000492 lldb::thread_t embedded_interpreter_thread;
493 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
494
Chris Lattner24943d22010-06-08 16:52:24 +0000495 if (baton == NULL)
496 return 0;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000497
498 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
499
500 if (script_interpreter->m_script_lang != eScriptLanguagePython)
501 return 0;
502
Caroline Tice892fadd2011-06-16 16:27:19 +0000503 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
504 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
505
Chris Lattner24943d22010-06-08 16:52:24 +0000506 switch (notification)
507 {
508 case eInputReaderActivate:
509 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000510 if (!batch_mode)
511 {
512 out_stream->Printf ("Python Interactive Interpreter. To exit, type 'quit()', 'exit()' or Ctrl-D.\n");
513 out_stream->Flush();
514 }
Greg Clayton58928562011-02-09 01:08:52 +0000515
Chris Lattner24943d22010-06-08 16:52:24 +0000516 // Save terminal settings if we can
Greg Clayton58928562011-02-09 01:08:52 +0000517 int input_fd = reader.GetDebugger().GetInputFile().GetDescriptor();
518 if (input_fd == File::kInvalidDescriptor)
Greg Clayton24b48ff2010-10-17 22:03:32 +0000519 input_fd = STDIN_FILENO;
Caroline Ticec95c6d12010-09-14 22:49:06 +0000520
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000521 script_interpreter->SaveTerminalState(input_fd);
Greg Clayton99208582011-02-07 19:04:58 +0000522
Caroline Tice202f6b82011-01-17 21:55:19 +0000523 if (!CurrentThreadHasPythonLock())
524 {
525 while (!GetPythonLock(1))
526 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000527 out_stream->Printf ("Python interpreter locked on another thread; waiting to acquire lock...\n");
528 out_stream->Flush();
Caroline Tice202f6b82011-01-17 21:55:19 +0000529 }
530 script_interpreter->EnterSession ();
531 ReleasePythonLock();
532 }
533 else
534 script_interpreter->EnterSession ();
535
Caroline Tice2ade6112010-11-10 19:18:14 +0000536 char error_str[1024];
537 if (script_interpreter->m_embedded_python_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, error_str,
538 sizeof(error_str)))
539 {
540 if (log)
541 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in opening master pty (fd = %d).",
542 script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor());
543 embedded_interpreter_thread = Host::ThreadCreate ("<lldb.script-interpreter.embedded-python-loop>",
544 ScriptInterpreterPython::RunEmbeddedPythonInterpreter,
545 script_interpreter, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +0000546 if (IS_VALID_LLDB_HOST_THREAD(embedded_interpreter_thread))
Caroline Tice2ade6112010-11-10 19:18:14 +0000547 {
548 if (log)
549 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in creating thread (thread = %d)", embedded_interpreter_thread);
550 Error detach_error;
551 Host::ThreadDetach (embedded_interpreter_thread, &detach_error);
552 }
553 else
554 {
555 if (log)
556 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed in creating thread");
557 reader.SetIsDone (true);
558 }
559 }
560 else
561 {
562 if (log)
563 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed to open master pty ");
564 reader.SetIsDone (true);
565 }
Chris Lattner24943d22010-06-08 16:52:24 +0000566 }
567 break;
568
569 case eInputReaderDeactivate:
Caroline Tice0aa2e552011-01-14 00:29:16 +0000570 script_interpreter->LeaveSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000571 break;
572
573 case eInputReaderReactivate:
Caroline Tice202f6b82011-01-17 21:55:19 +0000574 if (!CurrentThreadHasPythonLock())
575 {
576 while (!GetPythonLock(1))
577 {
578 // Wait until lock is acquired.
579 }
580 script_interpreter->EnterSession ();
581 ReleasePythonLock();
582 }
583 else
584 script_interpreter->EnterSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000585 break;
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000586
Caroline Tice4a348082011-05-02 20:41:46 +0000587 case eInputReaderAsynchronousOutputWritten:
588 break;
589
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000590 case eInputReaderInterrupt:
591 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "raise KeyboardInterrupt\n", 24);
592 break;
593
594 case eInputReaderEndOfFile:
595 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()\n", 7);
596 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000597
598 case eInputReaderGotToken:
Caroline Tice2ade6112010-11-10 19:18:14 +0000599 if (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor() != -1)
Chris Lattner24943d22010-06-08 16:52:24 +0000600 {
Caroline Tice2ade6112010-11-10 19:18:14 +0000601 if (log)
602 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %d", bytes,
603 bytes_len);
604 if (bytes && bytes_len)
605 {
606 if ((int) bytes[0] == 4)
607 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()", 6);
608 else
609 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), bytes, bytes_len);
610 }
611 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "\n", 1);
Chris Lattner24943d22010-06-08 16:52:24 +0000612 }
Caroline Tice2ade6112010-11-10 19:18:14 +0000613 else
614 {
615 if (log)
616 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %d, Master File Descriptor is bad.",
617 bytes,
618 bytes_len);
619 reader.SetIsDone (true);
620 }
621
Chris Lattner24943d22010-06-08 16:52:24 +0000622 break;
623
624 case eInputReaderDone:
Caroline Tice0aa2e552011-01-14 00:29:16 +0000625 script_interpreter->LeaveSession ();
626
Chris Lattner24943d22010-06-08 16:52:24 +0000627 // Restore terminal settings if they were validly saved
Caroline Tice2ade6112010-11-10 19:18:14 +0000628 if (log)
629 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Done, closing down input reader.");
Caroline Ticec95c6d12010-09-14 22:49:06 +0000630
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000631 script_interpreter->RestoreTerminalState ();
632
Caroline Tice2ade6112010-11-10 19:18:14 +0000633 script_interpreter->m_embedded_python_pty.CloseMasterFileDescriptor();
Chris Lattner24943d22010-06-08 16:52:24 +0000634 break;
635 }
636
637 return bytes_len;
638}
639
640
641void
Greg Clayton238c0a12010-09-18 01:14:36 +0000642ScriptInterpreterPython::ExecuteInterpreterLoop ()
Chris Lattner24943d22010-06-08 16:52:24 +0000643{
644 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
645
Caroline Tice0aa2e552011-01-14 00:29:16 +0000646 Debugger &debugger = GetCommandInterpreter().GetDebugger();
Caroline Ticec95c6d12010-09-14 22:49:06 +0000647
648 // At the moment, the only time the debugger does not have an input file handle is when this is called
649 // directly from Python, in which case it is both dangerous and unnecessary (not to mention confusing) to
650 // try to embed a running interpreter loop inside the already running Python interpreter loop, so we won't
651 // do it.
652
Greg Clayton58928562011-02-09 01:08:52 +0000653 if (!debugger.GetInputFile().IsValid())
Caroline Ticec95c6d12010-09-14 22:49:06 +0000654 return;
655
Greg Clayton63094e02010-06-23 01:19:29 +0000656 InputReaderSP reader_sp (new InputReader(debugger));
Chris Lattner24943d22010-06-08 16:52:24 +0000657 if (reader_sp)
658 {
659 Error error (reader_sp->Initialize (ScriptInterpreterPython::InputReaderCallback,
660 this, // baton
661 eInputReaderGranularityLine, // token size, to pass to callback function
662 NULL, // end token
663 NULL, // prompt
664 true)); // echo input
665
666 if (error.Success())
667 {
Greg Clayton63094e02010-06-23 01:19:29 +0000668 debugger.PushInputReader (reader_sp);
Caroline Tice2ade6112010-11-10 19:18:14 +0000669 m_embedded_thread_input_reader_sp = reader_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000670 }
671 }
672}
673
674bool
675ScriptInterpreterPython::ExecuteOneLineWithReturn (const char *in_string,
676 ScriptInterpreter::ReturnType return_type,
677 void *ret_value)
678{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000679
Caroline Tice202f6b82011-01-17 21:55:19 +0000680 bool need_to_release_lock = true;
681
682 if (CurrentThreadHasPythonLock())
683 need_to_release_lock = false;
684 else if (!GetPythonLock (1))
685 {
686 fprintf ((m_dbg_stdout ? m_dbg_stdout : stdout),
687 "Python interpreter is currently locked by another thread; unable to process command.\n");
688 return false;
689 }
690
691 EnterSession ();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000692
Chris Lattner24943d22010-06-08 16:52:24 +0000693 PyObject *py_return = NULL;
694 PyObject *mainmod = PyImport_AddModule ("__main__");
695 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000696 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000697 PyObject *py_error = NULL;
698 bool ret_success;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000699 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000700 int success;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000701
702 if (PyDict_Check (globals))
703 {
704 PyObject *key, *value;
705 Py_ssize_t pos = 0;
706
707 int i = 0;
708 while (PyDict_Next (globals, &pos, &key, &value))
709 {
710 // We have stolen references to the key and value objects in the dictionary; we need to increment them now
711 // so that Python's garbage collector doesn't collect them out from under us.
712 Py_INCREF (key);
713 Py_INCREF (value);
714 char *c_str = PyString_AsString (key);
715 if (strcmp (c_str, m_dictionary_name.c_str()) == 0)
716 locals = value;
717 ++i;
718 }
719 }
Chris Lattner24943d22010-06-08 16:52:24 +0000720
Caroline Tice0aa2e552011-01-14 00:29:16 +0000721 if (locals == NULL)
722 {
723 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
724 should_decrement_locals = true;
725 }
726
727 if (locals == NULL)
728 {
729 locals = globals;
730 should_decrement_locals = false;
731 }
732
733 py_error = PyErr_Occurred();
734 if (py_error != NULL)
735 PyErr_Clear();
736
Chris Lattner24943d22010-06-08 16:52:24 +0000737 if (in_string != NULL)
738 {
739 py_return = PyRun_String (in_string, Py_eval_input, globals, locals);
740 if (py_return == NULL)
741 {
742 py_error = PyErr_Occurred ();
743 if (py_error != NULL)
744 PyErr_Clear ();
745
746 py_return = PyRun_String (in_string, Py_single_input, globals, locals);
747 }
748
Caroline Tice0aa2e552011-01-14 00:29:16 +0000749 if (locals != NULL
750 && should_decrement_locals)
751 Py_DECREF (locals);
752
Chris Lattner24943d22010-06-08 16:52:24 +0000753 if (py_return != NULL)
754 {
755 switch (return_type)
756 {
757 case eCharPtr: // "char *"
758 {
759 const char format[3] = "s#";
760 success = PyArg_Parse (py_return, format, (char **) &ret_value);
761 break;
762 }
763 case eBool:
764 {
765 const char format[2] = "b";
766 success = PyArg_Parse (py_return, format, (bool *) ret_value);
767 break;
768 }
769 case eShortInt:
770 {
771 const char format[2] = "h";
772 success = PyArg_Parse (py_return, format, (short *) ret_value);
773 break;
774 }
775 case eShortIntUnsigned:
776 {
777 const char format[2] = "H";
778 success = PyArg_Parse (py_return, format, (unsigned short *) ret_value);
779 break;
780 }
781 case eInt:
782 {
783 const char format[2] = "i";
784 success = PyArg_Parse (py_return, format, (int *) ret_value);
785 break;
786 }
787 case eIntUnsigned:
788 {
789 const char format[2] = "I";
790 success = PyArg_Parse (py_return, format, (unsigned int *) ret_value);
791 break;
792 }
793 case eLongInt:
794 {
795 const char format[2] = "l";
796 success = PyArg_Parse (py_return, format, (long *) ret_value);
797 break;
798 }
799 case eLongIntUnsigned:
800 {
801 const char format[2] = "k";
802 success = PyArg_Parse (py_return, format, (unsigned long *) ret_value);
803 break;
804 }
805 case eLongLong:
806 {
807 const char format[2] = "L";
808 success = PyArg_Parse (py_return, format, (long long *) ret_value);
809 break;
810 }
811 case eLongLongUnsigned:
812 {
813 const char format[2] = "K";
814 success = PyArg_Parse (py_return, format, (unsigned long long *) ret_value);
815 break;
816 }
817 case eFloat:
818 {
819 const char format[2] = "f";
820 success = PyArg_Parse (py_return, format, (float *) ret_value);
821 break;
822 }
823 case eDouble:
824 {
825 const char format[2] = "d";
826 success = PyArg_Parse (py_return, format, (double *) ret_value);
827 break;
828 }
829 case eChar:
830 {
831 const char format[2] = "c";
832 success = PyArg_Parse (py_return, format, (char *) ret_value);
833 break;
834 }
835 default:
836 {}
837 }
838 Py_DECREF (py_return);
839 if (success)
840 ret_success = true;
841 else
842 ret_success = false;
843 }
844 }
845
846 py_error = PyErr_Occurred();
847 if (py_error != NULL)
848 {
849 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
850 PyErr_Print ();
851 PyErr_Clear();
852 ret_success = false;
853 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000854
855 LeaveSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000856
Caroline Tice202f6b82011-01-17 21:55:19 +0000857 if (need_to_release_lock)
858 ReleasePythonLock();
859
Chris Lattner24943d22010-06-08 16:52:24 +0000860 return ret_success;
861}
862
863bool
864ScriptInterpreterPython::ExecuteMultipleLines (const char *in_string)
865{
Caroline Tice202f6b82011-01-17 21:55:19 +0000866 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
867 bool need_to_release_lock = true;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000868
Caroline Tice202f6b82011-01-17 21:55:19 +0000869 if (CurrentThreadHasPythonLock())
870 need_to_release_lock = false;
871 else
872 {
873 while (!GetPythonLock (1))
874 fprintf (tmp_fh, "Python interpreter locked on another thread; waiting to acquire lock...\n");
875 }
876
877 EnterSession ();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000878
Chris Lattner24943d22010-06-08 16:52:24 +0000879 bool success = false;
880 PyObject *py_return = NULL;
881 PyObject *mainmod = PyImport_AddModule ("__main__");
882 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000883 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000884 PyObject *py_error = NULL;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000885 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000886
Caroline Tice0aa2e552011-01-14 00:29:16 +0000887 if (PyDict_Check (globals))
888 {
889 PyObject *key, *value;
890 Py_ssize_t pos = 0;
891
892 while (PyDict_Next (globals, &pos, &key, &value))
893 {
894 // We have stolen references to the key and value objects in the dictionary; we need to increment them now
895 // so that Python's garbage collector doesn't collect them out from under us.
896 Py_INCREF (key);
897 Py_INCREF (value);
898 if (strcmp (PyString_AsString (key), m_dictionary_name.c_str()) == 0)
899 locals = value;
900 }
901 }
902
903 if (locals == NULL)
904 {
905 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
906 should_decrement_locals = true;
907 }
908
909 if (locals == NULL)
910 {
911 locals = globals;
912 should_decrement_locals = false;
913 }
914
915 py_error = PyErr_Occurred();
916 if (py_error != NULL)
917 PyErr_Clear();
918
Chris Lattner24943d22010-06-08 16:52:24 +0000919 if (in_string != NULL)
920 {
921 struct _node *compiled_node = PyParser_SimpleParseString (in_string, Py_file_input);
922 if (compiled_node)
923 {
924 PyCodeObject *compiled_code = PyNode_Compile (compiled_node, "temp.py");
925 if (compiled_code)
926 {
927 py_return = PyEval_EvalCode (compiled_code, globals, locals);
928 if (py_return != NULL)
929 {
930 success = true;
931 Py_DECREF (py_return);
932 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000933 if (locals && should_decrement_locals)
934 Py_DECREF (locals);
Chris Lattner24943d22010-06-08 16:52:24 +0000935 }
936 }
937 }
938
939 py_error = PyErr_Occurred ();
940 if (py_error != NULL)
941 {
942 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
943 PyErr_Print ();
944 PyErr_Clear();
945 success = false;
946 }
947
Caroline Tice0aa2e552011-01-14 00:29:16 +0000948 LeaveSession ();
949
Caroline Tice202f6b82011-01-17 21:55:19 +0000950 if (need_to_release_lock)
951 ReleasePythonLock();
952
Chris Lattner24943d22010-06-08 16:52:24 +0000953 return success;
954}
955
956static const char *g_reader_instructions = "Enter your Python command(s). Type 'DONE' to end.";
957
958size_t
959ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback
960(
961 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000962 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000963 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000964 const char *bytes,
965 size_t bytes_len
966)
967{
Caroline Tice892fadd2011-06-16 16:27:19 +0000968 static StringList commands_in_progress;
969
970 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
971 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
972
Chris Lattner24943d22010-06-08 16:52:24 +0000973 switch (notification)
974 {
975 case eInputReaderActivate:
976 {
977 commands_in_progress.Clear();
Caroline Tice892fadd2011-06-16 16:27:19 +0000978 if (!batch_mode)
Chris Lattner24943d22010-06-08 16:52:24 +0000979 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000980 out_stream->Printf ("%s\n", g_reader_instructions);
Greg Clayton63094e02010-06-23 01:19:29 +0000981 if (reader.GetPrompt())
Caroline Tice892fadd2011-06-16 16:27:19 +0000982 out_stream->Printf ("%s", reader.GetPrompt());
983 out_stream->Flush ();
Chris Lattner24943d22010-06-08 16:52:24 +0000984 }
985 }
986 break;
987
988 case eInputReaderDeactivate:
989 break;
990
991 case eInputReaderReactivate:
Caroline Tice892fadd2011-06-16 16:27:19 +0000992 if (reader.GetPrompt() && !batch_mode)
Caroline Ticef81b4c52010-10-27 18:34:42 +0000993 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000994 out_stream->Printf ("%s", reader.GetPrompt());
995 out_stream->Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +0000996 }
Chris Lattner24943d22010-06-08 16:52:24 +0000997 break;
998
Caroline Tice4a348082011-05-02 20:41:46 +0000999 case eInputReaderAsynchronousOutputWritten:
1000 break;
1001
Chris Lattner24943d22010-06-08 16:52:24 +00001002 case eInputReaderGotToken:
1003 {
1004 std::string temp_string (bytes, bytes_len);
1005 commands_in_progress.AppendString (temp_string.c_str());
Caroline Tice892fadd2011-06-16 16:27:19 +00001006 if (!reader.IsDone() && reader.GetPrompt() && !batch_mode)
Caroline Ticef81b4c52010-10-27 18:34:42 +00001007 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001008 out_stream->Printf ("%s", reader.GetPrompt());
1009 out_stream->Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +00001010 }
Chris Lattner24943d22010-06-08 16:52:24 +00001011 }
1012 break;
1013
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001014 case eInputReaderEndOfFile:
1015 case eInputReaderInterrupt:
1016 // Control-c (SIGINT) & control-d both mean finish & exit.
1017 reader.SetIsDone(true);
1018
1019 // Control-c (SIGINT) ALSO means cancel; do NOT create a breakpoint command.
1020 if (notification == eInputReaderInterrupt)
1021 commands_in_progress.Clear();
1022
1023 // Fall through here...
1024
Chris Lattner24943d22010-06-08 16:52:24 +00001025 case eInputReaderDone:
1026 {
1027 BreakpointOptions *bp_options = (BreakpointOptions *)baton;
1028 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1029 data_ap->user_source.AppendList (commands_in_progress);
1030 if (data_ap.get())
1031 {
Greg Clayton63094e02010-06-23 01:19:29 +00001032 ScriptInterpreter *interpreter = reader.GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
Chris Lattner24943d22010-06-08 16:52:24 +00001033 if (interpreter)
1034 {
1035 if (interpreter->GenerateBreakpointCommandCallbackData (data_ap->user_source,
1036 data_ap->script_source))
1037 {
1038 if (data_ap->script_source.GetSize() == 1)
1039 {
1040 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1041 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
1042 }
1043 }
Caroline Tice892fadd2011-06-16 16:27:19 +00001044 else if (!batch_mode)
1045 {
1046 out_stream->Printf ("Warning: No command attached to breakpoint.\n");
1047 out_stream->Flush();
1048 }
Chris Lattner24943d22010-06-08 16:52:24 +00001049 }
1050 else
1051 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001052 if (!batch_mode)
1053 {
1054 out_stream->Printf ("Warning: Unable to find script intepreter; no command attached to breakpoint.\n");
1055 out_stream->Flush();
1056 }
Chris Lattner24943d22010-06-08 16:52:24 +00001057 }
1058 }
1059 }
1060 break;
1061
1062 }
1063
1064 return bytes_len;
1065}
1066
1067void
Greg Clayton238c0a12010-09-18 01:14:36 +00001068ScriptInterpreterPython::CollectDataForBreakpointCommandCallback (BreakpointOptions *bp_options,
Chris Lattner24943d22010-06-08 16:52:24 +00001069 CommandReturnObject &result)
1070{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001071 Debugger &debugger = GetCommandInterpreter().GetDebugger();
1072
Greg Clayton63094e02010-06-23 01:19:29 +00001073 InputReaderSP reader_sp (new InputReader (debugger));
Chris Lattner24943d22010-06-08 16:52:24 +00001074
1075 if (reader_sp)
1076 {
1077 Error err = reader_sp->Initialize (
1078 ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback,
1079 bp_options, // baton
1080 eInputReaderGranularityLine, // token size, for feeding data to callback function
1081 "DONE", // end token
1082 "> ", // prompt
1083 true); // echo input
1084
1085 if (err.Success())
Greg Clayton63094e02010-06-23 01:19:29 +00001086 debugger.PushInputReader (reader_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001087 else
1088 {
1089 result.AppendError (err.AsCString());
1090 result.SetStatus (eReturnStatusFailed);
1091 }
1092 }
1093 else
1094 {
1095 result.AppendError("out of memory");
1096 result.SetStatus (eReturnStatusFailed);
1097 }
1098}
1099
Johnny Chen3e0571b2010-09-11 00:23:59 +00001100// Set a Python one-liner as the callback for the breakpoint.
Johnny Chend1c2dca2010-09-10 18:21:10 +00001101void
Greg Clayton238c0a12010-09-18 01:14:36 +00001102ScriptInterpreterPython::SetBreakpointCommandCallback (BreakpointOptions *bp_options,
Johnny Chend1c2dca2010-09-10 18:21:10 +00001103 const char *oneliner)
1104{
1105 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1106
1107 // It's necessary to set both user_source and script_source to the oneliner.
1108 // The former is used to generate callback description (as in breakpoint command list)
1109 // while the latter is used for Python to interpret during the actual callback.
Caroline Tice5136f942010-09-27 21:35:15 +00001110
Johnny Chend1c2dca2010-09-10 18:21:10 +00001111 data_ap->user_source.AppendString (oneliner);
Johnny Chend1c2dca2010-09-10 18:21:10 +00001112
Caroline Tice5136f942010-09-27 21:35:15 +00001113 if (GenerateBreakpointCommandCallbackData (data_ap->user_source, data_ap->script_source))
1114 {
1115 if (data_ap->script_source.GetSize() == 1)
1116 {
1117 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1118 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
1119 }
1120 }
1121
Johnny Chend1c2dca2010-09-10 18:21:10 +00001122 return;
1123}
1124
Chris Lattner24943d22010-06-08 16:52:24 +00001125bool
1126ScriptInterpreterPython::ExportFunctionDefinitionToInterpreter (StringList &function_def)
1127{
1128 // Convert StringList to one long, newline delimited, const char *.
1129 std::string function_def_string;
1130
1131 int num_lines = function_def.GetSize();
1132
1133 for (int i = 0; i < num_lines; ++i)
1134 {
1135 function_def_string.append (function_def.GetStringAtIndex(i));
1136 if (function_def_string.at (function_def_string.length() - 1) != '\n')
1137 function_def_string.append ("\n");
1138
1139 }
1140
1141 return ExecuteMultipleLines (function_def_string.c_str());
1142}
1143
Enrico Granataf7a9b142011-07-15 02:26:42 +00001144// TODO move both GenerateTypeScriptFunction and GenerateBreakpointCommandCallbackData to actually
1145// use this code to generate their functions
1146bool
1147ScriptInterpreterPython::GenerateFunction(std::string& signature, StringList &input, StringList &output)
1148{
1149 int num_lines = input.GetSize ();
1150 if (num_lines == 0)
1151 return false;
1152 StreamString sstr;
1153 StringList auto_generated_function;
1154 auto_generated_function.AppendString (signature.c_str());
1155 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1156 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1157 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1158 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1159 // global dictionary.
1160
1161 // Wrap everything up inside the function, increasing the indentation.
1162
1163 for (int i = 0; i < num_lines; ++i)
1164 {
1165 sstr.Clear ();
1166 sstr.Printf (" %s", input.GetStringAtIndex (i));
1167 auto_generated_function.AppendString (sstr.GetData());
1168 }
1169 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1170 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1171 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1172 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1173
1174 // Verify that the results are valid Python.
1175
1176 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1177 return false;
1178
1179 return true;
1180
1181}
1182
1183// this implementation is identical to GenerateBreakpointCommandCallbackData (apart from the name
1184// given to generated functions, of course)
1185bool
1186ScriptInterpreterPython::GenerateTypeScriptFunction (StringList &user_input, StringList &output)
1187{
1188 static int num_created_functions = 0;
1189 user_input.RemoveBlankLines ();
1190 int num_lines = user_input.GetSize ();
1191 StreamString sstr;
1192
1193 // Check to see if we have any data; if not, just return.
1194 if (user_input.GetSize() == 0)
1195 return false;
1196
1197 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1198 // ValueObject as parameter to the function.
1199
1200 sstr.Printf ("lldb_autogen_python_type_print_func_%d", num_created_functions);
1201 ++num_created_functions;
1202 std::string auto_generated_function_name = sstr.GetData();
1203
1204 sstr.Clear();
1205 StringList auto_generated_function;
1206
1207 // Create the function name & definition string.
1208
1209 sstr.Printf ("def %s (valobj, dict):", auto_generated_function_name.c_str());
1210 auto_generated_function.AppendString (sstr.GetData());
1211
1212 // Pre-pend code for setting up the session dictionary.
1213
1214 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1215 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1216 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1217 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1218 // global dictionary.
1219
1220 // Wrap everything up inside the function, increasing the indentation.
1221
1222 for (int i = 0; i < num_lines; ++i)
1223 {
1224 sstr.Clear ();
1225 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1226 auto_generated_function.AppendString (sstr.GetData());
1227 }
1228
1229 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1230 // got written to the values in the global dictionary, not the session dictionary).
1231
1232 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1233 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1234 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1235 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1236
1237 // Verify that the results are valid Python.
1238
1239 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1240 return false;
1241
1242 // Store the name of the auto-generated function to be called.
1243
1244 output.AppendString (auto_generated_function_name.c_str());
1245 return true;
1246}
1247
1248bool
1249ScriptInterpreterPython::GenerateTypeScriptFunction (const char* oneliner, StringList &output)
1250{
1251 StringList input(oneliner);
1252 return GenerateTypeScriptFunction(input, output);
1253}
1254
Chris Lattner24943d22010-06-08 16:52:24 +00001255bool
1256ScriptInterpreterPython::GenerateBreakpointCommandCallbackData (StringList &user_input, StringList &callback_data)
1257{
1258 static int num_created_functions = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001259 user_input.RemoveBlankLines ();
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001260 int num_lines = user_input.GetSize ();
1261 StreamString sstr;
Chris Lattner24943d22010-06-08 16:52:24 +00001262
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001263 // Check to see if we have any data; if not, just return.
1264 if (user_input.GetSize() == 0)
1265 return false;
1266
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001267 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1268 // frame and breakpoint location as parameters to the function.
Caroline Ticeb447e842010-09-21 19:25:28 +00001269
Caroline Ticeb447e842010-09-21 19:25:28 +00001270
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001271 sstr.Printf ("lldb_autogen_python_bp_callback_func_%d", num_created_functions);
1272 ++num_created_functions;
1273 std::string auto_generated_function_name = sstr.GetData();
Caroline Ticeb447e842010-09-21 19:25:28 +00001274
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001275 sstr.Clear();
Caroline Ticeb447e842010-09-21 19:25:28 +00001276 StringList auto_generated_function;
Caroline Ticeb447e842010-09-21 19:25:28 +00001277
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001278 // Create the function name & definition string.
1279
Caroline Tice0aa2e552011-01-14 00:29:16 +00001280 sstr.Printf ("def %s (frame, bp_loc, dict):", auto_generated_function_name.c_str());
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001281 auto_generated_function.AppendString (sstr.GetData());
Caroline Tice0aa2e552011-01-14 00:29:16 +00001282
1283 // Pre-pend code for setting up the session dictionary.
1284
1285 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1286 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1287 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1288 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1289 // global dictionary.
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001290
1291 // Wrap everything up inside the function, increasing the indentation.
Chris Lattner24943d22010-06-08 16:52:24 +00001292
1293 for (int i = 0; i < num_lines; ++i)
1294 {
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001295 sstr.Clear ();
1296 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1297 auto_generated_function.AppendString (sstr.GetData());
Caroline Ticeb447e842010-09-21 19:25:28 +00001298 }
Chris Lattner24943d22010-06-08 16:52:24 +00001299
Caroline Tice0aa2e552011-01-14 00:29:16 +00001300 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1301 // got written to the values in the global dictionary, not the session dictionary).
1302
1303 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1304 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1305 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1306 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1307
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001308 // Verify that the results are valid Python.
Chris Lattner24943d22010-06-08 16:52:24 +00001309
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001310 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
Caroline Ticeb447e842010-09-21 19:25:28 +00001311 {
Caroline Ticeb447e842010-09-21 19:25:28 +00001312 return false;
Chris Lattner24943d22010-06-08 16:52:24 +00001313 }
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001314
1315 // Store the name of the auto-generated function to be called.
1316
1317 callback_data.AppendString (auto_generated_function_name.c_str());
1318 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001319}
1320
Enrico Granataf7a9b142011-07-15 02:26:42 +00001321std::string
1322ScriptInterpreterPython::CallPythonScriptFunction (const char *python_function_name,
1323 lldb::ValueObjectSP valobj)
1324{
1325
1326 if (!python_function_name || !(*python_function_name))
1327 return "<no function>";
1328
1329 if (!valobj.get())
1330 return "<no object>";
1331
1332 Target *target = valobj->GetUpdatePoint().GetTarget();
1333
1334 if (!target)
1335 return "<no target>";
1336
1337 Debugger &debugger = target->GetDebugger();
1338 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1339 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1340
1341 if (!script_interpreter)
1342 return "<no python>";
1343
1344 std::string ret_val;
1345
1346 if (python_function_name
1347 && *python_function_name)
1348 {
1349 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
1350 if (CurrentThreadHasPythonLock())
1351 {
1352 python_interpreter->EnterSession ();
1353 ret_val = g_swig_typescript_callback (python_function_name,
1354 python_interpreter->m_dictionary_name.c_str(),
1355 valobj);
1356 python_interpreter->LeaveSession ();
1357 }
1358 else
1359 {
1360 while (!GetPythonLock (1))
1361 fprintf (tmp_fh,
1362 "Python interpreter locked on another thread; waiting to acquire lock...\n");
1363 python_interpreter->EnterSession ();
1364 ret_val = g_swig_typescript_callback (python_function_name,
1365 python_interpreter->m_dictionary_name.c_str(),
1366 valobj);
1367 python_interpreter->LeaveSession ();
1368 ReleasePythonLock ();
1369 }
1370 }
1371 else
1372 return "<no function name>";
1373
1374 return ret_val;
1375
1376}
1377
Greg Clayton5144f382010-10-07 17:14:24 +00001378bool
1379ScriptInterpreterPython::BreakpointCallbackFunction
1380(
1381 void *baton,
1382 StoppointCallbackContext *context,
1383 user_id_t break_id,
1384 user_id_t break_loc_id
1385)
1386{
1387 BreakpointOptions::CommandData *bp_option_data = (BreakpointOptions::CommandData *) baton;
1388 const char *python_function_name = bp_option_data->script_source.GetStringAtIndex (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001389
1390 if (!context)
1391 return true;
1392
1393 Target *target = context->exe_ctx.target;
1394
1395 if (!target)
1396 return true;
1397
1398 Debugger &debugger = target->GetDebugger();
1399 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1400 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1401
1402 if (!script_interpreter)
1403 return true;
Greg Clayton5144f382010-10-07 17:14:24 +00001404
1405 if (python_function_name != NULL
1406 && python_function_name[0] != '\0')
1407 {
1408 Thread *thread = context->exe_ctx.thread;
Greg Claytone86cbb92011-03-22 01:14:58 +00001409 const StackFrameSP stop_frame_sp (thread->GetStackFrameSPForStackFramePtr (context->exe_ctx.frame));
Greg Clayton5144f382010-10-07 17:14:24 +00001410 BreakpointSP breakpoint_sp = target->GetBreakpointByID (break_id);
Greg Claytone86cbb92011-03-22 01:14:58 +00001411 if (breakpoint_sp)
Caroline Tice0aa2e552011-01-14 00:29:16 +00001412 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001413 const BreakpointLocationSP bp_loc_sp (breakpoint_sp->FindLocationByID (break_loc_id));
1414
1415 if (stop_frame_sp && bp_loc_sp)
Caroline Tice202f6b82011-01-17 21:55:19 +00001416 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001417 bool ret_val = true;
1418 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
1419 if (CurrentThreadHasPythonLock())
1420 {
1421 python_interpreter->EnterSession ();
1422 ret_val = g_swig_breakpoint_callback (python_function_name,
1423 python_interpreter->m_dictionary_name.c_str(),
1424 stop_frame_sp,
1425 bp_loc_sp);
1426 python_interpreter->LeaveSession ();
1427 }
1428 else
1429 {
1430 while (!GetPythonLock (1))
1431 fprintf (tmp_fh,
1432 "Python interpreter locked on another thread; waiting to acquire lock...\n");
1433 python_interpreter->EnterSession ();
1434 ret_val = g_swig_breakpoint_callback (python_function_name,
1435 python_interpreter->m_dictionary_name.c_str(),
1436 stop_frame_sp,
1437 bp_loc_sp);
1438 python_interpreter->LeaveSession ();
1439 ReleasePythonLock ();
1440 }
1441 return ret_val;
Caroline Tice202f6b82011-01-17 21:55:19 +00001442 }
Caroline Tice0aa2e552011-01-14 00:29:16 +00001443 }
Greg Clayton5144f382010-10-07 17:14:24 +00001444 }
1445 // We currently always true so we stop in case anything goes wrong when
1446 // trying to call the script function
1447 return true;
1448}
Caroline Tice2ade6112010-11-10 19:18:14 +00001449
1450lldb::thread_result_t
1451ScriptInterpreterPython::RunEmbeddedPythonInterpreter (lldb::thread_arg_t baton)
1452{
1453 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
1454
1455 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
1456
1457 if (log)
1458 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread starting...", baton);
1459
1460 char error_str[1024];
1461 const char *pty_slave_name = script_interpreter->m_embedded_python_pty.GetSlaveName (error_str, sizeof (error_str));
Caroline Tice202f6b82011-01-17 21:55:19 +00001462 bool need_to_release_lock = true;
1463 bool safe_to_run = false;
Caroline Tice0aa2e552011-01-14 00:29:16 +00001464
Caroline Tice202f6b82011-01-17 21:55:19 +00001465 if (CurrentThreadHasPythonLock())
1466 {
1467 safe_to_run = true;
1468 need_to_release_lock = false;
1469 }
1470 else
1471 {
1472 int interval = 1;
1473 safe_to_run = GetPythonLock (interval);
1474 while (!safe_to_run)
1475 {
1476 interval = interval * 2;
1477 safe_to_run = GetPythonLock (interval);
1478 }
1479 }
1480
1481 if (pty_slave_name != NULL && safe_to_run)
1482 {
Caroline Tice2ade6112010-11-10 19:18:14 +00001483 StreamString run_string;
Caroline Tice2ade6112010-11-10 19:18:14 +00001484
Caroline Tice202f6b82011-01-17 21:55:19 +00001485 script_interpreter->EnterSession ();
1486
Caroline Tice0aa2e552011-01-14 00:29:16 +00001487 run_string.Printf ("run_one_line (%s, 'save_stderr = sys.stderr')", script_interpreter->m_dictionary_name.c_str());
1488 PyRun_SimpleString (run_string.GetData());
1489 run_string.Clear ();
1490
1491 run_string.Printf ("run_one_line (%s, 'sys.stderr = sys.stdout')", script_interpreter->m_dictionary_name.c_str());
1492 PyRun_SimpleString (run_string.GetData());
1493 run_string.Clear ();
1494
1495 run_string.Printf ("run_one_line (%s, 'save_stdin = sys.stdin')", script_interpreter->m_dictionary_name.c_str());
1496 PyRun_SimpleString (run_string.GetData());
1497 run_string.Clear ();
1498
1499 run_string.Printf ("run_one_line (%s, \"sys.stdin = open ('%s', 'r')\")", script_interpreter->m_dictionary_name.c_str(),
1500 pty_slave_name);
1501 PyRun_SimpleString (run_string.GetData());
1502 run_string.Clear ();
1503
Johnny Chen8054ba32011-03-11 00:28:50 +00001504 // The following call drops into the embedded interpreter loop and stays there until the
1505 // user chooses to exit from the Python interpreter.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001506
Caroline Ticece207c12011-03-11 00:21:55 +00001507 // When in the embedded interpreter, the user can call arbitrary system and Python stuff, which may require
Johnny Chen8054ba32011-03-11 00:28:50 +00001508 // 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 +00001509 // calls to Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS.
1510
1511 // We ALSO need to surround the call to the embedded interpreter with calls to PyGILState_Ensure and
1512 // PyGILState_Release. This is because this embedded interpreter is being run on a DIFFERENT THREAD than
1513 // the thread on which the call to Py_Initialize (and PyEval_InitThreads) was called. Those initializations
1514 // called PyGILState_Ensure on *that* thread, but it also needs to be called on *this* thread. Otherwise,
1515 // if the user calls Python code that does threading stuff, the interpreter state will be off, and things could
1516 // hang (it's happened before).
1517
Caroline Tice9d352ce2011-03-07 23:24:28 +00001518 Py_BEGIN_ALLOW_THREADS
1519 PyGILState_STATE gstate = PyGILState_Ensure();
1520
Caroline Tice0aa2e552011-01-14 00:29:16 +00001521 run_string.Printf ("run_python_interpreter (%s)", script_interpreter->m_dictionary_name.c_str());
1522 PyRun_SimpleString (run_string.GetData());
1523 run_string.Clear ();
Caroline Tice2ade6112010-11-10 19:18:14 +00001524
Caroline Tice9d352ce2011-03-07 23:24:28 +00001525 PyGILState_Release (gstate);
1526 Py_END_ALLOW_THREADS
1527
Caroline Tice0aa2e552011-01-14 00:29:16 +00001528 run_string.Printf ("run_one_line (%s, 'sys.stdin = save_stdin')", script_interpreter->m_dictionary_name.c_str());
1529 PyRun_SimpleString (run_string.GetData());
1530 run_string.Clear();
1531
1532 run_string.Printf ("run_one_line (%s, 'sys.stderr = save_stderr')", script_interpreter->m_dictionary_name.c_str());
1533 PyRun_SimpleString (run_string.GetData());
1534 run_string.Clear();
Caroline Tice202f6b82011-01-17 21:55:19 +00001535
1536 script_interpreter->LeaveSession ();
1537
Caroline Tice2ade6112010-11-10 19:18:14 +00001538 }
1539
Caroline Tice202f6b82011-01-17 21:55:19 +00001540 if (!safe_to_run)
1541 fprintf ((script_interpreter->m_dbg_stdout ? script_interpreter->m_dbg_stdout : stdout),
1542 "Python interpreter locked on another thread; unable to acquire lock.\n");
1543
1544 if (need_to_release_lock)
1545 ReleasePythonLock ();
1546
Caroline Tice2ade6112010-11-10 19:18:14 +00001547 if (script_interpreter->m_embedded_thread_input_reader_sp)
1548 script_interpreter->m_embedded_thread_input_reader_sp->SetIsDone (true);
1549
1550 script_interpreter->m_embedded_python_pty.CloseSlaveFileDescriptor();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001551
1552 script_interpreter->m_pty_slave_is_open = false;
Caroline Tice2ade6112010-11-10 19:18:14 +00001553
1554 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT);
1555 if (log)
1556 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread exiting...", baton);
1557
1558
Johnny Chen8054ba32011-03-11 00:28:50 +00001559 // Clean up the input reader and make the debugger pop it off the stack.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001560 Debugger &debugger = script_interpreter->GetCommandInterpreter().GetDebugger();
Caroline Tice2ade6112010-11-10 19:18:14 +00001561 const InputReaderSP reader_sp = script_interpreter->m_embedded_thread_input_reader_sp;
1562 script_interpreter->m_embedded_thread_input_reader_sp.reset();
1563 debugger.PopInputReader (reader_sp);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001564
Caroline Tice2ade6112010-11-10 19:18:14 +00001565 return NULL;
1566}
1567
1568
Caroline Tice0aa2e552011-01-14 00:29:16 +00001569void
Greg Claytone86cbb92011-03-22 01:14:58 +00001570ScriptInterpreterPython::InitializeInterpreter (SWIGInitCallback python_swig_init_callback,
Enrico Granataf7a9b142011-07-15 02:26:42 +00001571 SWIGBreakpointCallbackFunction python_swig_breakpoint_callback,
1572 SWIGPythonTypeScriptCallbackFunction python_swig_typescript_callback)
Greg Claytone86cbb92011-03-22 01:14:58 +00001573{
1574 g_swig_init_callback = python_swig_init_callback;
Enrico Granataf7a9b142011-07-15 02:26:42 +00001575 g_swig_breakpoint_callback = python_swig_breakpoint_callback;
1576 g_swig_typescript_callback = python_swig_typescript_callback;
Greg Claytone86cbb92011-03-22 01:14:58 +00001577}
1578
1579void
1580ScriptInterpreterPython::InitializePrivate ()
Caroline Tice0aa2e552011-01-14 00:29:16 +00001581{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001582 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
1583
Greg Clayton0fdd4a02011-02-07 23:24:47 +00001584 // Python will muck with STDIN terminal state, so save off any current TTY
1585 // settings so we can restore them.
1586 TerminalState stdin_tty_state;
1587 stdin_tty_state.Save(STDIN_FILENO, false);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001588
1589 // Find the module that owns this code and use that path we get to
1590 // set the PYTHONPATH appropriately.
1591
1592 FileSpec file_spec;
1593 char python_dir_path[PATH_MAX];
1594 if (Host::GetLLDBPath (ePathTypePythonDir, file_spec))
1595 {
1596 std::string python_path;
1597 const char *curr_python_path = ::getenv ("PYTHONPATH");
1598 if (curr_python_path)
1599 {
1600 // We have a current value for PYTHONPATH, so lets append to it
1601 python_path.append (curr_python_path);
1602 }
1603
1604 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
1605 {
1606 if (!python_path.empty())
1607 python_path.append (1, ':');
1608 python_path.append (python_dir_path);
1609 }
1610
1611 if (Host::GetLLDBPath (ePathTypeLLDBShlibDir, file_spec))
1612 {
1613 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
1614 {
1615 if (!python_path.empty())
1616 python_path.append (1, ':');
1617 python_path.append (python_dir_path);
1618 }
1619 }
1620 const char *pathon_path_env_cstr = python_path.c_str();
1621 ::setenv ("PYTHONPATH", pathon_path_env_cstr, 1);
1622 }
1623
Caroline Tice9d352ce2011-03-07 23:24:28 +00001624 PyEval_InitThreads ();
Caroline Ticea54461d2011-06-02 22:09:43 +00001625 Py_InitializeEx (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001626
Greg Claytone86cbb92011-03-22 01:14:58 +00001627 // Initialize SWIG after setting up python
1628 assert (g_swig_init_callback != NULL);
1629 g_swig_init_callback ();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001630
1631 // Update the path python uses to search for modules to include the current directory.
1632
Caroline Ticed4d92832011-06-13 21:33:00 +00001633 PyRun_SimpleString ("import sys");
1634 PyRun_SimpleString ("sys.path.append ('.')");
Caroline Tice0aa2e552011-01-14 00:29:16 +00001635
Caroline Ticed4d92832011-06-13 21:33:00 +00001636 PyRun_SimpleString ("import embedded_interpreter");
Caroline Tice0aa2e552011-01-14 00:29:16 +00001637
Caroline Ticed4d92832011-06-13 21:33:00 +00001638 PyRun_SimpleString ("from embedded_interpreter import run_python_interpreter");
1639 PyRun_SimpleString ("from embedded_interpreter import run_one_line");
1640 PyRun_SimpleString ("import sys");
1641 PyRun_SimpleString ("from termios import *");
Greg Clayton99208582011-02-07 19:04:58 +00001642
Greg Clayton0fdd4a02011-02-07 23:24:47 +00001643 stdin_tty_state.Restore();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001644}
1645
Greg Claytone86cbb92011-03-22 01:14:58 +00001646//void
1647//ScriptInterpreterPython::Terminate ()
1648//{
1649// // We are intentionally NOT calling Py_Finalize here (this would be the logical place to call it). Calling
1650// // Py_Finalize here causes test suite runs to seg fault: The test suite runs in Python. It registers
1651// // SBDebugger::Terminate to be called 'at_exit'. When the test suite Python harness finishes up, it calls
1652// // Py_Finalize, which calls all the 'at_exit' registered functions. SBDebugger::Terminate calls Debugger::Terminate,
1653// // which calls lldb::Terminate, which calls ScriptInterpreter::Terminate, which calls
1654// // ScriptInterpreterPython::Terminate. So if we call Py_Finalize here, we end up with Py_Finalize being called from
1655// // within Py_Finalize, which results in a seg fault.
1656// //
1657// // Since this function only gets called when lldb is shutting down and going away anyway, the fact that we don't
1658// // actually call Py_Finalize should not cause any problems (everything should shut down/go away anyway when the
1659// // process exits).
1660// //
1661//// Py_Finalize ();
1662//}