blob: 70fb3f8237c1079e4ad4e60f2c788df576213f75 [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
Benjamin Kramerc28bbdb2011-10-23 16:49:03 +000011// the *FIRST* header file included here.
12
13#if defined (__APPLE__)
14#include <Python/Python.h>
15#else
16#include <Python.h>
17#endif
Chris Lattner24943d22010-06-08 16:52:24 +000018
19#include "lldb/Interpreter/ScriptInterpreterPython.h"
20
Chris Lattner24943d22010-06-08 16:52:24 +000021#include <stdlib.h>
22#include <stdio.h>
23
24#include <string>
25
Enrico Granata91544802011-09-06 19:20:51 +000026#include "lldb/API/SBValue.h"
Greg Clayton987c7eb2011-09-17 08:33:22 +000027#include "lldb/Breakpoint/BreakpointLocation.h"
Greg Clayton63094e02010-06-23 01:19:29 +000028#include "lldb/Breakpoint/StoppointCallbackContext.h"
Chris Lattner24943d22010-06-08 16:52:24 +000029#include "lldb/Core/Debugger.h"
Chris Lattner24943d22010-06-08 16:52:24 +000030#include "lldb/Core/Timer.h"
31#include "lldb/Host/Host.h"
32#include "lldb/Interpreter/CommandInterpreter.h"
33#include "lldb/Interpreter/CommandReturnObject.h"
Greg Clayton5144f382010-10-07 17:14:24 +000034#include "lldb/Target/Thread.h"
Chris Lattner24943d22010-06-08 16:52:24 +000035
Chris Lattner24943d22010-06-08 16:52:24 +000036using namespace lldb;
37using namespace lldb_private;
38
Greg Claytone86cbb92011-03-22 01:14:58 +000039
40static ScriptInterpreter::SWIGInitCallback g_swig_init_callback = NULL;
41static ScriptInterpreter::SWIGBreakpointCallbackFunction g_swig_breakpoint_callback = NULL;
Enrico Granataf7a9b142011-07-15 02:26:42 +000042static ScriptInterpreter::SWIGPythonTypeScriptCallbackFunction g_swig_typescript_callback = NULL;
Enrico Granata9ae7cef2011-07-24 00:14:56 +000043static ScriptInterpreter::SWIGPythonCreateSyntheticProvider g_swig_synthetic_script = NULL;
44static ScriptInterpreter::SWIGPythonCalculateNumChildren g_swig_calc_children = NULL;
45static ScriptInterpreter::SWIGPythonGetChildAtIndex g_swig_get_child_index = NULL;
46static ScriptInterpreter::SWIGPythonGetIndexOfChildWithName g_swig_get_index_child = NULL;
47static ScriptInterpreter::SWIGPythonCastPyObjectToSBValue g_swig_cast_to_sbvalue = NULL;
Enrico Granata979e20d2011-07-29 19:53:35 +000048static ScriptInterpreter::SWIGPythonUpdateSynthProviderInstance g_swig_update_provider = NULL;
Enrico Granatac2a28252011-08-16 16:49:25 +000049static ScriptInterpreter::SWIGPythonCallCommand g_swig_call_command = NULL;
Enrico Granata59df36f2011-10-17 21:45:27 +000050static ScriptInterpreter::SWIGPythonCallModuleInit g_swig_call_module_init = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +000051
52static int
53_check_and_flush (FILE *stream)
54{
55 int prev_fail = ferror (stream);
56 return fflush (stream) || prev_fail ? EOF : 0;
57}
58
Caroline Tice202f6b82011-01-17 21:55:19 +000059static Predicate<lldb::tid_t> &
60PythonMutexPredicate ()
Caroline Tice0aa2e552011-01-14 00:29:16 +000061{
Caroline Tice202f6b82011-01-17 21:55:19 +000062 static lldb_private::Predicate<lldb::tid_t> g_interpreter_is_running (LLDB_INVALID_THREAD_ID);
63 return g_interpreter_is_running;
64}
65
66static bool
67CurrentThreadHasPythonLock ()
68{
69 TimeValue timeout;
70
71 timeout = TimeValue::Now(); // Don't wait any time.
72
73 return PythonMutexPredicate().WaitForValueEqualTo (Host::GetCurrentThreadID(), &timeout, NULL);
74}
75
76static bool
77GetPythonLock (uint32_t seconds_to_wait)
78{
79
80 TimeValue timeout;
81
82 if (seconds_to_wait != UINT32_MAX)
83 {
84 timeout = TimeValue::Now();
85 timeout.OffsetWithSeconds (seconds_to_wait);
86 }
87
88 return PythonMutexPredicate().WaitForValueEqualToAndSetValueTo (LLDB_INVALID_THREAD_ID,
89 Host::GetCurrentThreadID(), &timeout, NULL);
90}
91
92static void
93ReleasePythonLock ()
94{
95 PythonMutexPredicate().SetValue (LLDB_INVALID_THREAD_ID, eBroadcastAlways);
Caroline Tice0aa2e552011-01-14 00:29:16 +000096}
97
Enrico Granata91544802011-09-06 19:20:51 +000098ScriptInterpreterPython::Locker::Locker (ScriptInterpreterPython *pi,
99 FILE* tmp_fh,
100 bool ns) :
101 m_need_session(ns),
102 m_release_lock(false),
103 m_python_interpreter(pi),
104 m_tmp_fh(tmp_fh)
105{
106 // if Enter/LeaveSession() must be called, then m_python_interpreter must be != NULL
107 assert(m_need_session && m_python_interpreter);
108 if (!CurrentThreadHasPythonLock())
109 {
110 while (!GetPythonLock (1))
111 if (tmp_fh)
112 fprintf (tmp_fh,
113 "Python interpreter locked on another thread; waiting to acquire lock...\n");
114 m_release_lock = true;
115 }
116 if (m_need_session)
117 m_python_interpreter->EnterSession ();
118}
119
120ScriptInterpreterPython::Locker::~Locker()
121{
122 if (m_need_session)
123 m_python_interpreter->LeaveSession ();
124 if (m_release_lock)
125 ReleasePythonLock ();
126}
127
Greg Clayton63094e02010-06-23 01:19:29 +0000128ScriptInterpreterPython::ScriptInterpreterPython (CommandInterpreter &interpreter) :
Greg Clayton238c0a12010-09-18 01:14:36 +0000129 ScriptInterpreter (interpreter, eScriptLanguagePython),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000130 m_embedded_python_pty (),
131 m_embedded_thread_input_reader_sp (),
Greg Clayton58928562011-02-09 01:08:52 +0000132 m_dbg_stdout (interpreter.GetDebugger().GetOutputFile().GetStream()),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000133 m_new_sysout (NULL),
134 m_dictionary_name (interpreter.GetDebugger().GetInstanceName().AsCString()),
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000135 m_terminal_state (),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000136 m_session_is_active (false),
137 m_pty_slave_is_open (false),
138 m_valid_session (true)
Chris Lattner24943d22010-06-08 16:52:24 +0000139{
140
Greg Clayton7c330d62011-01-27 01:01:10 +0000141 static int g_initialized = false;
142
143 if (!g_initialized)
144 {
145 g_initialized = true;
Greg Claytone86cbb92011-03-22 01:14:58 +0000146 ScriptInterpreterPython::InitializePrivate ();
Greg Clayton7c330d62011-01-27 01:01:10 +0000147 }
148
Caroline Tice202f6b82011-01-17 21:55:19 +0000149 bool safe_to_run = false;
150 bool need_to_release_lock = true;
151 int interval = 5; // Number of seconds to try getting the Python lock before timing out.
152
153 // We don't dare exit this function without finishing setting up the script interpreter, so we must wait until
154 // we can get the Python lock.
155
156 if (CurrentThreadHasPythonLock())
157 {
158 safe_to_run = true;
159 need_to_release_lock = false;
160 }
161
162 while (!safe_to_run)
163 {
164 safe_to_run = GetPythonLock (interval);
165 if (!safe_to_run)
166 {
167 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
168 fprintf (tmp_fh,
169 "Python interpreter is locked on another thread; "
170 "please release interpreter in order to continue.\n");
171 interval = interval * 2;
172 }
173 }
174
Caroline Tice0aa2e552011-01-14 00:29:16 +0000175 m_dictionary_name.append("_dict");
176 StreamString run_string;
177 run_string.Printf ("%s = dict()", m_dictionary_name.c_str());
178 PyRun_SimpleString (run_string.GetData());
Caroline Tice5867f6b2010-10-18 18:24:17 +0000179
Caroline Tice0aa2e552011-01-14 00:29:16 +0000180 run_string.Clear();
181 run_string.Printf ("run_one_line (%s, 'import sys')", m_dictionary_name.c_str());
182 PyRun_SimpleString (run_string.GetData());
183
184 // Importing 'lldb' module calls SBDebugger::Initialize, which calls Debugger::Initialize, which increments a
185 // global debugger ref-count; therefore we need to check the ref-count before and after importing lldb, and if the
186 // ref-count increased we need to call Debugger::Terminate here to decrement the ref-count so that when the final
187 // call to Debugger::Terminate is made, the ref-count has the correct value.
188 //
189 // Bonus question: Why doesn't the ref-count always increase? Because sometimes lldb has already been imported, in
190 // which case the code inside it, including the call to SBDebugger::Initialize(), does not get executed.
Caroline Tice5867f6b2010-10-18 18:24:17 +0000191
Caroline Tice0aa2e552011-01-14 00:29:16 +0000192 int old_count = Debugger::TestDebuggerRefCount();
Chris Lattner24943d22010-06-08 16:52:24 +0000193
Caroline Tice0aa2e552011-01-14 00:29:16 +0000194 run_string.Clear();
195 run_string.Printf ("run_one_line (%s, 'import lldb')", m_dictionary_name.c_str());
196 PyRun_SimpleString (run_string.GetData());
Greg Clayton24b48ff2010-10-17 22:03:32 +0000197
Caroline Tice0aa2e552011-01-14 00:29:16 +0000198 int new_count = Debugger::TestDebuggerRefCount();
Chris Lattner24943d22010-06-08 16:52:24 +0000199
Caroline Tice0aa2e552011-01-14 00:29:16 +0000200 if (new_count > old_count)
201 Debugger::Terminate();
Caroline Tice5867f6b2010-10-18 18:24:17 +0000202
Caroline Tice0aa2e552011-01-14 00:29:16 +0000203 run_string.Clear();
204 run_string.Printf ("run_one_line (%s, 'import copy')", m_dictionary_name.c_str());
205 PyRun_SimpleString (run_string.GetData());
206
207 run_string.Clear();
Enrico Granata59df36f2011-10-17 21:45:27 +0000208 run_string.Printf ("run_one_line (%s, 'import os')", m_dictionary_name.c_str());
209 PyRun_SimpleString (run_string.GetData());
210
211 run_string.Clear();
Greg Clayton444e35b2011-10-19 18:09:39 +0000212 run_string.Printf ("run_one_line (%s, 'lldb.debugger_unique_id = %llu')", m_dictionary_name.c_str(),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000213 interpreter.GetDebugger().GetID());
214 PyRun_SimpleString (run_string.GetData());
215
Enrico Granata074e3b62011-08-17 19:07:52 +0000216 run_string.Clear();
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000217 run_string.Printf ("run_one_line (%s, 'import gnu_libstdcpp')", m_dictionary_name.c_str());
Enrico Granata074e3b62011-08-17 19:07:52 +0000218 PyRun_SimpleString (run_string.GetData());
219
Caroline Tice0aa2e552011-01-14 00:29:16 +0000220 if (m_dbg_stdout != NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000221 {
Caroline Tice0aa2e552011-01-14 00:29:16 +0000222 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
Caroline Tice5867f6b2010-10-18 18:24:17 +0000223 }
Caroline Tice202f6b82011-01-17 21:55:19 +0000224
225 if (need_to_release_lock)
226 ReleasePythonLock();
Chris Lattner24943d22010-06-08 16:52:24 +0000227}
228
229ScriptInterpreterPython::~ScriptInterpreterPython ()
230{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000231 Debugger &debugger = GetCommandInterpreter().GetDebugger();
232
233 if (m_embedded_thread_input_reader_sp.get() != NULL)
234 {
235 m_embedded_thread_input_reader_sp->SetIsDone (true);
236 m_embedded_python_pty.CloseSlaveFileDescriptor();
237 m_pty_slave_is_open = false;
238 const InputReaderSP reader_sp = m_embedded_thread_input_reader_sp;
239 m_embedded_thread_input_reader_sp.reset();
240 debugger.PopInputReader (reader_sp);
241 }
242
243 if (m_new_sysout)
244 {
Caroline Tice202f6b82011-01-17 21:55:19 +0000245 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
246 if (!CurrentThreadHasPythonLock ())
247 {
248 while (!GetPythonLock (1))
249 fprintf (tmp_fh, "Python interpreter locked on another thread; waiting to acquire lock...\n");
Benjamin Kramerc28bbdb2011-10-23 16:49:03 +0000250 Py_DECREF ((PyObject*)m_new_sysout);
Caroline Tice202f6b82011-01-17 21:55:19 +0000251 ReleasePythonLock ();
252 }
253 else
Benjamin Kramerc28bbdb2011-10-23 16:49:03 +0000254 Py_DECREF ((PyObject*)m_new_sysout);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000255 }
Chris Lattner24943d22010-06-08 16:52:24 +0000256}
257
Caroline Tice0aa2e552011-01-14 00:29:16 +0000258void
259ScriptInterpreterPython::ResetOutputFileHandle (FILE *fh)
260{
261 if (fh == NULL)
262 return;
263
264 m_dbg_stdout = fh;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000265
Caroline Tice202f6b82011-01-17 21:55:19 +0000266 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
Enrico Granata91544802011-09-06 19:20:51 +0000267
268 Locker py_lock(this, tmp_fh);
269
270 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000271}
272
273void
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000274ScriptInterpreterPython::SaveTerminalState (int fd)
275{
276 // Python mucks with the terminal state of STDIN. If we can possibly avoid
277 // this by setting the file handles up correctly prior to entering the
278 // interpreter we should. For now we save and restore the terminal state
279 // on the input file handle.
280 m_terminal_state.Save (fd, false);
281}
282
283void
284ScriptInterpreterPython::RestoreTerminalState ()
285{
286 // Python mucks with the terminal state of STDIN. If we can possibly avoid
287 // this by setting the file handles up correctly prior to entering the
288 // interpreter we should. For now we save and restore the terminal state
289 // on the input file handle.
290 m_terminal_state.Restore();
291}
292
293
294
295void
Caroline Tice0aa2e552011-01-14 00:29:16 +0000296ScriptInterpreterPython::LeaveSession ()
297{
298 m_session_is_active = false;
299}
300
301void
302ScriptInterpreterPython::EnterSession ()
303{
304 // If we have already entered the session, without having officially 'left' it, then there is no need to
305 // 'enter' it again.
306
307 if (m_session_is_active)
308 return;
309
310 m_session_is_active = true;
311
Caroline Tice202f6b82011-01-17 21:55:19 +0000312 StreamString run_string;
313
Greg Clayton444e35b2011-10-19 18:09:39 +0000314 run_string.Printf ("run_one_line (%s, 'lldb.debugger_unique_id = %llu')", m_dictionary_name.c_str(),
Caroline Tice202f6b82011-01-17 21:55:19 +0000315 GetCommandInterpreter().GetDebugger().GetID());
316 PyRun_SimpleString (run_string.GetData());
Caroline Tice6af65cb2011-05-03 21:21:50 +0000317 run_string.Clear();
Caroline Tice202f6b82011-01-17 21:55:19 +0000318
Caroline Tice0aa2e552011-01-14 00:29:16 +0000319
Greg Clayton444e35b2011-10-19 18:09:39 +0000320 run_string.Printf ("run_one_line (%s, 'lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%llu)')",
Caroline Tice6af65cb2011-05-03 21:21:50 +0000321 m_dictionary_name.c_str(),
322 GetCommandInterpreter().GetDebugger().GetID());
323 PyRun_SimpleString (run_string.GetData());
324 run_string.Clear();
325
326
Greg Clayton567e7f32011-09-22 04:58:26 +0000327 ExecutionContext exe_ctx (m_interpreter.GetDebugger().GetSelectedExecutionContext());
Caroline Tice6af65cb2011-05-03 21:21:50 +0000328
Greg Clayton567e7f32011-09-22 04:58:26 +0000329 if (exe_ctx.GetTargetPtr())
Caroline Tice6af65cb2011-05-03 21:21:50 +0000330 run_string.Printf ("run_one_line (%s, 'lldb.target = lldb.debugger.GetSelectedTarget()')",
331 m_dictionary_name.c_str());
332 else
333 run_string.Printf ("run_one_line (%s, 'lldb.target = None')", m_dictionary_name.c_str());
334 PyRun_SimpleString (run_string.GetData());
335 run_string.Clear();
336
Greg Clayton567e7f32011-09-22 04:58:26 +0000337 if (exe_ctx.GetProcessPtr())
Caroline Tice6af65cb2011-05-03 21:21:50 +0000338 run_string.Printf ("run_one_line (%s, 'lldb.process = lldb.target.GetProcess()')", m_dictionary_name.c_str());
339 else
340 run_string.Printf ("run_one_line (%s, 'lldb.process = None')", m_dictionary_name.c_str());
341 PyRun_SimpleString (run_string.GetData());
342 run_string.Clear();
343
Greg Clayton567e7f32011-09-22 04:58:26 +0000344 if (exe_ctx.GetThreadPtr())
Caroline Tice6af65cb2011-05-03 21:21:50 +0000345 run_string.Printf ("run_one_line (%s, 'lldb.thread = lldb.process.GetSelectedThread ()')",
346 m_dictionary_name.c_str());
347 else
348 run_string.Printf ("run_one_line (%s, 'lldb.thread = None')", m_dictionary_name.c_str());
349 PyRun_SimpleString (run_string.GetData());
350 run_string.Clear();
351
Greg Clayton567e7f32011-09-22 04:58:26 +0000352 if (exe_ctx.GetFramePtr())
Caroline Tice6af65cb2011-05-03 21:21:50 +0000353 run_string.Printf ("run_one_line (%s, 'lldb.frame = lldb.thread.GetSelectedFrame ()')",
354 m_dictionary_name.c_str());
355 else
356 run_string.Printf ("run_one_line (%s, 'lldb.frame = None')", m_dictionary_name.c_str());
357 PyRun_SimpleString (run_string.GetData());
358 run_string.Clear();
359
Caroline Tice0aa2e552011-01-14 00:29:16 +0000360 PyObject *sysmod = PyImport_AddModule ("sys");
361 PyObject *sysdict = PyModule_GetDict (sysmod);
362
363 if ((m_new_sysout != NULL)
364 && (sysmod != NULL)
365 && (sysdict != NULL))
Benjamin Kramerc28bbdb2011-10-23 16:49:03 +0000366 PyDict_SetItemString (sysdict, "stdout", (PyObject*)m_new_sysout);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000367
368 if (PyErr_Occurred())
369 PyErr_Clear ();
370
Caroline Tice0aa2e552011-01-14 00:29:16 +0000371 if (!m_pty_slave_is_open)
372 {
Caroline Tice202f6b82011-01-17 21:55:19 +0000373 run_string.Clear();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000374 run_string.Printf ("run_one_line (%s, \"new_stdin = open('%s', 'r')\")", m_dictionary_name.c_str(),
375 m_pty_slave_name.c_str());
376 PyRun_SimpleString (run_string.GetData());
377 m_pty_slave_is_open = true;
378
379 run_string.Clear();
380 run_string.Printf ("run_one_line (%s, 'sys.stdin = new_stdin')", m_dictionary_name.c_str());
381 PyRun_SimpleString (run_string.GetData());
382 }
383}
384
385
Johnny Chen60dde642010-07-30 22:33:14 +0000386bool
Greg Clayton238c0a12010-09-18 01:14:36 +0000387ScriptInterpreterPython::ExecuteOneLine (const char *command, CommandReturnObject *result)
Chris Lattner24943d22010-06-08 16:52:24 +0000388{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000389 if (!m_valid_session)
390 return false;
391
Caroline Tice0aa2e552011-01-14 00:29:16 +0000392
Caroline Tice0aa2e552011-01-14 00:29:16 +0000393
Caroline Tice4a461da2011-01-14 21:09:29 +0000394 // We want to call run_one_line, passing in the dictionary and the command string. We cannot do this through
395 // PyRun_SimpleString here because the command string may contain escaped characters, and putting it inside
396 // another string to pass to PyRun_SimpleString messes up the escaping. So we use the following more complicated
397 // method to pass the command string directly down to Python.
398
399
Caroline Tice202f6b82011-01-17 21:55:19 +0000400 bool need_to_release_lock = true;
401
402 if (CurrentThreadHasPythonLock())
403 need_to_release_lock = false;
404 else if (!GetPythonLock (1))
405 {
406 fprintf ((m_dbg_stdout ? m_dbg_stdout : stdout),
407 "Python interpreter is currently locked by another thread; unable to process command.\n");
408 return false;
409 }
410
411 EnterSession ();
Caroline Tice4a461da2011-01-14 21:09:29 +0000412 bool success = false;
413
Greg Clayton63094e02010-06-23 01:19:29 +0000414 if (command)
Chris Lattner24943d22010-06-08 16:52:24 +0000415 {
Caroline Tice4a461da2011-01-14 21:09:29 +0000416 // Find the correct script interpreter dictionary in the main module.
417 PyObject *main_mod = PyImport_AddModule ("__main__");
418 PyObject *script_interpreter_dict = NULL;
419 if (main_mod != NULL)
420 {
421 PyObject *main_dict = PyModule_GetDict (main_mod);
422 if ((main_dict != NULL)
423 && PyDict_Check (main_dict))
424 {
425 // Go through the main dictionary looking for the correct python script interpreter dictionary
426 PyObject *key, *value;
427 Py_ssize_t pos = 0;
428
429 while (PyDict_Next (main_dict, &pos, &key, &value))
430 {
431 // We have stolen references to the key and value objects in the dictionary; we need to increment
432 // them now so that Python's garbage collector doesn't collect them out from under us.
433 Py_INCREF (key);
434 Py_INCREF (value);
435 if (strcmp (PyString_AsString (key), m_dictionary_name.c_str()) == 0)
436 {
437 script_interpreter_dict = value;
438 break;
439 }
440 }
441 }
442
443 if (script_interpreter_dict != NULL)
444 {
445 PyObject *pfunc = NULL;
446 PyObject *pmod = PyImport_AddModule ("embedded_interpreter");
447 if (pmod != NULL)
448 {
449 PyObject *pmod_dict = PyModule_GetDict (pmod);
450 if ((pmod_dict != NULL)
451 && PyDict_Check (pmod_dict))
452 {
453 PyObject *key, *value;
454 Py_ssize_t pos = 0;
455
456 while (PyDict_Next (pmod_dict, &pos, &key, &value))
457 {
458 Py_INCREF (key);
459 Py_INCREF (value);
460 if (strcmp (PyString_AsString (key), "run_one_line") == 0)
461 {
462 pfunc = value;
463 break;
464 }
465 }
466
467 PyObject *string_arg = PyString_FromString (command);
468 if (pfunc && string_arg && PyCallable_Check (pfunc))
469 {
470 PyObject *pargs = PyTuple_New (2);
471 if (pargs != NULL)
472 {
473 PyTuple_SetItem (pargs, 0, script_interpreter_dict);
474 PyTuple_SetItem (pargs, 1, string_arg);
475 PyObject *pvalue = PyObject_CallObject (pfunc, pargs);
476 Py_DECREF (pargs);
477 if (pvalue != NULL)
478 {
479 Py_DECREF (pvalue);
480 success = true;
481 }
482 else if (PyErr_Occurred ())
483 {
484 PyErr_Print();
485 PyErr_Clear();
486 }
487 }
488 }
489 }
490 }
491 Py_INCREF (script_interpreter_dict);
492 }
493 }
Greg Clayton63094e02010-06-23 01:19:29 +0000494
Caroline Tice0aa2e552011-01-14 00:29:16 +0000495 LeaveSession ();
496
Caroline Tice202f6b82011-01-17 21:55:19 +0000497 if (need_to_release_lock)
498 ReleasePythonLock();
499
Caroline Tice4a461da2011-01-14 21:09:29 +0000500 if (success)
Johnny Chen60dde642010-07-30 22:33:14 +0000501 return true;
502
503 // The one-liner failed. Append the error message.
504 if (result)
505 result->AppendErrorWithFormat ("python failed attempting to evaluate '%s'\n", command);
506 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000507 }
Johnny Chen60dde642010-07-30 22:33:14 +0000508
Caroline Tice0aa2e552011-01-14 00:29:16 +0000509 LeaveSession ();
Caroline Tice202f6b82011-01-17 21:55:19 +0000510
511 if (need_to_release_lock)
512 ReleasePythonLock ();
513
Johnny Chen60dde642010-07-30 22:33:14 +0000514 if (result)
515 result->AppendError ("empty command passed to python\n");
516 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000517}
518
519
520
521size_t
522ScriptInterpreterPython::InputReaderCallback
523(
524 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000525 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000526 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000527 const char *bytes,
528 size_t bytes_len
529)
530{
Caroline Tice2ade6112010-11-10 19:18:14 +0000531 lldb::thread_t embedded_interpreter_thread;
532 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
533
Chris Lattner24943d22010-06-08 16:52:24 +0000534 if (baton == NULL)
535 return 0;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000536
537 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
538
539 if (script_interpreter->m_script_lang != eScriptLanguagePython)
540 return 0;
541
Caroline Tice892fadd2011-06-16 16:27:19 +0000542 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
543 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
544
Chris Lattner24943d22010-06-08 16:52:24 +0000545 switch (notification)
546 {
547 case eInputReaderActivate:
548 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000549 if (!batch_mode)
550 {
551 out_stream->Printf ("Python Interactive Interpreter. To exit, type 'quit()', 'exit()' or Ctrl-D.\n");
552 out_stream->Flush();
553 }
Greg Clayton58928562011-02-09 01:08:52 +0000554
Chris Lattner24943d22010-06-08 16:52:24 +0000555 // Save terminal settings if we can
Greg Clayton58928562011-02-09 01:08:52 +0000556 int input_fd = reader.GetDebugger().GetInputFile().GetDescriptor();
557 if (input_fd == File::kInvalidDescriptor)
Greg Clayton24b48ff2010-10-17 22:03:32 +0000558 input_fd = STDIN_FILENO;
Caroline Ticec95c6d12010-09-14 22:49:06 +0000559
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000560 script_interpreter->SaveTerminalState(input_fd);
Greg Clayton99208582011-02-07 19:04:58 +0000561
Caroline Tice202f6b82011-01-17 21:55:19 +0000562 if (!CurrentThreadHasPythonLock())
563 {
564 while (!GetPythonLock(1))
565 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000566 out_stream->Printf ("Python interpreter locked on another thread; waiting to acquire lock...\n");
567 out_stream->Flush();
Caroline Tice202f6b82011-01-17 21:55:19 +0000568 }
569 script_interpreter->EnterSession ();
570 ReleasePythonLock();
571 }
572 else
573 script_interpreter->EnterSession ();
574
Caroline Tice2ade6112010-11-10 19:18:14 +0000575 char error_str[1024];
576 if (script_interpreter->m_embedded_python_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, error_str,
577 sizeof(error_str)))
578 {
579 if (log)
580 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in opening master pty (fd = %d).",
581 script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor());
582 embedded_interpreter_thread = Host::ThreadCreate ("<lldb.script-interpreter.embedded-python-loop>",
583 ScriptInterpreterPython::RunEmbeddedPythonInterpreter,
584 script_interpreter, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +0000585 if (IS_VALID_LLDB_HOST_THREAD(embedded_interpreter_thread))
Caroline Tice2ade6112010-11-10 19:18:14 +0000586 {
587 if (log)
Jason Molendae09e2542011-09-20 23:23:44 +0000588 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in creating thread (thread_t = %p)", embedded_interpreter_thread);
Caroline Tice2ade6112010-11-10 19:18:14 +0000589 Error detach_error;
590 Host::ThreadDetach (embedded_interpreter_thread, &detach_error);
591 }
592 else
593 {
594 if (log)
595 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed in creating thread");
596 reader.SetIsDone (true);
597 }
598 }
599 else
600 {
601 if (log)
602 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed to open master pty ");
603 reader.SetIsDone (true);
604 }
Chris Lattner24943d22010-06-08 16:52:24 +0000605 }
606 break;
607
608 case eInputReaderDeactivate:
Caroline Tice0aa2e552011-01-14 00:29:16 +0000609 script_interpreter->LeaveSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000610 break;
611
612 case eInputReaderReactivate:
Caroline Tice202f6b82011-01-17 21:55:19 +0000613 if (!CurrentThreadHasPythonLock())
614 {
615 while (!GetPythonLock(1))
616 {
617 // Wait until lock is acquired.
618 }
619 script_interpreter->EnterSession ();
620 ReleasePythonLock();
621 }
622 else
623 script_interpreter->EnterSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000624 break;
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000625
Caroline Tice4a348082011-05-02 20:41:46 +0000626 case eInputReaderAsynchronousOutputWritten:
627 break;
628
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000629 case eInputReaderInterrupt:
630 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "raise KeyboardInterrupt\n", 24);
631 break;
632
633 case eInputReaderEndOfFile:
634 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()\n", 7);
635 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000636
637 case eInputReaderGotToken:
Caroline Tice2ade6112010-11-10 19:18:14 +0000638 if (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor() != -1)
Chris Lattner24943d22010-06-08 16:52:24 +0000639 {
Caroline Tice2ade6112010-11-10 19:18:14 +0000640 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000641 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %lu", bytes,
Caroline Tice2ade6112010-11-10 19:18:14 +0000642 bytes_len);
643 if (bytes && bytes_len)
644 {
645 if ((int) bytes[0] == 4)
646 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()", 6);
647 else
648 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), bytes, bytes_len);
649 }
650 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "\n", 1);
Chris Lattner24943d22010-06-08 16:52:24 +0000651 }
Caroline Tice2ade6112010-11-10 19:18:14 +0000652 else
653 {
654 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000655 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %lu, Master File Descriptor is bad.",
Caroline Tice2ade6112010-11-10 19:18:14 +0000656 bytes,
657 bytes_len);
658 reader.SetIsDone (true);
659 }
660
Chris Lattner24943d22010-06-08 16:52:24 +0000661 break;
662
663 case eInputReaderDone:
Caroline Tice0aa2e552011-01-14 00:29:16 +0000664 script_interpreter->LeaveSession ();
665
Chris Lattner24943d22010-06-08 16:52:24 +0000666 // Restore terminal settings if they were validly saved
Caroline Tice2ade6112010-11-10 19:18:14 +0000667 if (log)
668 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Done, closing down input reader.");
Caroline Ticec95c6d12010-09-14 22:49:06 +0000669
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000670 script_interpreter->RestoreTerminalState ();
671
Caroline Tice2ade6112010-11-10 19:18:14 +0000672 script_interpreter->m_embedded_python_pty.CloseMasterFileDescriptor();
Chris Lattner24943d22010-06-08 16:52:24 +0000673 break;
674 }
675
676 return bytes_len;
677}
678
679
680void
Greg Clayton238c0a12010-09-18 01:14:36 +0000681ScriptInterpreterPython::ExecuteInterpreterLoop ()
Chris Lattner24943d22010-06-08 16:52:24 +0000682{
683 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
684
Caroline Tice0aa2e552011-01-14 00:29:16 +0000685 Debugger &debugger = GetCommandInterpreter().GetDebugger();
Caroline Ticec95c6d12010-09-14 22:49:06 +0000686
687 // At the moment, the only time the debugger does not have an input file handle is when this is called
688 // directly from Python, in which case it is both dangerous and unnecessary (not to mention confusing) to
689 // try to embed a running interpreter loop inside the already running Python interpreter loop, so we won't
690 // do it.
691
Greg Clayton58928562011-02-09 01:08:52 +0000692 if (!debugger.GetInputFile().IsValid())
Caroline Ticec95c6d12010-09-14 22:49:06 +0000693 return;
694
Greg Clayton63094e02010-06-23 01:19:29 +0000695 InputReaderSP reader_sp (new InputReader(debugger));
Chris Lattner24943d22010-06-08 16:52:24 +0000696 if (reader_sp)
697 {
698 Error error (reader_sp->Initialize (ScriptInterpreterPython::InputReaderCallback,
699 this, // baton
700 eInputReaderGranularityLine, // token size, to pass to callback function
701 NULL, // end token
702 NULL, // prompt
703 true)); // echo input
704
705 if (error.Success())
706 {
Greg Clayton63094e02010-06-23 01:19:29 +0000707 debugger.PushInputReader (reader_sp);
Caroline Tice2ade6112010-11-10 19:18:14 +0000708 m_embedded_thread_input_reader_sp = reader_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000709 }
710 }
711}
712
713bool
714ScriptInterpreterPython::ExecuteOneLineWithReturn (const char *in_string,
Enrico Granata59df36f2011-10-17 21:45:27 +0000715 ScriptInterpreter::ScriptReturnType return_type,
Chris Lattner24943d22010-06-08 16:52:24 +0000716 void *ret_value)
717{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000718
Caroline Tice202f6b82011-01-17 21:55:19 +0000719 bool need_to_release_lock = true;
720
721 if (CurrentThreadHasPythonLock())
722 need_to_release_lock = false;
723 else if (!GetPythonLock (1))
724 {
725 fprintf ((m_dbg_stdout ? m_dbg_stdout : stdout),
726 "Python interpreter is currently locked by another thread; unable to process command.\n");
727 return false;
728 }
729
730 EnterSession ();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000731
Chris Lattner24943d22010-06-08 16:52:24 +0000732 PyObject *py_return = NULL;
733 PyObject *mainmod = PyImport_AddModule ("__main__");
734 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000735 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000736 PyObject *py_error = NULL;
Johnny Chen60a7df52011-08-11 19:17:45 +0000737 bool ret_success = false;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000738 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000739 int success;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000740
741 if (PyDict_Check (globals))
742 {
743 PyObject *key, *value;
744 Py_ssize_t pos = 0;
745
746 int i = 0;
747 while (PyDict_Next (globals, &pos, &key, &value))
748 {
749 // We have stolen references to the key and value objects in the dictionary; we need to increment them now
750 // so that Python's garbage collector doesn't collect them out from under us.
751 Py_INCREF (key);
752 Py_INCREF (value);
753 char *c_str = PyString_AsString (key);
754 if (strcmp (c_str, m_dictionary_name.c_str()) == 0)
755 locals = value;
756 ++i;
757 }
758 }
Chris Lattner24943d22010-06-08 16:52:24 +0000759
Caroline Tice0aa2e552011-01-14 00:29:16 +0000760 if (locals == NULL)
761 {
762 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
763 should_decrement_locals = true;
764 }
765
766 if (locals == NULL)
767 {
768 locals = globals;
769 should_decrement_locals = false;
770 }
771
772 py_error = PyErr_Occurred();
773 if (py_error != NULL)
774 PyErr_Clear();
775
Chris Lattner24943d22010-06-08 16:52:24 +0000776 if (in_string != NULL)
777 {
778 py_return = PyRun_String (in_string, Py_eval_input, globals, locals);
779 if (py_return == NULL)
780 {
781 py_error = PyErr_Occurred ();
782 if (py_error != NULL)
783 PyErr_Clear ();
784
785 py_return = PyRun_String (in_string, Py_single_input, globals, locals);
786 }
787
Caroline Tice0aa2e552011-01-14 00:29:16 +0000788 if (locals != NULL
789 && should_decrement_locals)
790 Py_DECREF (locals);
791
Chris Lattner24943d22010-06-08 16:52:24 +0000792 if (py_return != NULL)
793 {
794 switch (return_type)
795 {
Enrico Granata59df36f2011-10-17 21:45:27 +0000796 case eScriptReturnTypeCharPtr: // "char *"
Chris Lattner24943d22010-06-08 16:52:24 +0000797 {
798 const char format[3] = "s#";
Enrico Granatae5e34cb2011-08-17 01:30:04 +0000799 success = PyArg_Parse (py_return, format, (char **) ret_value);
Chris Lattner24943d22010-06-08 16:52:24 +0000800 break;
801 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000802 case eScriptReturnTypeCharStrOrNone: // char* or NULL if py_return == Py_None
Enrico Granatac2a28252011-08-16 16:49:25 +0000803 {
804 const char format[3] = "z";
Enrico Granatae5e34cb2011-08-17 01:30:04 +0000805 success = PyArg_Parse (py_return, format, (char **) ret_value);
Enrico Granatac2a28252011-08-16 16:49:25 +0000806 break;
807 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000808 case eScriptReturnTypeBool:
Chris Lattner24943d22010-06-08 16:52:24 +0000809 {
810 const char format[2] = "b";
811 success = PyArg_Parse (py_return, format, (bool *) ret_value);
812 break;
813 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000814 case eScriptReturnTypeShortInt:
Chris Lattner24943d22010-06-08 16:52:24 +0000815 {
816 const char format[2] = "h";
817 success = PyArg_Parse (py_return, format, (short *) ret_value);
818 break;
819 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000820 case eScriptReturnTypeShortIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000821 {
822 const char format[2] = "H";
823 success = PyArg_Parse (py_return, format, (unsigned short *) ret_value);
824 break;
825 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000826 case eScriptReturnTypeInt:
Chris Lattner24943d22010-06-08 16:52:24 +0000827 {
828 const char format[2] = "i";
829 success = PyArg_Parse (py_return, format, (int *) ret_value);
830 break;
831 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000832 case eScriptReturnTypeIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000833 {
834 const char format[2] = "I";
835 success = PyArg_Parse (py_return, format, (unsigned int *) ret_value);
836 break;
837 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000838 case eScriptReturnTypeLongInt:
Chris Lattner24943d22010-06-08 16:52:24 +0000839 {
840 const char format[2] = "l";
841 success = PyArg_Parse (py_return, format, (long *) ret_value);
842 break;
843 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000844 case eScriptReturnTypeLongIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000845 {
846 const char format[2] = "k";
847 success = PyArg_Parse (py_return, format, (unsigned long *) ret_value);
848 break;
849 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000850 case eScriptReturnTypeLongLong:
Chris Lattner24943d22010-06-08 16:52:24 +0000851 {
852 const char format[2] = "L";
853 success = PyArg_Parse (py_return, format, (long long *) ret_value);
854 break;
855 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000856 case eScriptReturnTypeLongLongUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000857 {
858 const char format[2] = "K";
859 success = PyArg_Parse (py_return, format, (unsigned long long *) ret_value);
860 break;
861 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000862 case eScriptReturnTypeFloat:
Chris Lattner24943d22010-06-08 16:52:24 +0000863 {
864 const char format[2] = "f";
865 success = PyArg_Parse (py_return, format, (float *) ret_value);
866 break;
867 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000868 case eScriptReturnTypeDouble:
Chris Lattner24943d22010-06-08 16:52:24 +0000869 {
870 const char format[2] = "d";
871 success = PyArg_Parse (py_return, format, (double *) ret_value);
872 break;
873 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000874 case eScriptReturnTypeChar:
Chris Lattner24943d22010-06-08 16:52:24 +0000875 {
876 const char format[2] = "c";
877 success = PyArg_Parse (py_return, format, (char *) ret_value);
878 break;
879 }
880 default:
881 {}
882 }
883 Py_DECREF (py_return);
884 if (success)
885 ret_success = true;
886 else
887 ret_success = false;
888 }
889 }
890
891 py_error = PyErr_Occurred();
892 if (py_error != NULL)
893 {
894 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
895 PyErr_Print ();
896 PyErr_Clear();
897 ret_success = false;
898 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000899
900 LeaveSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000901
Caroline Tice202f6b82011-01-17 21:55:19 +0000902 if (need_to_release_lock)
903 ReleasePythonLock();
904
Chris Lattner24943d22010-06-08 16:52:24 +0000905 return ret_success;
906}
907
908bool
909ScriptInterpreterPython::ExecuteMultipleLines (const char *in_string)
910{
Caroline Tice202f6b82011-01-17 21:55:19 +0000911 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
912 bool need_to_release_lock = true;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000913
Caroline Tice202f6b82011-01-17 21:55:19 +0000914 if (CurrentThreadHasPythonLock())
915 need_to_release_lock = false;
916 else
917 {
918 while (!GetPythonLock (1))
919 fprintf (tmp_fh, "Python interpreter locked on another thread; waiting to acquire lock...\n");
920 }
921
922 EnterSession ();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000923
Chris Lattner24943d22010-06-08 16:52:24 +0000924 bool success = false;
925 PyObject *py_return = NULL;
926 PyObject *mainmod = PyImport_AddModule ("__main__");
927 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000928 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000929 PyObject *py_error = NULL;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000930 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000931
Caroline Tice0aa2e552011-01-14 00:29:16 +0000932 if (PyDict_Check (globals))
933 {
934 PyObject *key, *value;
935 Py_ssize_t pos = 0;
936
937 while (PyDict_Next (globals, &pos, &key, &value))
938 {
939 // We have stolen references to the key and value objects in the dictionary; we need to increment them now
940 // so that Python's garbage collector doesn't collect them out from under us.
941 Py_INCREF (key);
942 Py_INCREF (value);
943 if (strcmp (PyString_AsString (key), m_dictionary_name.c_str()) == 0)
944 locals = value;
945 }
946 }
947
948 if (locals == NULL)
949 {
950 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
951 should_decrement_locals = true;
952 }
953
954 if (locals == NULL)
955 {
956 locals = globals;
957 should_decrement_locals = false;
958 }
959
960 py_error = PyErr_Occurred();
961 if (py_error != NULL)
962 PyErr_Clear();
963
Chris Lattner24943d22010-06-08 16:52:24 +0000964 if (in_string != NULL)
965 {
966 struct _node *compiled_node = PyParser_SimpleParseString (in_string, Py_file_input);
967 if (compiled_node)
968 {
969 PyCodeObject *compiled_code = PyNode_Compile (compiled_node, "temp.py");
970 if (compiled_code)
971 {
972 py_return = PyEval_EvalCode (compiled_code, globals, locals);
973 if (py_return != NULL)
974 {
975 success = true;
976 Py_DECREF (py_return);
977 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000978 if (locals && should_decrement_locals)
979 Py_DECREF (locals);
Chris Lattner24943d22010-06-08 16:52:24 +0000980 }
981 }
982 }
983
984 py_error = PyErr_Occurred ();
985 if (py_error != NULL)
986 {
987 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
988 PyErr_Print ();
989 PyErr_Clear();
990 success = false;
991 }
992
Caroline Tice0aa2e552011-01-14 00:29:16 +0000993 LeaveSession ();
994
Caroline Tice202f6b82011-01-17 21:55:19 +0000995 if (need_to_release_lock)
996 ReleasePythonLock();
997
Chris Lattner24943d22010-06-08 16:52:24 +0000998 return success;
999}
1000
1001static const char *g_reader_instructions = "Enter your Python command(s). Type 'DONE' to end.";
1002
1003size_t
1004ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback
1005(
1006 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +00001007 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +00001008 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +00001009 const char *bytes,
1010 size_t bytes_len
1011)
1012{
Caroline Tice892fadd2011-06-16 16:27:19 +00001013 static StringList commands_in_progress;
1014
1015 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
1016 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
1017
Chris Lattner24943d22010-06-08 16:52:24 +00001018 switch (notification)
1019 {
1020 case eInputReaderActivate:
1021 {
1022 commands_in_progress.Clear();
Caroline Tice892fadd2011-06-16 16:27:19 +00001023 if (!batch_mode)
Chris Lattner24943d22010-06-08 16:52:24 +00001024 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001025 out_stream->Printf ("%s\n", g_reader_instructions);
Greg Clayton63094e02010-06-23 01:19:29 +00001026 if (reader.GetPrompt())
Caroline Tice892fadd2011-06-16 16:27:19 +00001027 out_stream->Printf ("%s", reader.GetPrompt());
1028 out_stream->Flush ();
Chris Lattner24943d22010-06-08 16:52:24 +00001029 }
1030 }
1031 break;
1032
1033 case eInputReaderDeactivate:
1034 break;
1035
1036 case eInputReaderReactivate:
Caroline Tice892fadd2011-06-16 16:27:19 +00001037 if (reader.GetPrompt() && !batch_mode)
Caroline Ticef81b4c52010-10-27 18:34:42 +00001038 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001039 out_stream->Printf ("%s", reader.GetPrompt());
1040 out_stream->Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +00001041 }
Chris Lattner24943d22010-06-08 16:52:24 +00001042 break;
1043
Caroline Tice4a348082011-05-02 20:41:46 +00001044 case eInputReaderAsynchronousOutputWritten:
1045 break;
1046
Chris Lattner24943d22010-06-08 16:52:24 +00001047 case eInputReaderGotToken:
1048 {
1049 std::string temp_string (bytes, bytes_len);
1050 commands_in_progress.AppendString (temp_string.c_str());
Caroline Tice892fadd2011-06-16 16:27:19 +00001051 if (!reader.IsDone() && reader.GetPrompt() && !batch_mode)
Caroline Ticef81b4c52010-10-27 18:34:42 +00001052 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001053 out_stream->Printf ("%s", reader.GetPrompt());
1054 out_stream->Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +00001055 }
Chris Lattner24943d22010-06-08 16:52:24 +00001056 }
1057 break;
1058
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001059 case eInputReaderEndOfFile:
1060 case eInputReaderInterrupt:
1061 // Control-c (SIGINT) & control-d both mean finish & exit.
1062 reader.SetIsDone(true);
1063
1064 // Control-c (SIGINT) ALSO means cancel; do NOT create a breakpoint command.
1065 if (notification == eInputReaderInterrupt)
1066 commands_in_progress.Clear();
1067
1068 // Fall through here...
1069
Chris Lattner24943d22010-06-08 16:52:24 +00001070 case eInputReaderDone:
1071 {
1072 BreakpointOptions *bp_options = (BreakpointOptions *)baton;
1073 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1074 data_ap->user_source.AppendList (commands_in_progress);
1075 if (data_ap.get())
1076 {
Greg Clayton63094e02010-06-23 01:19:29 +00001077 ScriptInterpreter *interpreter = reader.GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
Chris Lattner24943d22010-06-08 16:52:24 +00001078 if (interpreter)
1079 {
1080 if (interpreter->GenerateBreakpointCommandCallbackData (data_ap->user_source,
1081 data_ap->script_source))
1082 {
1083 if (data_ap->script_source.GetSize() == 1)
1084 {
1085 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1086 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
1087 }
1088 }
Caroline Tice892fadd2011-06-16 16:27:19 +00001089 else if (!batch_mode)
1090 {
1091 out_stream->Printf ("Warning: No command attached to breakpoint.\n");
1092 out_stream->Flush();
1093 }
Chris Lattner24943d22010-06-08 16:52:24 +00001094 }
1095 else
1096 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001097 if (!batch_mode)
1098 {
1099 out_stream->Printf ("Warning: Unable to find script intepreter; no command attached to breakpoint.\n");
1100 out_stream->Flush();
1101 }
Chris Lattner24943d22010-06-08 16:52:24 +00001102 }
1103 }
1104 }
1105 break;
1106
1107 }
1108
1109 return bytes_len;
1110}
1111
1112void
Greg Clayton238c0a12010-09-18 01:14:36 +00001113ScriptInterpreterPython::CollectDataForBreakpointCommandCallback (BreakpointOptions *bp_options,
Chris Lattner24943d22010-06-08 16:52:24 +00001114 CommandReturnObject &result)
1115{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001116 Debugger &debugger = GetCommandInterpreter().GetDebugger();
1117
Greg Clayton63094e02010-06-23 01:19:29 +00001118 InputReaderSP reader_sp (new InputReader (debugger));
Chris Lattner24943d22010-06-08 16:52:24 +00001119
1120 if (reader_sp)
1121 {
1122 Error err = reader_sp->Initialize (
1123 ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback,
1124 bp_options, // baton
1125 eInputReaderGranularityLine, // token size, for feeding data to callback function
1126 "DONE", // end token
1127 "> ", // prompt
1128 true); // echo input
1129
1130 if (err.Success())
Greg Clayton63094e02010-06-23 01:19:29 +00001131 debugger.PushInputReader (reader_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001132 else
1133 {
1134 result.AppendError (err.AsCString());
1135 result.SetStatus (eReturnStatusFailed);
1136 }
1137 }
1138 else
1139 {
1140 result.AppendError("out of memory");
1141 result.SetStatus (eReturnStatusFailed);
1142 }
1143}
1144
Johnny Chen3e0571b2010-09-11 00:23:59 +00001145// Set a Python one-liner as the callback for the breakpoint.
Johnny Chend1c2dca2010-09-10 18:21:10 +00001146void
Greg Clayton238c0a12010-09-18 01:14:36 +00001147ScriptInterpreterPython::SetBreakpointCommandCallback (BreakpointOptions *bp_options,
Johnny Chend1c2dca2010-09-10 18:21:10 +00001148 const char *oneliner)
1149{
1150 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1151
1152 // It's necessary to set both user_source and script_source to the oneliner.
1153 // The former is used to generate callback description (as in breakpoint command list)
1154 // while the latter is used for Python to interpret during the actual callback.
Caroline Tice5136f942010-09-27 21:35:15 +00001155
Johnny Chend1c2dca2010-09-10 18:21:10 +00001156 data_ap->user_source.AppendString (oneliner);
Johnny Chend1c2dca2010-09-10 18:21:10 +00001157
Caroline Tice5136f942010-09-27 21:35:15 +00001158 if (GenerateBreakpointCommandCallbackData (data_ap->user_source, data_ap->script_source))
1159 {
1160 if (data_ap->script_source.GetSize() == 1)
1161 {
1162 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1163 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
1164 }
1165 }
1166
Johnny Chend1c2dca2010-09-10 18:21:10 +00001167 return;
1168}
1169
Chris Lattner24943d22010-06-08 16:52:24 +00001170bool
1171ScriptInterpreterPython::ExportFunctionDefinitionToInterpreter (StringList &function_def)
1172{
1173 // Convert StringList to one long, newline delimited, const char *.
1174 std::string function_def_string;
1175
1176 int num_lines = function_def.GetSize();
1177
1178 for (int i = 0; i < num_lines; ++i)
1179 {
1180 function_def_string.append (function_def.GetStringAtIndex(i));
1181 if (function_def_string.at (function_def_string.length() - 1) != '\n')
1182 function_def_string.append ("\n");
1183
1184 }
1185
1186 return ExecuteMultipleLines (function_def_string.c_str());
1187}
1188
Enrico Granataf7a9b142011-07-15 02:26:42 +00001189// TODO move both GenerateTypeScriptFunction and GenerateBreakpointCommandCallbackData to actually
1190// use this code to generate their functions
1191bool
1192ScriptInterpreterPython::GenerateFunction(std::string& signature, StringList &input, StringList &output)
1193{
1194 int num_lines = input.GetSize ();
1195 if (num_lines == 0)
1196 return false;
1197 StreamString sstr;
1198 StringList auto_generated_function;
1199 auto_generated_function.AppendString (signature.c_str());
1200 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1201 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1202 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1203 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1204 // global dictionary.
1205
1206 // Wrap everything up inside the function, increasing the indentation.
1207
1208 for (int i = 0; i < num_lines; ++i)
1209 {
1210 sstr.Clear ();
1211 sstr.Printf (" %s", input.GetStringAtIndex (i));
1212 auto_generated_function.AppendString (sstr.GetData());
1213 }
1214 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1215 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1216 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1217 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1218
1219 // Verify that the results are valid Python.
1220
1221 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1222 return false;
1223
1224 return true;
1225
1226}
1227
1228// this implementation is identical to GenerateBreakpointCommandCallbackData (apart from the name
1229// given to generated functions, of course)
1230bool
1231ScriptInterpreterPython::GenerateTypeScriptFunction (StringList &user_input, StringList &output)
1232{
1233 static int num_created_functions = 0;
1234 user_input.RemoveBlankLines ();
1235 int num_lines = user_input.GetSize ();
1236 StreamString sstr;
1237
1238 // Check to see if we have any data; if not, just return.
1239 if (user_input.GetSize() == 0)
1240 return false;
1241
1242 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1243 // ValueObject as parameter to the function.
1244
1245 sstr.Printf ("lldb_autogen_python_type_print_func_%d", num_created_functions);
1246 ++num_created_functions;
1247 std::string auto_generated_function_name = sstr.GetData();
1248
1249 sstr.Clear();
1250 StringList auto_generated_function;
1251
1252 // Create the function name & definition string.
1253
1254 sstr.Printf ("def %s (valobj, dict):", auto_generated_function_name.c_str());
1255 auto_generated_function.AppendString (sstr.GetData());
1256
1257 // Pre-pend code for setting up the session dictionary.
1258
1259 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1260 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1261 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1262 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1263 // global dictionary.
1264
1265 // Wrap everything up inside the function, increasing the indentation.
1266
1267 for (int i = 0; i < num_lines; ++i)
1268 {
1269 sstr.Clear ();
1270 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1271 auto_generated_function.AppendString (sstr.GetData());
1272 }
1273
1274 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1275 // got written to the values in the global dictionary, not the session dictionary).
1276
1277 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1278 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1279 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1280 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1281
1282 // Verify that the results are valid Python.
1283
1284 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1285 return false;
1286
1287 // Store the name of the auto-generated function to be called.
1288
1289 output.AppendString (auto_generated_function_name.c_str());
1290 return true;
1291}
1292
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001293bool
Enrico Granatac2a28252011-08-16 16:49:25 +00001294ScriptInterpreterPython::GenerateScriptAliasFunction (StringList &user_input, StringList &output)
1295{
1296 static int num_created_functions = 0;
1297 user_input.RemoveBlankLines ();
1298 int num_lines = user_input.GetSize ();
1299 StreamString sstr;
1300
1301 // Check to see if we have any data; if not, just return.
1302 if (user_input.GetSize() == 0)
1303 return false;
1304
1305 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1306 // ValueObject as parameter to the function.
1307
1308 sstr.Printf ("lldb_autogen_python_cmd_alias_func_%d", num_created_functions);
1309 ++num_created_functions;
1310 std::string auto_generated_function_name = sstr.GetData();
1311
1312 sstr.Clear();
1313 StringList auto_generated_function;
1314
1315 // Create the function name & definition string.
1316
Enrico Granata271568f2011-09-09 01:41:30 +00001317 sstr.Printf ("def %s (debugger, args, result, dict):", auto_generated_function_name.c_str());
Enrico Granatac2a28252011-08-16 16:49:25 +00001318 auto_generated_function.AppendString (sstr.GetData());
1319
1320 // Pre-pend code for setting up the session dictionary.
1321
1322 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1323 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1324 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1325 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1326 // global dictionary.
1327
1328 // Wrap everything up inside the function, increasing the indentation.
1329
1330 for (int i = 0; i < num_lines; ++i)
1331 {
1332 sstr.Clear ();
1333 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1334 auto_generated_function.AppendString (sstr.GetData());
1335 }
1336
1337 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1338 // got written to the values in the global dictionary, not the session dictionary).
1339
1340 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1341 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1342 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1343 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1344
1345 // Verify that the results are valid Python.
1346
1347 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1348 return false;
1349
1350 // Store the name of the auto-generated function to be called.
1351
1352 output.AppendString (auto_generated_function_name.c_str());
1353 return true;
1354}
1355
1356
1357bool
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001358ScriptInterpreterPython::GenerateTypeSynthClass (StringList &user_input, StringList &output)
1359{
1360 static int num_created_classes = 0;
1361 user_input.RemoveBlankLines ();
1362 int num_lines = user_input.GetSize ();
1363 StreamString sstr;
1364
1365 // Check to see if we have any data; if not, just return.
1366 if (user_input.GetSize() == 0)
1367 return false;
1368
1369 // Wrap all user input into a Python class
1370
1371 sstr.Printf ("lldb_autogen_python_type_synth_class_%d", num_created_classes);
1372 ++num_created_classes;
1373 std::string auto_generated_class_name = sstr.GetData();
1374
1375 sstr.Clear();
1376 StringList auto_generated_class;
1377
1378 // Create the function name & definition string.
1379
1380 sstr.Printf ("class %s:", auto_generated_class_name.c_str());
1381 auto_generated_class.AppendString (sstr.GetData());
1382
1383 // Wrap everything up inside the class, increasing the indentation.
1384
1385 for (int i = 0; i < num_lines; ++i)
1386 {
1387 sstr.Clear ();
1388 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1389 auto_generated_class.AppendString (sstr.GetData());
1390 }
1391
1392
1393 // Verify that the results are valid Python.
1394 // (even though the method is ExportFunctionDefinitionToInterpreter, a class will actually be exported)
1395 // (TODO: rename that method to ExportDefinitionToInterpreter)
1396 if (!ExportFunctionDefinitionToInterpreter (auto_generated_class))
1397 return false;
1398
1399 // Store the name of the auto-generated class
1400
1401 output.AppendString (auto_generated_class_name.c_str());
1402 return true;
1403}
1404
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001405void*
1406ScriptInterpreterPython::CreateSyntheticScriptedProvider (std::string class_name,
1407 lldb::ValueObjectSP valobj)
1408{
1409 if (class_name.empty())
1410 return NULL;
1411
1412 if (!valobj.get())
1413 return NULL;
1414
Enrico Granata979e20d2011-07-29 19:53:35 +00001415 Target *target = valobj->GetUpdatePoint().GetTargetSP().get();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001416
1417 if (!target)
1418 return NULL;
1419
1420 Debugger &debugger = target->GetDebugger();
1421 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1422 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1423
1424 if (!script_interpreter)
1425 return NULL;
1426
1427 void* ret_val;
1428
1429 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
Enrico Granata91544802011-09-06 19:20:51 +00001430
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001431 {
Enrico Granata91544802011-09-06 19:20:51 +00001432 Locker py_lock(this, tmp_fh);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001433 ret_val = g_swig_synthetic_script (class_name,
1434 python_interpreter->m_dictionary_name.c_str(),
1435 valobj);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001436 }
1437
1438 return ret_val;
1439}
1440
Enrico Granataf7a9b142011-07-15 02:26:42 +00001441bool
1442ScriptInterpreterPython::GenerateTypeScriptFunction (const char* oneliner, StringList &output)
1443{
1444 StringList input(oneliner);
1445 return GenerateTypeScriptFunction(input, output);
1446}
1447
Chris Lattner24943d22010-06-08 16:52:24 +00001448bool
1449ScriptInterpreterPython::GenerateBreakpointCommandCallbackData (StringList &user_input, StringList &callback_data)
1450{
1451 static int num_created_functions = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001452 user_input.RemoveBlankLines ();
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001453 int num_lines = user_input.GetSize ();
1454 StreamString sstr;
Chris Lattner24943d22010-06-08 16:52:24 +00001455
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001456 // Check to see if we have any data; if not, just return.
1457 if (user_input.GetSize() == 0)
1458 return false;
1459
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001460 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1461 // frame and breakpoint location as parameters to the function.
Caroline Ticeb447e842010-09-21 19:25:28 +00001462
Caroline Ticeb447e842010-09-21 19:25:28 +00001463
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001464 sstr.Printf ("lldb_autogen_python_bp_callback_func_%d", num_created_functions);
1465 ++num_created_functions;
1466 std::string auto_generated_function_name = sstr.GetData();
Caroline Ticeb447e842010-09-21 19:25:28 +00001467
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001468 sstr.Clear();
Caroline Ticeb447e842010-09-21 19:25:28 +00001469 StringList auto_generated_function;
Caroline Ticeb447e842010-09-21 19:25:28 +00001470
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001471 // Create the function name & definition string.
1472
Caroline Tice0aa2e552011-01-14 00:29:16 +00001473 sstr.Printf ("def %s (frame, bp_loc, dict):", auto_generated_function_name.c_str());
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001474 auto_generated_function.AppendString (sstr.GetData());
Caroline Tice0aa2e552011-01-14 00:29:16 +00001475
1476 // Pre-pend code for setting up the session dictionary.
1477
1478 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1479 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1480 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1481 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1482 // global dictionary.
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001483
1484 // Wrap everything up inside the function, increasing the indentation.
Chris Lattner24943d22010-06-08 16:52:24 +00001485
1486 for (int i = 0; i < num_lines; ++i)
1487 {
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001488 sstr.Clear ();
1489 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1490 auto_generated_function.AppendString (sstr.GetData());
Caroline Ticeb447e842010-09-21 19:25:28 +00001491 }
Chris Lattner24943d22010-06-08 16:52:24 +00001492
Caroline Tice0aa2e552011-01-14 00:29:16 +00001493 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1494 // got written to the values in the global dictionary, not the session dictionary).
1495
1496 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1497 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1498 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1499 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1500
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001501 // Verify that the results are valid Python.
Chris Lattner24943d22010-06-08 16:52:24 +00001502
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001503 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
Caroline Ticeb447e842010-09-21 19:25:28 +00001504 {
Caroline Ticeb447e842010-09-21 19:25:28 +00001505 return false;
Chris Lattner24943d22010-06-08 16:52:24 +00001506 }
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001507
1508 // Store the name of the auto-generated function to be called.
1509
1510 callback_data.AppendString (auto_generated_function_name.c_str());
1511 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001512}
1513
Enrico Granataf7a9b142011-07-15 02:26:42 +00001514std::string
1515ScriptInterpreterPython::CallPythonScriptFunction (const char *python_function_name,
1516 lldb::ValueObjectSP valobj)
1517{
1518
1519 if (!python_function_name || !(*python_function_name))
1520 return "<no function>";
1521
1522 if (!valobj.get())
1523 return "<no object>";
1524
Enrico Granata979e20d2011-07-29 19:53:35 +00001525 Target *target = valobj->GetUpdatePoint().GetTargetSP().get();
Enrico Granataf7a9b142011-07-15 02:26:42 +00001526
1527 if (!target)
1528 return "<no target>";
1529
1530 Debugger &debugger = target->GetDebugger();
1531 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1532 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1533
1534 if (!script_interpreter)
1535 return "<no python>";
1536
1537 std::string ret_val;
1538
1539 if (python_function_name
1540 && *python_function_name)
1541 {
1542 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
Enrico Granata91544802011-09-06 19:20:51 +00001543
Enrico Granataf7a9b142011-07-15 02:26:42 +00001544 {
Enrico Granata91544802011-09-06 19:20:51 +00001545 Locker py_lock(python_interpreter, tmp_fh);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001546 ret_val = g_swig_typescript_callback (python_function_name,
1547 python_interpreter->m_dictionary_name.c_str(),
1548 valobj);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001549 }
1550 }
1551 else
1552 return "<no function name>";
1553
1554 return ret_val;
1555
1556}
1557
Greg Clayton5144f382010-10-07 17:14:24 +00001558bool
1559ScriptInterpreterPython::BreakpointCallbackFunction
1560(
1561 void *baton,
1562 StoppointCallbackContext *context,
1563 user_id_t break_id,
1564 user_id_t break_loc_id
1565)
1566{
1567 BreakpointOptions::CommandData *bp_option_data = (BreakpointOptions::CommandData *) baton;
1568 const char *python_function_name = bp_option_data->script_source.GetStringAtIndex (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001569
1570 if (!context)
1571 return true;
1572
Greg Clayton567e7f32011-09-22 04:58:26 +00001573 Target *target = context->exe_ctx.GetTargetPtr();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001574
1575 if (!target)
1576 return true;
1577
1578 Debugger &debugger = target->GetDebugger();
1579 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1580 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1581
1582 if (!script_interpreter)
1583 return true;
Greg Clayton5144f382010-10-07 17:14:24 +00001584
1585 if (python_function_name != NULL
1586 && python_function_name[0] != '\0')
1587 {
Greg Clayton567e7f32011-09-22 04:58:26 +00001588 const StackFrameSP stop_frame_sp (context->exe_ctx.GetFrameSP());
Greg Clayton5144f382010-10-07 17:14:24 +00001589 BreakpointSP breakpoint_sp = target->GetBreakpointByID (break_id);
Greg Claytone86cbb92011-03-22 01:14:58 +00001590 if (breakpoint_sp)
Caroline Tice0aa2e552011-01-14 00:29:16 +00001591 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001592 const BreakpointLocationSP bp_loc_sp (breakpoint_sp->FindLocationByID (break_loc_id));
1593
1594 if (stop_frame_sp && bp_loc_sp)
Caroline Tice202f6b82011-01-17 21:55:19 +00001595 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001596 bool ret_val = true;
1597 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
Enrico Granata91544802011-09-06 19:20:51 +00001598
Greg Claytone86cbb92011-03-22 01:14:58 +00001599 {
Enrico Granata91544802011-09-06 19:20:51 +00001600 Locker py_lock(python_interpreter, tmp_fh);
Greg Claytone86cbb92011-03-22 01:14:58 +00001601 ret_val = g_swig_breakpoint_callback (python_function_name,
1602 python_interpreter->m_dictionary_name.c_str(),
1603 stop_frame_sp,
1604 bp_loc_sp);
Greg Claytone86cbb92011-03-22 01:14:58 +00001605 }
1606 return ret_val;
Caroline Tice202f6b82011-01-17 21:55:19 +00001607 }
Caroline Tice0aa2e552011-01-14 00:29:16 +00001608 }
Greg Clayton5144f382010-10-07 17:14:24 +00001609 }
1610 // We currently always true so we stop in case anything goes wrong when
1611 // trying to call the script function
1612 return true;
1613}
Caroline Tice2ade6112010-11-10 19:18:14 +00001614
1615lldb::thread_result_t
1616ScriptInterpreterPython::RunEmbeddedPythonInterpreter (lldb::thread_arg_t baton)
1617{
1618 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
1619
1620 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
1621
1622 if (log)
1623 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread starting...", baton);
1624
1625 char error_str[1024];
1626 const char *pty_slave_name = script_interpreter->m_embedded_python_pty.GetSlaveName (error_str, sizeof (error_str));
Caroline Tice202f6b82011-01-17 21:55:19 +00001627 bool need_to_release_lock = true;
1628 bool safe_to_run = false;
Caroline Tice0aa2e552011-01-14 00:29:16 +00001629
Caroline Tice202f6b82011-01-17 21:55:19 +00001630 if (CurrentThreadHasPythonLock())
1631 {
1632 safe_to_run = true;
1633 need_to_release_lock = false;
1634 }
1635 else
1636 {
1637 int interval = 1;
1638 safe_to_run = GetPythonLock (interval);
1639 while (!safe_to_run)
1640 {
1641 interval = interval * 2;
1642 safe_to_run = GetPythonLock (interval);
1643 }
1644 }
1645
1646 if (pty_slave_name != NULL && safe_to_run)
1647 {
Caroline Tice2ade6112010-11-10 19:18:14 +00001648 StreamString run_string;
Caroline Tice2ade6112010-11-10 19:18:14 +00001649
Caroline Tice202f6b82011-01-17 21:55:19 +00001650 script_interpreter->EnterSession ();
1651
Caroline Tice0aa2e552011-01-14 00:29:16 +00001652 run_string.Printf ("run_one_line (%s, 'save_stderr = sys.stderr')", script_interpreter->m_dictionary_name.c_str());
1653 PyRun_SimpleString (run_string.GetData());
1654 run_string.Clear ();
1655
1656 run_string.Printf ("run_one_line (%s, 'sys.stderr = sys.stdout')", script_interpreter->m_dictionary_name.c_str());
1657 PyRun_SimpleString (run_string.GetData());
1658 run_string.Clear ();
1659
1660 run_string.Printf ("run_one_line (%s, 'save_stdin = sys.stdin')", script_interpreter->m_dictionary_name.c_str());
1661 PyRun_SimpleString (run_string.GetData());
1662 run_string.Clear ();
1663
1664 run_string.Printf ("run_one_line (%s, \"sys.stdin = open ('%s', 'r')\")", script_interpreter->m_dictionary_name.c_str(),
1665 pty_slave_name);
1666 PyRun_SimpleString (run_string.GetData());
1667 run_string.Clear ();
1668
Johnny Chen8054ba32011-03-11 00:28:50 +00001669 // The following call drops into the embedded interpreter loop and stays there until the
1670 // user chooses to exit from the Python interpreter.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001671
Caroline Ticece207c12011-03-11 00:21:55 +00001672 // When in the embedded interpreter, the user can call arbitrary system and Python stuff, which may require
Johnny Chen8054ba32011-03-11 00:28:50 +00001673 // 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 +00001674 // calls to Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS.
1675
1676 // We ALSO need to surround the call to the embedded interpreter with calls to PyGILState_Ensure and
1677 // PyGILState_Release. This is because this embedded interpreter is being run on a DIFFERENT THREAD than
1678 // the thread on which the call to Py_Initialize (and PyEval_InitThreads) was called. Those initializations
1679 // called PyGILState_Ensure on *that* thread, but it also needs to be called on *this* thread. Otherwise,
1680 // if the user calls Python code that does threading stuff, the interpreter state will be off, and things could
1681 // hang (it's happened before).
1682
Caroline Tice9d352ce2011-03-07 23:24:28 +00001683 Py_BEGIN_ALLOW_THREADS
1684 PyGILState_STATE gstate = PyGILState_Ensure();
1685
Caroline Tice0aa2e552011-01-14 00:29:16 +00001686 run_string.Printf ("run_python_interpreter (%s)", script_interpreter->m_dictionary_name.c_str());
1687 PyRun_SimpleString (run_string.GetData());
1688 run_string.Clear ();
Caroline Tice2ade6112010-11-10 19:18:14 +00001689
Caroline Tice9d352ce2011-03-07 23:24:28 +00001690 PyGILState_Release (gstate);
1691 Py_END_ALLOW_THREADS
1692
Caroline Tice0aa2e552011-01-14 00:29:16 +00001693 run_string.Printf ("run_one_line (%s, 'sys.stdin = save_stdin')", script_interpreter->m_dictionary_name.c_str());
1694 PyRun_SimpleString (run_string.GetData());
1695 run_string.Clear();
1696
1697 run_string.Printf ("run_one_line (%s, 'sys.stderr = save_stderr')", script_interpreter->m_dictionary_name.c_str());
1698 PyRun_SimpleString (run_string.GetData());
1699 run_string.Clear();
Caroline Tice202f6b82011-01-17 21:55:19 +00001700
1701 script_interpreter->LeaveSession ();
1702
Caroline Tice2ade6112010-11-10 19:18:14 +00001703 }
1704
Caroline Tice202f6b82011-01-17 21:55:19 +00001705 if (!safe_to_run)
1706 fprintf ((script_interpreter->m_dbg_stdout ? script_interpreter->m_dbg_stdout : stdout),
1707 "Python interpreter locked on another thread; unable to acquire lock.\n");
1708
1709 if (need_to_release_lock)
1710 ReleasePythonLock ();
1711
Caroline Tice2ade6112010-11-10 19:18:14 +00001712 if (script_interpreter->m_embedded_thread_input_reader_sp)
1713 script_interpreter->m_embedded_thread_input_reader_sp->SetIsDone (true);
1714
1715 script_interpreter->m_embedded_python_pty.CloseSlaveFileDescriptor();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001716
1717 script_interpreter->m_pty_slave_is_open = false;
Caroline Tice2ade6112010-11-10 19:18:14 +00001718
1719 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT);
1720 if (log)
1721 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread exiting...", baton);
1722
1723
Johnny Chen8054ba32011-03-11 00:28:50 +00001724 // Clean up the input reader and make the debugger pop it off the stack.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001725 Debugger &debugger = script_interpreter->GetCommandInterpreter().GetDebugger();
Caroline Tice2ade6112010-11-10 19:18:14 +00001726 const InputReaderSP reader_sp = script_interpreter->m_embedded_thread_input_reader_sp;
1727 script_interpreter->m_embedded_thread_input_reader_sp.reset();
1728 debugger.PopInputReader (reader_sp);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001729
Caroline Tice2ade6112010-11-10 19:18:14 +00001730 return NULL;
1731}
1732
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001733uint32_t
1734ScriptInterpreterPython::CalculateNumChildren (void *implementor)
1735{
1736 if (!implementor)
1737 return 0;
1738
1739 if (!g_swig_calc_children)
1740 return 0;
1741
1742 ScriptInterpreterPython *python_interpreter = this;
1743
1744 uint32_t ret_val = 0;
1745
1746 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
Enrico Granata91544802011-09-06 19:20:51 +00001747
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001748 {
Enrico Granata91544802011-09-06 19:20:51 +00001749 Locker py_lock(python_interpreter, tmp_fh);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001750 ret_val = g_swig_calc_children (implementor);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001751 }
1752
1753 return ret_val;
1754}
1755
Enrico Granata91544802011-09-06 19:20:51 +00001756lldb::ValueObjectSP
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001757ScriptInterpreterPython::GetChildAtIndex (void *implementor, uint32_t idx)
1758{
1759 if (!implementor)
Enrico Granata91544802011-09-06 19:20:51 +00001760 return lldb::ValueObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001761
Enrico Granata91544802011-09-06 19:20:51 +00001762 if (!g_swig_get_child_index || !g_swig_cast_to_sbvalue)
1763 return lldb::ValueObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001764
1765 ScriptInterpreterPython *python_interpreter = this;
1766
Enrico Granata91544802011-09-06 19:20:51 +00001767 void* child_ptr = NULL;
1768 lldb::SBValue* value_sb = NULL;
1769 lldb::ValueObjectSP ret_val;
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001770
1771 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
Enrico Granata91544802011-09-06 19:20:51 +00001772
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001773 {
Enrico Granata91544802011-09-06 19:20:51 +00001774 Locker py_lock(python_interpreter, tmp_fh);
1775 child_ptr = g_swig_get_child_index (implementor,idx);
1776 if (child_ptr != NULL && child_ptr != Py_None)
1777 {
1778 value_sb = (lldb::SBValue*)g_swig_cast_to_sbvalue(child_ptr);
1779 if (value_sb == NULL)
1780 Py_XDECREF(child_ptr);
1781 else
1782 ret_val = value_sb->get_sp();
1783 }
1784 else
1785 {
1786 Py_XDECREF(child_ptr);
1787 }
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001788 }
1789
1790 return ret_val;
1791}
1792
1793int
1794ScriptInterpreterPython::GetIndexOfChildWithName (void *implementor, const char* child_name)
1795{
1796 if (!implementor)
1797 return UINT32_MAX;
1798
1799 if (!g_swig_get_index_child)
1800 return UINT32_MAX;
1801
1802 ScriptInterpreterPython *python_interpreter = this;
1803
1804 int ret_val = UINT32_MAX;
1805
1806 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
Enrico Granata91544802011-09-06 19:20:51 +00001807
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001808 {
Enrico Granata91544802011-09-06 19:20:51 +00001809 Locker py_lock(python_interpreter, tmp_fh);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001810 ret_val = g_swig_get_index_child (implementor, child_name);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001811 }
1812
1813 return ret_val;
1814}
1815
Enrico Granata979e20d2011-07-29 19:53:35 +00001816void
1817ScriptInterpreterPython::UpdateSynthProviderInstance (void* implementor)
1818{
1819 if (!implementor)
1820 return;
1821
1822 if (!g_swig_update_provider)
1823 return;
1824
1825 ScriptInterpreterPython *python_interpreter = this;
1826
1827 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
Enrico Granata91544802011-09-06 19:20:51 +00001828
Enrico Granata979e20d2011-07-29 19:53:35 +00001829 {
Enrico Granata91544802011-09-06 19:20:51 +00001830 Locker py_lock(python_interpreter, tmp_fh);
Enrico Granata979e20d2011-07-29 19:53:35 +00001831 g_swig_update_provider (implementor);
Enrico Granata979e20d2011-07-29 19:53:35 +00001832 }
1833
1834 return;
1835}
1836
Enrico Granatac2a28252011-08-16 16:49:25 +00001837bool
Enrico Granata59df36f2011-10-17 21:45:27 +00001838ScriptInterpreterPython::LoadScriptingModule (const char* pathname,
1839 lldb_private::Error& error)
1840{
1841 if (!pathname || !pathname[0])
1842 {
1843 error.SetErrorString("invalid pathname");
1844 return false;
1845 }
1846
1847 if (!g_swig_call_module_init)
1848 {
1849 error.SetErrorString("internal helper function missing");
1850 return false;
1851 }
1852
1853 ScriptInterpreterPython *python_interpreter = this;
1854
1855 lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().GetSP();
1856
1857 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
1858
1859 {
1860 Locker py_lock(python_interpreter, tmp_fh);
1861
1862 FileSpec target_file(pathname, true);
1863
1864 // TODO: would we want to reject any other value?
1865 if (target_file.GetFileType() == FileSpec::eFileTypeInvalid ||
1866 target_file.GetFileType() == FileSpec::eFileTypeUnknown)
1867 {
1868 error.SetErrorString("invalid pathname");
1869 return false;
1870 }
1871
1872 const char* directory = target_file.GetDirectory().GetCString();
1873 std::string basename(target_file.GetFilename().GetCString());
1874
1875 // now make sure that Python has "directory" in the search path
1876 StreamString command_stream;
1877 command_stream.Printf("if not (sys.path.__contains__('%s')):\n sys.path.append('%s');\n\n",
1878 directory,
1879 directory);
1880 bool syspath_retval = python_interpreter->ExecuteMultipleLines(command_stream.GetData());
1881 if (!syspath_retval)
1882 {
1883 error.SetErrorString("Python sys.path handling failed");
1884 return false;
1885 }
1886
1887 // strip .py or .pyc extension
1888 ConstString extension = target_file.GetFileNameExtension();
1889 if (::strcmp(extension.GetCString(), "py") == 0)
1890 basename.resize(basename.length()-3);
1891 else if(::strcmp(extension.GetCString(), "pyc") == 0)
1892 basename.resize(basename.length()-4);
1893
1894 // check if the module is already import-ed
1895 command_stream.Clear();
1896 command_stream.Printf("sys.getrefcount(%s)",basename.c_str());
1897 int refcount = 0;
1898 // this call will fail if the module does not exist (because the parameter to it is not a string
1899 // but an actual Python module object, which is non-existant if the module was not imported before)
1900 if (python_interpreter->ExecuteOneLineWithReturn(command_stream.GetData(),
1901 ScriptInterpreterPython::eScriptReturnTypeInt, &refcount) && refcount > 0)
1902 {
1903 error.SetErrorString("module already imported");
1904 return false;
1905 }
1906
1907 // now actually do the import
1908 command_stream.Clear();
1909 command_stream.Printf("import %s",basename.c_str());
1910 bool import_retval = python_interpreter->ExecuteOneLine(command_stream.GetData(), NULL);
1911 if (!import_retval)
1912 {
1913 error.SetErrorString("Python import statement failed");
1914 return false;
1915 }
1916
1917 // call __lldb_module_init(debugger,dict)
1918 if (!g_swig_call_module_init (basename,
1919 python_interpreter->m_dictionary_name.c_str(),
1920 debugger_sp))
1921 {
1922 error.SetErrorString("calling __lldb_module_init failed");
1923 return false;
1924 }
1925 return true;
1926 }
1927}
1928
1929bool
Enrico Granatac2a28252011-08-16 16:49:25 +00001930ScriptInterpreterPython::RunScriptBasedCommand(const char* impl_function,
1931 const char* args,
Enrico Granata6b1596d2011-08-16 23:24:13 +00001932 lldb_private::CommandReturnObject& cmd_retobj,
Enrico Granatac2a28252011-08-16 16:49:25 +00001933 Error& error)
1934{
1935 if (!impl_function)
1936 {
1937 error.SetErrorString("no function to execute");
1938 return false;
1939 }
1940
1941 if (!g_swig_call_command)
1942 {
1943 error.SetErrorString("no helper function to run scripted commands");
1944 return false;
1945 }
1946
1947 ScriptInterpreterPython *python_interpreter = this;
Enrico Granata3370f0c2011-08-19 23:56:34 +00001948
Enrico Granatac2a28252011-08-16 16:49:25 +00001949 lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().GetSP();
1950
1951 bool ret_val;
1952
1953 std::string err_msg;
1954
1955 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
Enrico Granata91544802011-09-06 19:20:51 +00001956
Enrico Granatac2a28252011-08-16 16:49:25 +00001957 {
Enrico Granata91544802011-09-06 19:20:51 +00001958 Locker py_lock(python_interpreter, tmp_fh);
Enrico Granatac2a28252011-08-16 16:49:25 +00001959 ret_val = g_swig_call_command (impl_function,
1960 python_interpreter->m_dictionary_name.c_str(),
1961 debugger_sp,
1962 args,
1963 err_msg,
Enrico Granata3370f0c2011-08-19 23:56:34 +00001964 cmd_retobj);
Enrico Granatac2a28252011-08-16 16:49:25 +00001965 }
1966
1967 if (!ret_val)
1968 error.SetErrorString(err_msg.c_str());
1969 else
1970 error.Clear();
Enrico Granata3370f0c2011-08-19 23:56:34 +00001971
Enrico Granatac2a28252011-08-16 16:49:25 +00001972 return ret_val;
1973
1974
1975 return true;
1976
1977}
1978
Enrico Granatae5e34cb2011-08-17 01:30:04 +00001979// in Python, a special attribute __doc__ contains the docstring
1980// for an object (function, method, class, ...) if any is defined
1981// Otherwise, the attribute's value is None
1982std::string
1983ScriptInterpreterPython::GetDocumentationForItem(const char* item)
1984{
1985 std::string command(item);
1986 command += ".__doc__";
1987
1988 char* result_ptr = NULL; // Python is going to point this to valid data if ExecuteOneLineWithReturn returns successfully
1989
1990 if (ExecuteOneLineWithReturn (command.c_str(),
Enrico Granata59df36f2011-10-17 21:45:27 +00001991 ScriptInterpreter::eScriptReturnTypeCharStrOrNone,
Enrico Granatae5e34cb2011-08-17 01:30:04 +00001992 &result_ptr) && result_ptr)
1993 {
1994 return std::string(result_ptr);
1995 }
1996 else
1997 return std::string("");
1998}
Caroline Tice2ade6112010-11-10 19:18:14 +00001999
Caroline Tice0aa2e552011-01-14 00:29:16 +00002000void
Greg Claytone86cbb92011-03-22 01:14:58 +00002001ScriptInterpreterPython::InitializeInterpreter (SWIGInitCallback python_swig_init_callback,
Enrico Granataf7a9b142011-07-15 02:26:42 +00002002 SWIGBreakpointCallbackFunction python_swig_breakpoint_callback,
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002003 SWIGPythonTypeScriptCallbackFunction python_swig_typescript_callback,
2004 SWIGPythonCreateSyntheticProvider python_swig_synthetic_script,
2005 SWIGPythonCalculateNumChildren python_swig_calc_children,
2006 SWIGPythonGetChildAtIndex python_swig_get_child_index,
2007 SWIGPythonGetIndexOfChildWithName python_swig_get_index_child,
Enrico Granata979e20d2011-07-29 19:53:35 +00002008 SWIGPythonCastPyObjectToSBValue python_swig_cast_to_sbvalue,
Enrico Granatac2a28252011-08-16 16:49:25 +00002009 SWIGPythonUpdateSynthProviderInstance python_swig_update_provider,
Enrico Granata59df36f2011-10-17 21:45:27 +00002010 SWIGPythonCallCommand python_swig_call_command,
2011 SWIGPythonCallModuleInit python_swig_call_mod_init)
Greg Claytone86cbb92011-03-22 01:14:58 +00002012{
2013 g_swig_init_callback = python_swig_init_callback;
Enrico Granataf7a9b142011-07-15 02:26:42 +00002014 g_swig_breakpoint_callback = python_swig_breakpoint_callback;
2015 g_swig_typescript_callback = python_swig_typescript_callback;
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002016 g_swig_synthetic_script = python_swig_synthetic_script;
2017 g_swig_calc_children = python_swig_calc_children;
2018 g_swig_get_child_index = python_swig_get_child_index;
2019 g_swig_get_index_child = python_swig_get_index_child;
2020 g_swig_cast_to_sbvalue = python_swig_cast_to_sbvalue;
Enrico Granata979e20d2011-07-29 19:53:35 +00002021 g_swig_update_provider = python_swig_update_provider;
Enrico Granatac2a28252011-08-16 16:49:25 +00002022 g_swig_call_command = python_swig_call_command;
Enrico Granata59df36f2011-10-17 21:45:27 +00002023 g_swig_call_module_init = python_swig_call_mod_init;
Greg Claytone86cbb92011-03-22 01:14:58 +00002024}
2025
2026void
2027ScriptInterpreterPython::InitializePrivate ()
Caroline Tice0aa2e552011-01-14 00:29:16 +00002028{
Caroline Tice0aa2e552011-01-14 00:29:16 +00002029 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
2030
Greg Clayton0fdd4a02011-02-07 23:24:47 +00002031 // Python will muck with STDIN terminal state, so save off any current TTY
2032 // settings so we can restore them.
2033 TerminalState stdin_tty_state;
2034 stdin_tty_state.Save(STDIN_FILENO, false);
Caroline Tice0aa2e552011-01-14 00:29:16 +00002035
Caroline Tice9d352ce2011-03-07 23:24:28 +00002036 PyEval_InitThreads ();
Caroline Ticea54461d2011-06-02 22:09:43 +00002037 Py_InitializeEx (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00002038
Greg Claytone86cbb92011-03-22 01:14:58 +00002039 // Initialize SWIG after setting up python
2040 assert (g_swig_init_callback != NULL);
2041 g_swig_init_callback ();
Caroline Tice0aa2e552011-01-14 00:29:16 +00002042
2043 // Update the path python uses to search for modules to include the current directory.
2044
Caroline Ticed4d92832011-06-13 21:33:00 +00002045 PyRun_SimpleString ("import sys");
2046 PyRun_SimpleString ("sys.path.append ('.')");
Jim Ingham2a19ef92011-08-27 01:24:08 +00002047
2048 // Find the module that owns this code and use that path we get to
2049 // set the sys.path appropriately.
2050
2051 FileSpec file_spec;
2052 char python_dir_path[PATH_MAX];
2053 if (Host::GetLLDBPath (ePathTypePythonDir, file_spec))
2054 {
2055 std::string python_path("sys.path.insert(0,\"");
2056 size_t orig_len = python_path.length();
2057 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
2058 {
2059 python_path.append (python_dir_path);
2060 python_path.append ("\")");
2061 PyRun_SimpleString (python_path.c_str());
2062 python_path.resize (orig_len);
2063 }
2064
2065 if (Host::GetLLDBPath (ePathTypeLLDBShlibDir, file_spec))
2066 {
2067 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
2068 {
2069 python_path.append (python_dir_path);
2070 python_path.append ("\")");
2071 PyRun_SimpleString (python_path.c_str());
2072 python_path.resize (orig_len);
2073 }
2074 }
2075 }
2076
Jim Ingham4dfa5112011-08-22 19:10:09 +00002077 PyRun_SimpleString ("sys.dont_write_bytecode = 1");
Caroline Tice0aa2e552011-01-14 00:29:16 +00002078
Caroline Ticed4d92832011-06-13 21:33:00 +00002079 PyRun_SimpleString ("import embedded_interpreter");
Caroline Tice0aa2e552011-01-14 00:29:16 +00002080
Caroline Ticed4d92832011-06-13 21:33:00 +00002081 PyRun_SimpleString ("from embedded_interpreter import run_python_interpreter");
2082 PyRun_SimpleString ("from embedded_interpreter import run_one_line");
Caroline Ticed4d92832011-06-13 21:33:00 +00002083 PyRun_SimpleString ("from termios import *");
Greg Clayton99208582011-02-07 19:04:58 +00002084
Greg Clayton0fdd4a02011-02-07 23:24:47 +00002085 stdin_tty_state.Restore();
Caroline Tice0aa2e552011-01-14 00:29:16 +00002086}
2087
Greg Claytone86cbb92011-03-22 01:14:58 +00002088//void
2089//ScriptInterpreterPython::Terminate ()
2090//{
2091// // We are intentionally NOT calling Py_Finalize here (this would be the logical place to call it). Calling
2092// // Py_Finalize here causes test suite runs to seg fault: The test suite runs in Python. It registers
2093// // SBDebugger::Terminate to be called 'at_exit'. When the test suite Python harness finishes up, it calls
2094// // Py_Finalize, which calls all the 'at_exit' registered functions. SBDebugger::Terminate calls Debugger::Terminate,
2095// // which calls lldb::Terminate, which calls ScriptInterpreter::Terminate, which calls
2096// // ScriptInterpreterPython::Terminate. So if we call Py_Finalize here, we end up with Py_Finalize being called from
2097// // within Py_Finalize, which results in a seg fault.
2098// //
2099// // Since this function only gets called when lldb is shutting down and going away anyway, the fact that we don't
2100// // actually call Py_Finalize should not cause any problems (everything should shut down/go away anyway when the
2101// // process exits).
2102// //
2103//// Py_Finalize ();
2104//}