blob: 6b71c82b4e8ea130c37b2845531c916b652a0e64 [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
Enrico Granata91544802011-09-06 19:20:51 +000021#include "lldb/API/SBValue.h"
Greg Clayton987c7eb2011-09-17 08:33:22 +000022#include "lldb/Breakpoint/BreakpointLocation.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;
Enrico Granata9ae7cef2011-07-24 00:14:56 +000038static ScriptInterpreter::SWIGPythonCreateSyntheticProvider g_swig_synthetic_script = NULL;
39static ScriptInterpreter::SWIGPythonCalculateNumChildren g_swig_calc_children = NULL;
40static ScriptInterpreter::SWIGPythonGetChildAtIndex g_swig_get_child_index = NULL;
41static ScriptInterpreter::SWIGPythonGetIndexOfChildWithName g_swig_get_index_child = NULL;
42static ScriptInterpreter::SWIGPythonCastPyObjectToSBValue g_swig_cast_to_sbvalue = NULL;
Enrico Granata979e20d2011-07-29 19:53:35 +000043static ScriptInterpreter::SWIGPythonUpdateSynthProviderInstance g_swig_update_provider = NULL;
Enrico Granatac2a28252011-08-16 16:49:25 +000044static ScriptInterpreter::SWIGPythonCallCommand g_swig_call_command = NULL;
Enrico Granata59df36f2011-10-17 21:45:27 +000045static ScriptInterpreter::SWIGPythonCallModuleInit g_swig_call_module_init = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +000046
47static int
48_check_and_flush (FILE *stream)
49{
50 int prev_fail = ferror (stream);
51 return fflush (stream) || prev_fail ? EOF : 0;
52}
53
Caroline Tice202f6b82011-01-17 21:55:19 +000054static Predicate<lldb::tid_t> &
55PythonMutexPredicate ()
Caroline Tice0aa2e552011-01-14 00:29:16 +000056{
Caroline Tice202f6b82011-01-17 21:55:19 +000057 static lldb_private::Predicate<lldb::tid_t> g_interpreter_is_running (LLDB_INVALID_THREAD_ID);
58 return g_interpreter_is_running;
59}
60
61static bool
62CurrentThreadHasPythonLock ()
63{
64 TimeValue timeout;
65
66 timeout = TimeValue::Now(); // Don't wait any time.
67
68 return PythonMutexPredicate().WaitForValueEqualTo (Host::GetCurrentThreadID(), &timeout, NULL);
69}
70
71static bool
72GetPythonLock (uint32_t seconds_to_wait)
73{
74
75 TimeValue timeout;
76
77 if (seconds_to_wait != UINT32_MAX)
78 {
79 timeout = TimeValue::Now();
80 timeout.OffsetWithSeconds (seconds_to_wait);
81 }
82
83 return PythonMutexPredicate().WaitForValueEqualToAndSetValueTo (LLDB_INVALID_THREAD_ID,
84 Host::GetCurrentThreadID(), &timeout, NULL);
85}
86
87static void
88ReleasePythonLock ()
89{
90 PythonMutexPredicate().SetValue (LLDB_INVALID_THREAD_ID, eBroadcastAlways);
Caroline Tice0aa2e552011-01-14 00:29:16 +000091}
92
Enrico Granata91544802011-09-06 19:20:51 +000093ScriptInterpreterPython::Locker::Locker (ScriptInterpreterPython *pi,
94 FILE* tmp_fh,
95 bool ns) :
96 m_need_session(ns),
97 m_release_lock(false),
98 m_python_interpreter(pi),
99 m_tmp_fh(tmp_fh)
100{
101 // if Enter/LeaveSession() must be called, then m_python_interpreter must be != NULL
102 assert(m_need_session && m_python_interpreter);
103 if (!CurrentThreadHasPythonLock())
104 {
105 while (!GetPythonLock (1))
106 if (tmp_fh)
107 fprintf (tmp_fh,
108 "Python interpreter locked on another thread; waiting to acquire lock...\n");
109 m_release_lock = true;
110 }
111 if (m_need_session)
112 m_python_interpreter->EnterSession ();
113}
114
115ScriptInterpreterPython::Locker::~Locker()
116{
117 if (m_need_session)
118 m_python_interpreter->LeaveSession ();
119 if (m_release_lock)
120 ReleasePythonLock ();
121}
122
Greg Clayton63094e02010-06-23 01:19:29 +0000123ScriptInterpreterPython::ScriptInterpreterPython (CommandInterpreter &interpreter) :
Greg Clayton238c0a12010-09-18 01:14:36 +0000124 ScriptInterpreter (interpreter, eScriptLanguagePython),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000125 m_embedded_python_pty (),
126 m_embedded_thread_input_reader_sp (),
Greg Clayton58928562011-02-09 01:08:52 +0000127 m_dbg_stdout (interpreter.GetDebugger().GetOutputFile().GetStream()),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000128 m_new_sysout (NULL),
129 m_dictionary_name (interpreter.GetDebugger().GetInstanceName().AsCString()),
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000130 m_terminal_state (),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000131 m_session_is_active (false),
132 m_pty_slave_is_open (false),
133 m_valid_session (true)
Chris Lattner24943d22010-06-08 16:52:24 +0000134{
135
Greg Clayton7c330d62011-01-27 01:01:10 +0000136 static int g_initialized = false;
137
138 if (!g_initialized)
139 {
140 g_initialized = true;
Greg Claytone86cbb92011-03-22 01:14:58 +0000141 ScriptInterpreterPython::InitializePrivate ();
Greg Clayton7c330d62011-01-27 01:01:10 +0000142 }
143
Caroline Tice202f6b82011-01-17 21:55:19 +0000144 bool safe_to_run = false;
145 bool need_to_release_lock = true;
146 int interval = 5; // Number of seconds to try getting the Python lock before timing out.
147
148 // We don't dare exit this function without finishing setting up the script interpreter, so we must wait until
149 // we can get the Python lock.
150
151 if (CurrentThreadHasPythonLock())
152 {
153 safe_to_run = true;
154 need_to_release_lock = false;
155 }
156
157 while (!safe_to_run)
158 {
159 safe_to_run = GetPythonLock (interval);
160 if (!safe_to_run)
161 {
162 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
163 fprintf (tmp_fh,
164 "Python interpreter is locked on another thread; "
165 "please release interpreter in order to continue.\n");
166 interval = interval * 2;
167 }
168 }
169
Caroline Tice0aa2e552011-01-14 00:29:16 +0000170 m_dictionary_name.append("_dict");
171 StreamString run_string;
172 run_string.Printf ("%s = dict()", m_dictionary_name.c_str());
173 PyRun_SimpleString (run_string.GetData());
Caroline Tice5867f6b2010-10-18 18:24:17 +0000174
Caroline Tice0aa2e552011-01-14 00:29:16 +0000175 run_string.Clear();
176 run_string.Printf ("run_one_line (%s, 'import sys')", m_dictionary_name.c_str());
177 PyRun_SimpleString (run_string.GetData());
178
179 // Importing 'lldb' module calls SBDebugger::Initialize, which calls Debugger::Initialize, which increments a
180 // global debugger ref-count; therefore we need to check the ref-count before and after importing lldb, and if the
181 // ref-count increased we need to call Debugger::Terminate here to decrement the ref-count so that when the final
182 // call to Debugger::Terminate is made, the ref-count has the correct value.
183 //
184 // Bonus question: Why doesn't the ref-count always increase? Because sometimes lldb has already been imported, in
185 // which case the code inside it, including the call to SBDebugger::Initialize(), does not get executed.
Caroline Tice5867f6b2010-10-18 18:24:17 +0000186
Caroline Tice0aa2e552011-01-14 00:29:16 +0000187 int old_count = Debugger::TestDebuggerRefCount();
Chris Lattner24943d22010-06-08 16:52:24 +0000188
Caroline Tice0aa2e552011-01-14 00:29:16 +0000189 run_string.Clear();
190 run_string.Printf ("run_one_line (%s, 'import lldb')", m_dictionary_name.c_str());
191 PyRun_SimpleString (run_string.GetData());
Greg Clayton24b48ff2010-10-17 22:03:32 +0000192
Caroline Tice0aa2e552011-01-14 00:29:16 +0000193 int new_count = Debugger::TestDebuggerRefCount();
Chris Lattner24943d22010-06-08 16:52:24 +0000194
Caroline Tice0aa2e552011-01-14 00:29:16 +0000195 if (new_count > old_count)
196 Debugger::Terminate();
Caroline Tice5867f6b2010-10-18 18:24:17 +0000197
Caroline Tice0aa2e552011-01-14 00:29:16 +0000198 run_string.Clear();
199 run_string.Printf ("run_one_line (%s, 'import copy')", m_dictionary_name.c_str());
200 PyRun_SimpleString (run_string.GetData());
201
202 run_string.Clear();
Enrico Granata59df36f2011-10-17 21:45:27 +0000203 run_string.Printf ("run_one_line (%s, 'import os')", m_dictionary_name.c_str());
204 PyRun_SimpleString (run_string.GetData());
205
206 run_string.Clear();
Greg Clayton444e35b2011-10-19 18:09:39 +0000207 run_string.Printf ("run_one_line (%s, 'lldb.debugger_unique_id = %llu')", m_dictionary_name.c_str(),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000208 interpreter.GetDebugger().GetID());
209 PyRun_SimpleString (run_string.GetData());
210
Enrico Granata074e3b62011-08-17 19:07:52 +0000211 run_string.Clear();
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000212 run_string.Printf ("run_one_line (%s, 'import gnu_libstdcpp')", m_dictionary_name.c_str());
Enrico Granata074e3b62011-08-17 19:07:52 +0000213 PyRun_SimpleString (run_string.GetData());
214
Caroline Tice0aa2e552011-01-14 00:29:16 +0000215 if (m_dbg_stdout != NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000216 {
Caroline Tice0aa2e552011-01-14 00:29:16 +0000217 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
Caroline Tice5867f6b2010-10-18 18:24:17 +0000218 }
Caroline Tice202f6b82011-01-17 21:55:19 +0000219
220 if (need_to_release_lock)
221 ReleasePythonLock();
Chris Lattner24943d22010-06-08 16:52:24 +0000222}
223
224ScriptInterpreterPython::~ScriptInterpreterPython ()
225{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000226 Debugger &debugger = GetCommandInterpreter().GetDebugger();
227
228 if (m_embedded_thread_input_reader_sp.get() != NULL)
229 {
230 m_embedded_thread_input_reader_sp->SetIsDone (true);
231 m_embedded_python_pty.CloseSlaveFileDescriptor();
232 m_pty_slave_is_open = false;
233 const InputReaderSP reader_sp = m_embedded_thread_input_reader_sp;
234 m_embedded_thread_input_reader_sp.reset();
235 debugger.PopInputReader (reader_sp);
236 }
237
238 if (m_new_sysout)
239 {
Caroline Tice202f6b82011-01-17 21:55:19 +0000240 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
241 if (!CurrentThreadHasPythonLock ())
242 {
243 while (!GetPythonLock (1))
244 fprintf (tmp_fh, "Python interpreter locked on another thread; waiting to acquire lock...\n");
245 Py_DECREF (m_new_sysout);
246 ReleasePythonLock ();
247 }
248 else
249 Py_DECREF (m_new_sysout);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000250 }
Chris Lattner24943d22010-06-08 16:52:24 +0000251}
252
Caroline Tice0aa2e552011-01-14 00:29:16 +0000253void
254ScriptInterpreterPython::ResetOutputFileHandle (FILE *fh)
255{
256 if (fh == NULL)
257 return;
258
259 m_dbg_stdout = fh;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000260
Caroline Tice202f6b82011-01-17 21:55:19 +0000261 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
Enrico Granata91544802011-09-06 19:20:51 +0000262
263 Locker py_lock(this, tmp_fh);
264
265 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000266}
267
268void
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000269ScriptInterpreterPython::SaveTerminalState (int fd)
270{
271 // Python mucks with the terminal state of STDIN. If we can possibly avoid
272 // this by setting the file handles up correctly prior to entering the
273 // interpreter we should. For now we save and restore the terminal state
274 // on the input file handle.
275 m_terminal_state.Save (fd, false);
276}
277
278void
279ScriptInterpreterPython::RestoreTerminalState ()
280{
281 // Python mucks with the terminal state of STDIN. If we can possibly avoid
282 // this by setting the file handles up correctly prior to entering the
283 // interpreter we should. For now we save and restore the terminal state
284 // on the input file handle.
285 m_terminal_state.Restore();
286}
287
288
289
290void
Caroline Tice0aa2e552011-01-14 00:29:16 +0000291ScriptInterpreterPython::LeaveSession ()
292{
293 m_session_is_active = false;
294}
295
296void
297ScriptInterpreterPython::EnterSession ()
298{
299 // If we have already entered the session, without having officially 'left' it, then there is no need to
300 // 'enter' it again.
301
302 if (m_session_is_active)
303 return;
304
305 m_session_is_active = true;
306
Caroline Tice202f6b82011-01-17 21:55:19 +0000307 StreamString run_string;
308
Greg Clayton444e35b2011-10-19 18:09:39 +0000309 run_string.Printf ("run_one_line (%s, 'lldb.debugger_unique_id = %llu')", m_dictionary_name.c_str(),
Caroline Tice202f6b82011-01-17 21:55:19 +0000310 GetCommandInterpreter().GetDebugger().GetID());
311 PyRun_SimpleString (run_string.GetData());
Caroline Tice6af65cb2011-05-03 21:21:50 +0000312 run_string.Clear();
Caroline Tice202f6b82011-01-17 21:55:19 +0000313
Caroline Tice0aa2e552011-01-14 00:29:16 +0000314
Greg Clayton444e35b2011-10-19 18:09:39 +0000315 run_string.Printf ("run_one_line (%s, 'lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%llu)')",
Caroline Tice6af65cb2011-05-03 21:21:50 +0000316 m_dictionary_name.c_str(),
317 GetCommandInterpreter().GetDebugger().GetID());
318 PyRun_SimpleString (run_string.GetData());
319 run_string.Clear();
320
321
Greg Clayton567e7f32011-09-22 04:58:26 +0000322 ExecutionContext exe_ctx (m_interpreter.GetDebugger().GetSelectedExecutionContext());
Caroline Tice6af65cb2011-05-03 21:21:50 +0000323
Greg Clayton567e7f32011-09-22 04:58:26 +0000324 if (exe_ctx.GetTargetPtr())
Caroline Tice6af65cb2011-05-03 21:21:50 +0000325 run_string.Printf ("run_one_line (%s, 'lldb.target = lldb.debugger.GetSelectedTarget()')",
326 m_dictionary_name.c_str());
327 else
328 run_string.Printf ("run_one_line (%s, 'lldb.target = None')", m_dictionary_name.c_str());
329 PyRun_SimpleString (run_string.GetData());
330 run_string.Clear();
331
Greg Clayton567e7f32011-09-22 04:58:26 +0000332 if (exe_ctx.GetProcessPtr())
Caroline Tice6af65cb2011-05-03 21:21:50 +0000333 run_string.Printf ("run_one_line (%s, 'lldb.process = lldb.target.GetProcess()')", m_dictionary_name.c_str());
334 else
335 run_string.Printf ("run_one_line (%s, 'lldb.process = None')", m_dictionary_name.c_str());
336 PyRun_SimpleString (run_string.GetData());
337 run_string.Clear();
338
Greg Clayton567e7f32011-09-22 04:58:26 +0000339 if (exe_ctx.GetThreadPtr())
Caroline Tice6af65cb2011-05-03 21:21:50 +0000340 run_string.Printf ("run_one_line (%s, 'lldb.thread = lldb.process.GetSelectedThread ()')",
341 m_dictionary_name.c_str());
342 else
343 run_string.Printf ("run_one_line (%s, 'lldb.thread = None')", m_dictionary_name.c_str());
344 PyRun_SimpleString (run_string.GetData());
345 run_string.Clear();
346
Greg Clayton567e7f32011-09-22 04:58:26 +0000347 if (exe_ctx.GetFramePtr())
Caroline Tice6af65cb2011-05-03 21:21:50 +0000348 run_string.Printf ("run_one_line (%s, 'lldb.frame = lldb.thread.GetSelectedFrame ()')",
349 m_dictionary_name.c_str());
350 else
351 run_string.Printf ("run_one_line (%s, 'lldb.frame = None')", m_dictionary_name.c_str());
352 PyRun_SimpleString (run_string.GetData());
353 run_string.Clear();
354
Caroline Tice0aa2e552011-01-14 00:29:16 +0000355 PyObject *sysmod = PyImport_AddModule ("sys");
356 PyObject *sysdict = PyModule_GetDict (sysmod);
357
358 if ((m_new_sysout != NULL)
359 && (sysmod != NULL)
360 && (sysdict != NULL))
361 PyDict_SetItemString (sysdict, "stdout", m_new_sysout);
362
363 if (PyErr_Occurred())
364 PyErr_Clear ();
365
Caroline Tice0aa2e552011-01-14 00:29:16 +0000366 if (!m_pty_slave_is_open)
367 {
Caroline Tice202f6b82011-01-17 21:55:19 +0000368 run_string.Clear();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000369 run_string.Printf ("run_one_line (%s, \"new_stdin = open('%s', 'r')\")", m_dictionary_name.c_str(),
370 m_pty_slave_name.c_str());
371 PyRun_SimpleString (run_string.GetData());
372 m_pty_slave_is_open = true;
373
374 run_string.Clear();
375 run_string.Printf ("run_one_line (%s, 'sys.stdin = new_stdin')", m_dictionary_name.c_str());
376 PyRun_SimpleString (run_string.GetData());
377 }
378}
379
380
Johnny Chen60dde642010-07-30 22:33:14 +0000381bool
Greg Clayton238c0a12010-09-18 01:14:36 +0000382ScriptInterpreterPython::ExecuteOneLine (const char *command, CommandReturnObject *result)
Chris Lattner24943d22010-06-08 16:52:24 +0000383{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000384 if (!m_valid_session)
385 return false;
386
Caroline Tice0aa2e552011-01-14 00:29:16 +0000387
Caroline Tice0aa2e552011-01-14 00:29:16 +0000388
Caroline Tice4a461da2011-01-14 21:09:29 +0000389 // We want to call run_one_line, passing in the dictionary and the command string. We cannot do this through
390 // PyRun_SimpleString here because the command string may contain escaped characters, and putting it inside
391 // another string to pass to PyRun_SimpleString messes up the escaping. So we use the following more complicated
392 // method to pass the command string directly down to Python.
393
394
Caroline Tice202f6b82011-01-17 21:55:19 +0000395 bool need_to_release_lock = true;
396
397 if (CurrentThreadHasPythonLock())
398 need_to_release_lock = false;
399 else if (!GetPythonLock (1))
400 {
401 fprintf ((m_dbg_stdout ? m_dbg_stdout : stdout),
402 "Python interpreter is currently locked by another thread; unable to process command.\n");
403 return false;
404 }
405
406 EnterSession ();
Caroline Tice4a461da2011-01-14 21:09:29 +0000407 bool success = false;
408
Greg Clayton63094e02010-06-23 01:19:29 +0000409 if (command)
Chris Lattner24943d22010-06-08 16:52:24 +0000410 {
Caroline Tice4a461da2011-01-14 21:09:29 +0000411 // Find the correct script interpreter dictionary in the main module.
412 PyObject *main_mod = PyImport_AddModule ("__main__");
413 PyObject *script_interpreter_dict = NULL;
414 if (main_mod != NULL)
415 {
416 PyObject *main_dict = PyModule_GetDict (main_mod);
417 if ((main_dict != NULL)
418 && PyDict_Check (main_dict))
419 {
420 // Go through the main dictionary looking for the correct python script interpreter dictionary
421 PyObject *key, *value;
422 Py_ssize_t pos = 0;
423
424 while (PyDict_Next (main_dict, &pos, &key, &value))
425 {
426 // We have stolen references to the key and value objects in the dictionary; we need to increment
427 // them now so that Python's garbage collector doesn't collect them out from under us.
428 Py_INCREF (key);
429 Py_INCREF (value);
430 if (strcmp (PyString_AsString (key), m_dictionary_name.c_str()) == 0)
431 {
432 script_interpreter_dict = value;
433 break;
434 }
435 }
436 }
437
438 if (script_interpreter_dict != NULL)
439 {
440 PyObject *pfunc = NULL;
441 PyObject *pmod = PyImport_AddModule ("embedded_interpreter");
442 if (pmod != NULL)
443 {
444 PyObject *pmod_dict = PyModule_GetDict (pmod);
445 if ((pmod_dict != NULL)
446 && PyDict_Check (pmod_dict))
447 {
448 PyObject *key, *value;
449 Py_ssize_t pos = 0;
450
451 while (PyDict_Next (pmod_dict, &pos, &key, &value))
452 {
453 Py_INCREF (key);
454 Py_INCREF (value);
455 if (strcmp (PyString_AsString (key), "run_one_line") == 0)
456 {
457 pfunc = value;
458 break;
459 }
460 }
461
462 PyObject *string_arg = PyString_FromString (command);
463 if (pfunc && string_arg && PyCallable_Check (pfunc))
464 {
465 PyObject *pargs = PyTuple_New (2);
466 if (pargs != NULL)
467 {
468 PyTuple_SetItem (pargs, 0, script_interpreter_dict);
469 PyTuple_SetItem (pargs, 1, string_arg);
470 PyObject *pvalue = PyObject_CallObject (pfunc, pargs);
471 Py_DECREF (pargs);
472 if (pvalue != NULL)
473 {
474 Py_DECREF (pvalue);
475 success = true;
476 }
477 else if (PyErr_Occurred ())
478 {
479 PyErr_Print();
480 PyErr_Clear();
481 }
482 }
483 }
484 }
485 }
486 Py_INCREF (script_interpreter_dict);
487 }
488 }
Greg Clayton63094e02010-06-23 01:19:29 +0000489
Caroline Tice0aa2e552011-01-14 00:29:16 +0000490 LeaveSession ();
491
Caroline Tice202f6b82011-01-17 21:55:19 +0000492 if (need_to_release_lock)
493 ReleasePythonLock();
494
Caroline Tice4a461da2011-01-14 21:09:29 +0000495 if (success)
Johnny Chen60dde642010-07-30 22:33:14 +0000496 return true;
497
498 // The one-liner failed. Append the error message.
499 if (result)
500 result->AppendErrorWithFormat ("python failed attempting to evaluate '%s'\n", command);
501 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000502 }
Johnny Chen60dde642010-07-30 22:33:14 +0000503
Caroline Tice0aa2e552011-01-14 00:29:16 +0000504 LeaveSession ();
Caroline Tice202f6b82011-01-17 21:55:19 +0000505
506 if (need_to_release_lock)
507 ReleasePythonLock ();
508
Johnny Chen60dde642010-07-30 22:33:14 +0000509 if (result)
510 result->AppendError ("empty command passed to python\n");
511 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000512}
513
514
515
516size_t
517ScriptInterpreterPython::InputReaderCallback
518(
519 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000520 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000521 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000522 const char *bytes,
523 size_t bytes_len
524)
525{
Caroline Tice2ade6112010-11-10 19:18:14 +0000526 lldb::thread_t embedded_interpreter_thread;
527 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
528
Chris Lattner24943d22010-06-08 16:52:24 +0000529 if (baton == NULL)
530 return 0;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000531
532 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
533
534 if (script_interpreter->m_script_lang != eScriptLanguagePython)
535 return 0;
536
Caroline Tice892fadd2011-06-16 16:27:19 +0000537 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
538 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
539
Chris Lattner24943d22010-06-08 16:52:24 +0000540 switch (notification)
541 {
542 case eInputReaderActivate:
543 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000544 if (!batch_mode)
545 {
546 out_stream->Printf ("Python Interactive Interpreter. To exit, type 'quit()', 'exit()' or Ctrl-D.\n");
547 out_stream->Flush();
548 }
Greg Clayton58928562011-02-09 01:08:52 +0000549
Chris Lattner24943d22010-06-08 16:52:24 +0000550 // Save terminal settings if we can
Greg Clayton58928562011-02-09 01:08:52 +0000551 int input_fd = reader.GetDebugger().GetInputFile().GetDescriptor();
552 if (input_fd == File::kInvalidDescriptor)
Greg Clayton24b48ff2010-10-17 22:03:32 +0000553 input_fd = STDIN_FILENO;
Caroline Ticec95c6d12010-09-14 22:49:06 +0000554
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000555 script_interpreter->SaveTerminalState(input_fd);
Greg Clayton99208582011-02-07 19:04:58 +0000556
Caroline Tice202f6b82011-01-17 21:55:19 +0000557 if (!CurrentThreadHasPythonLock())
558 {
559 while (!GetPythonLock(1))
560 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000561 out_stream->Printf ("Python interpreter locked on another thread; waiting to acquire lock...\n");
562 out_stream->Flush();
Caroline Tice202f6b82011-01-17 21:55:19 +0000563 }
564 script_interpreter->EnterSession ();
565 ReleasePythonLock();
566 }
567 else
568 script_interpreter->EnterSession ();
569
Caroline Tice2ade6112010-11-10 19:18:14 +0000570 char error_str[1024];
571 if (script_interpreter->m_embedded_python_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, error_str,
572 sizeof(error_str)))
573 {
574 if (log)
575 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in opening master pty (fd = %d).",
576 script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor());
577 embedded_interpreter_thread = Host::ThreadCreate ("<lldb.script-interpreter.embedded-python-loop>",
578 ScriptInterpreterPython::RunEmbeddedPythonInterpreter,
579 script_interpreter, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +0000580 if (IS_VALID_LLDB_HOST_THREAD(embedded_interpreter_thread))
Caroline Tice2ade6112010-11-10 19:18:14 +0000581 {
582 if (log)
Jason Molendae09e2542011-09-20 23:23:44 +0000583 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in creating thread (thread_t = %p)", embedded_interpreter_thread);
Caroline Tice2ade6112010-11-10 19:18:14 +0000584 Error detach_error;
585 Host::ThreadDetach (embedded_interpreter_thread, &detach_error);
586 }
587 else
588 {
589 if (log)
590 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed in creating thread");
591 reader.SetIsDone (true);
592 }
593 }
594 else
595 {
596 if (log)
597 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed to open master pty ");
598 reader.SetIsDone (true);
599 }
Chris Lattner24943d22010-06-08 16:52:24 +0000600 }
601 break;
602
603 case eInputReaderDeactivate:
Caroline Tice0aa2e552011-01-14 00:29:16 +0000604 script_interpreter->LeaveSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000605 break;
606
607 case eInputReaderReactivate:
Caroline Tice202f6b82011-01-17 21:55:19 +0000608 if (!CurrentThreadHasPythonLock())
609 {
610 while (!GetPythonLock(1))
611 {
612 // Wait until lock is acquired.
613 }
614 script_interpreter->EnterSession ();
615 ReleasePythonLock();
616 }
617 else
618 script_interpreter->EnterSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000619 break;
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000620
Caroline Tice4a348082011-05-02 20:41:46 +0000621 case eInputReaderAsynchronousOutputWritten:
622 break;
623
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000624 case eInputReaderInterrupt:
625 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "raise KeyboardInterrupt\n", 24);
626 break;
627
628 case eInputReaderEndOfFile:
629 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()\n", 7);
630 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000631
632 case eInputReaderGotToken:
Caroline Tice2ade6112010-11-10 19:18:14 +0000633 if (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor() != -1)
Chris Lattner24943d22010-06-08 16:52:24 +0000634 {
Caroline Tice2ade6112010-11-10 19:18:14 +0000635 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000636 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %lu", bytes,
Caroline Tice2ade6112010-11-10 19:18:14 +0000637 bytes_len);
638 if (bytes && bytes_len)
639 {
640 if ((int) bytes[0] == 4)
641 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()", 6);
642 else
643 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), bytes, bytes_len);
644 }
645 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "\n", 1);
Chris Lattner24943d22010-06-08 16:52:24 +0000646 }
Caroline Tice2ade6112010-11-10 19:18:14 +0000647 else
648 {
649 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000650 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %lu, Master File Descriptor is bad.",
Caroline Tice2ade6112010-11-10 19:18:14 +0000651 bytes,
652 bytes_len);
653 reader.SetIsDone (true);
654 }
655
Chris Lattner24943d22010-06-08 16:52:24 +0000656 break;
657
658 case eInputReaderDone:
Caroline Tice0aa2e552011-01-14 00:29:16 +0000659 script_interpreter->LeaveSession ();
660
Chris Lattner24943d22010-06-08 16:52:24 +0000661 // Restore terminal settings if they were validly saved
Caroline Tice2ade6112010-11-10 19:18:14 +0000662 if (log)
663 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Done, closing down input reader.");
Caroline Ticec95c6d12010-09-14 22:49:06 +0000664
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000665 script_interpreter->RestoreTerminalState ();
666
Caroline Tice2ade6112010-11-10 19:18:14 +0000667 script_interpreter->m_embedded_python_pty.CloseMasterFileDescriptor();
Chris Lattner24943d22010-06-08 16:52:24 +0000668 break;
669 }
670
671 return bytes_len;
672}
673
674
675void
Greg Clayton238c0a12010-09-18 01:14:36 +0000676ScriptInterpreterPython::ExecuteInterpreterLoop ()
Chris Lattner24943d22010-06-08 16:52:24 +0000677{
678 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
679
Caroline Tice0aa2e552011-01-14 00:29:16 +0000680 Debugger &debugger = GetCommandInterpreter().GetDebugger();
Caroline Ticec95c6d12010-09-14 22:49:06 +0000681
682 // At the moment, the only time the debugger does not have an input file handle is when this is called
683 // directly from Python, in which case it is both dangerous and unnecessary (not to mention confusing) to
684 // try to embed a running interpreter loop inside the already running Python interpreter loop, so we won't
685 // do it.
686
Greg Clayton58928562011-02-09 01:08:52 +0000687 if (!debugger.GetInputFile().IsValid())
Caroline Ticec95c6d12010-09-14 22:49:06 +0000688 return;
689
Greg Clayton63094e02010-06-23 01:19:29 +0000690 InputReaderSP reader_sp (new InputReader(debugger));
Chris Lattner24943d22010-06-08 16:52:24 +0000691 if (reader_sp)
692 {
693 Error error (reader_sp->Initialize (ScriptInterpreterPython::InputReaderCallback,
694 this, // baton
695 eInputReaderGranularityLine, // token size, to pass to callback function
696 NULL, // end token
697 NULL, // prompt
698 true)); // echo input
699
700 if (error.Success())
701 {
Greg Clayton63094e02010-06-23 01:19:29 +0000702 debugger.PushInputReader (reader_sp);
Caroline Tice2ade6112010-11-10 19:18:14 +0000703 m_embedded_thread_input_reader_sp = reader_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000704 }
705 }
706}
707
708bool
709ScriptInterpreterPython::ExecuteOneLineWithReturn (const char *in_string,
Enrico Granata59df36f2011-10-17 21:45:27 +0000710 ScriptInterpreter::ScriptReturnType return_type,
Chris Lattner24943d22010-06-08 16:52:24 +0000711 void *ret_value)
712{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000713
Caroline Tice202f6b82011-01-17 21:55:19 +0000714 bool need_to_release_lock = true;
715
716 if (CurrentThreadHasPythonLock())
717 need_to_release_lock = false;
718 else if (!GetPythonLock (1))
719 {
720 fprintf ((m_dbg_stdout ? m_dbg_stdout : stdout),
721 "Python interpreter is currently locked by another thread; unable to process command.\n");
722 return false;
723 }
724
725 EnterSession ();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000726
Chris Lattner24943d22010-06-08 16:52:24 +0000727 PyObject *py_return = NULL;
728 PyObject *mainmod = PyImport_AddModule ("__main__");
729 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000730 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000731 PyObject *py_error = NULL;
Johnny Chen60a7df52011-08-11 19:17:45 +0000732 bool ret_success = false;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000733 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000734 int success;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000735
736 if (PyDict_Check (globals))
737 {
738 PyObject *key, *value;
739 Py_ssize_t pos = 0;
740
741 int i = 0;
742 while (PyDict_Next (globals, &pos, &key, &value))
743 {
744 // We have stolen references to the key and value objects in the dictionary; we need to increment them now
745 // so that Python's garbage collector doesn't collect them out from under us.
746 Py_INCREF (key);
747 Py_INCREF (value);
748 char *c_str = PyString_AsString (key);
749 if (strcmp (c_str, m_dictionary_name.c_str()) == 0)
750 locals = value;
751 ++i;
752 }
753 }
Chris Lattner24943d22010-06-08 16:52:24 +0000754
Caroline Tice0aa2e552011-01-14 00:29:16 +0000755 if (locals == NULL)
756 {
757 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
758 should_decrement_locals = true;
759 }
760
761 if (locals == NULL)
762 {
763 locals = globals;
764 should_decrement_locals = false;
765 }
766
767 py_error = PyErr_Occurred();
768 if (py_error != NULL)
769 PyErr_Clear();
770
Chris Lattner24943d22010-06-08 16:52:24 +0000771 if (in_string != NULL)
772 {
773 py_return = PyRun_String (in_string, Py_eval_input, globals, locals);
774 if (py_return == NULL)
775 {
776 py_error = PyErr_Occurred ();
777 if (py_error != NULL)
778 PyErr_Clear ();
779
780 py_return = PyRun_String (in_string, Py_single_input, globals, locals);
781 }
782
Caroline Tice0aa2e552011-01-14 00:29:16 +0000783 if (locals != NULL
784 && should_decrement_locals)
785 Py_DECREF (locals);
786
Chris Lattner24943d22010-06-08 16:52:24 +0000787 if (py_return != NULL)
788 {
789 switch (return_type)
790 {
Enrico Granata59df36f2011-10-17 21:45:27 +0000791 case eScriptReturnTypeCharPtr: // "char *"
Chris Lattner24943d22010-06-08 16:52:24 +0000792 {
793 const char format[3] = "s#";
Enrico Granatae5e34cb2011-08-17 01:30:04 +0000794 success = PyArg_Parse (py_return, format, (char **) ret_value);
Chris Lattner24943d22010-06-08 16:52:24 +0000795 break;
796 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000797 case eScriptReturnTypeCharStrOrNone: // char* or NULL if py_return == Py_None
Enrico Granatac2a28252011-08-16 16:49:25 +0000798 {
799 const char format[3] = "z";
Enrico Granatae5e34cb2011-08-17 01:30:04 +0000800 success = PyArg_Parse (py_return, format, (char **) ret_value);
Enrico Granatac2a28252011-08-16 16:49:25 +0000801 break;
802 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000803 case eScriptReturnTypeBool:
Chris Lattner24943d22010-06-08 16:52:24 +0000804 {
805 const char format[2] = "b";
806 success = PyArg_Parse (py_return, format, (bool *) ret_value);
807 break;
808 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000809 case eScriptReturnTypeShortInt:
Chris Lattner24943d22010-06-08 16:52:24 +0000810 {
811 const char format[2] = "h";
812 success = PyArg_Parse (py_return, format, (short *) ret_value);
813 break;
814 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000815 case eScriptReturnTypeShortIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000816 {
817 const char format[2] = "H";
818 success = PyArg_Parse (py_return, format, (unsigned short *) ret_value);
819 break;
820 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000821 case eScriptReturnTypeInt:
Chris Lattner24943d22010-06-08 16:52:24 +0000822 {
823 const char format[2] = "i";
824 success = PyArg_Parse (py_return, format, (int *) ret_value);
825 break;
826 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000827 case eScriptReturnTypeIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000828 {
829 const char format[2] = "I";
830 success = PyArg_Parse (py_return, format, (unsigned int *) ret_value);
831 break;
832 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000833 case eScriptReturnTypeLongInt:
Chris Lattner24943d22010-06-08 16:52:24 +0000834 {
835 const char format[2] = "l";
836 success = PyArg_Parse (py_return, format, (long *) ret_value);
837 break;
838 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000839 case eScriptReturnTypeLongIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000840 {
841 const char format[2] = "k";
842 success = PyArg_Parse (py_return, format, (unsigned long *) ret_value);
843 break;
844 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000845 case eScriptReturnTypeLongLong:
Chris Lattner24943d22010-06-08 16:52:24 +0000846 {
847 const char format[2] = "L";
848 success = PyArg_Parse (py_return, format, (long long *) ret_value);
849 break;
850 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000851 case eScriptReturnTypeLongLongUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +0000852 {
853 const char format[2] = "K";
854 success = PyArg_Parse (py_return, format, (unsigned long long *) ret_value);
855 break;
856 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000857 case eScriptReturnTypeFloat:
Chris Lattner24943d22010-06-08 16:52:24 +0000858 {
859 const char format[2] = "f";
860 success = PyArg_Parse (py_return, format, (float *) ret_value);
861 break;
862 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000863 case eScriptReturnTypeDouble:
Chris Lattner24943d22010-06-08 16:52:24 +0000864 {
865 const char format[2] = "d";
866 success = PyArg_Parse (py_return, format, (double *) ret_value);
867 break;
868 }
Enrico Granata59df36f2011-10-17 21:45:27 +0000869 case eScriptReturnTypeChar:
Chris Lattner24943d22010-06-08 16:52:24 +0000870 {
871 const char format[2] = "c";
872 success = PyArg_Parse (py_return, format, (char *) ret_value);
873 break;
874 }
875 default:
876 {}
877 }
878 Py_DECREF (py_return);
879 if (success)
880 ret_success = true;
881 else
882 ret_success = false;
883 }
884 }
885
886 py_error = PyErr_Occurred();
887 if (py_error != NULL)
888 {
889 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
890 PyErr_Print ();
891 PyErr_Clear();
892 ret_success = false;
893 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000894
895 LeaveSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000896
Caroline Tice202f6b82011-01-17 21:55:19 +0000897 if (need_to_release_lock)
898 ReleasePythonLock();
899
Chris Lattner24943d22010-06-08 16:52:24 +0000900 return ret_success;
901}
902
903bool
904ScriptInterpreterPython::ExecuteMultipleLines (const char *in_string)
905{
Caroline Tice202f6b82011-01-17 21:55:19 +0000906 FILE *tmp_fh = (m_dbg_stdout ? m_dbg_stdout : stdout);
907 bool need_to_release_lock = true;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000908
Caroline Tice202f6b82011-01-17 21:55:19 +0000909 if (CurrentThreadHasPythonLock())
910 need_to_release_lock = false;
911 else
912 {
913 while (!GetPythonLock (1))
914 fprintf (tmp_fh, "Python interpreter locked on another thread; waiting to acquire lock...\n");
915 }
916
917 EnterSession ();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000918
Chris Lattner24943d22010-06-08 16:52:24 +0000919 bool success = false;
920 PyObject *py_return = NULL;
921 PyObject *mainmod = PyImport_AddModule ("__main__");
922 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000923 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +0000924 PyObject *py_error = NULL;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000925 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +0000926
Caroline Tice0aa2e552011-01-14 00:29:16 +0000927 if (PyDict_Check (globals))
928 {
929 PyObject *key, *value;
930 Py_ssize_t pos = 0;
931
932 while (PyDict_Next (globals, &pos, &key, &value))
933 {
934 // We have stolen references to the key and value objects in the dictionary; we need to increment them now
935 // so that Python's garbage collector doesn't collect them out from under us.
936 Py_INCREF (key);
937 Py_INCREF (value);
938 if (strcmp (PyString_AsString (key), m_dictionary_name.c_str()) == 0)
939 locals = value;
940 }
941 }
942
943 if (locals == NULL)
944 {
945 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
946 should_decrement_locals = true;
947 }
948
949 if (locals == NULL)
950 {
951 locals = globals;
952 should_decrement_locals = false;
953 }
954
955 py_error = PyErr_Occurred();
956 if (py_error != NULL)
957 PyErr_Clear();
958
Chris Lattner24943d22010-06-08 16:52:24 +0000959 if (in_string != NULL)
960 {
961 struct _node *compiled_node = PyParser_SimpleParseString (in_string, Py_file_input);
962 if (compiled_node)
963 {
964 PyCodeObject *compiled_code = PyNode_Compile (compiled_node, "temp.py");
965 if (compiled_code)
966 {
967 py_return = PyEval_EvalCode (compiled_code, globals, locals);
968 if (py_return != NULL)
969 {
970 success = true;
971 Py_DECREF (py_return);
972 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000973 if (locals && should_decrement_locals)
974 Py_DECREF (locals);
Chris Lattner24943d22010-06-08 16:52:24 +0000975 }
976 }
977 }
978
979 py_error = PyErr_Occurred ();
980 if (py_error != NULL)
981 {
982 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
983 PyErr_Print ();
984 PyErr_Clear();
985 success = false;
986 }
987
Caroline Tice0aa2e552011-01-14 00:29:16 +0000988 LeaveSession ();
989
Caroline Tice202f6b82011-01-17 21:55:19 +0000990 if (need_to_release_lock)
991 ReleasePythonLock();
992
Chris Lattner24943d22010-06-08 16:52:24 +0000993 return success;
994}
995
996static const char *g_reader_instructions = "Enter your Python command(s). Type 'DONE' to end.";
997
998size_t
999ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback
1000(
1001 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +00001002 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +00001003 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +00001004 const char *bytes,
1005 size_t bytes_len
1006)
1007{
Caroline Tice892fadd2011-06-16 16:27:19 +00001008 static StringList commands_in_progress;
1009
1010 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
1011 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
1012
Chris Lattner24943d22010-06-08 16:52:24 +00001013 switch (notification)
1014 {
1015 case eInputReaderActivate:
1016 {
1017 commands_in_progress.Clear();
Caroline Tice892fadd2011-06-16 16:27:19 +00001018 if (!batch_mode)
Chris Lattner24943d22010-06-08 16:52:24 +00001019 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001020 out_stream->Printf ("%s\n", g_reader_instructions);
Greg Clayton63094e02010-06-23 01:19:29 +00001021 if (reader.GetPrompt())
Caroline Tice892fadd2011-06-16 16:27:19 +00001022 out_stream->Printf ("%s", reader.GetPrompt());
1023 out_stream->Flush ();
Chris Lattner24943d22010-06-08 16:52:24 +00001024 }
1025 }
1026 break;
1027
1028 case eInputReaderDeactivate:
1029 break;
1030
1031 case eInputReaderReactivate:
Caroline Tice892fadd2011-06-16 16:27:19 +00001032 if (reader.GetPrompt() && !batch_mode)
Caroline Ticef81b4c52010-10-27 18:34:42 +00001033 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001034 out_stream->Printf ("%s", reader.GetPrompt());
1035 out_stream->Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +00001036 }
Chris Lattner24943d22010-06-08 16:52:24 +00001037 break;
1038
Caroline Tice4a348082011-05-02 20:41:46 +00001039 case eInputReaderAsynchronousOutputWritten:
1040 break;
1041
Chris Lattner24943d22010-06-08 16:52:24 +00001042 case eInputReaderGotToken:
1043 {
1044 std::string temp_string (bytes, bytes_len);
1045 commands_in_progress.AppendString (temp_string.c_str());
Caroline Tice892fadd2011-06-16 16:27:19 +00001046 if (!reader.IsDone() && reader.GetPrompt() && !batch_mode)
Caroline Ticef81b4c52010-10-27 18:34:42 +00001047 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001048 out_stream->Printf ("%s", reader.GetPrompt());
1049 out_stream->Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +00001050 }
Chris Lattner24943d22010-06-08 16:52:24 +00001051 }
1052 break;
1053
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001054 case eInputReaderEndOfFile:
1055 case eInputReaderInterrupt:
1056 // Control-c (SIGINT) & control-d both mean finish & exit.
1057 reader.SetIsDone(true);
1058
1059 // Control-c (SIGINT) ALSO means cancel; do NOT create a breakpoint command.
1060 if (notification == eInputReaderInterrupt)
1061 commands_in_progress.Clear();
1062
1063 // Fall through here...
1064
Chris Lattner24943d22010-06-08 16:52:24 +00001065 case eInputReaderDone:
1066 {
1067 BreakpointOptions *bp_options = (BreakpointOptions *)baton;
1068 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1069 data_ap->user_source.AppendList (commands_in_progress);
1070 if (data_ap.get())
1071 {
Greg Clayton63094e02010-06-23 01:19:29 +00001072 ScriptInterpreter *interpreter = reader.GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
Chris Lattner24943d22010-06-08 16:52:24 +00001073 if (interpreter)
1074 {
1075 if (interpreter->GenerateBreakpointCommandCallbackData (data_ap->user_source,
1076 data_ap->script_source))
1077 {
1078 if (data_ap->script_source.GetSize() == 1)
1079 {
1080 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1081 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
1082 }
1083 }
Caroline Tice892fadd2011-06-16 16:27:19 +00001084 else if (!batch_mode)
1085 {
1086 out_stream->Printf ("Warning: No command attached to breakpoint.\n");
1087 out_stream->Flush();
1088 }
Chris Lattner24943d22010-06-08 16:52:24 +00001089 }
1090 else
1091 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001092 if (!batch_mode)
1093 {
1094 out_stream->Printf ("Warning: Unable to find script intepreter; no command attached to breakpoint.\n");
1095 out_stream->Flush();
1096 }
Chris Lattner24943d22010-06-08 16:52:24 +00001097 }
1098 }
1099 }
1100 break;
1101
1102 }
1103
1104 return bytes_len;
1105}
1106
1107void
Greg Clayton238c0a12010-09-18 01:14:36 +00001108ScriptInterpreterPython::CollectDataForBreakpointCommandCallback (BreakpointOptions *bp_options,
Chris Lattner24943d22010-06-08 16:52:24 +00001109 CommandReturnObject &result)
1110{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001111 Debugger &debugger = GetCommandInterpreter().GetDebugger();
1112
Greg Clayton63094e02010-06-23 01:19:29 +00001113 InputReaderSP reader_sp (new InputReader (debugger));
Chris Lattner24943d22010-06-08 16:52:24 +00001114
1115 if (reader_sp)
1116 {
1117 Error err = reader_sp->Initialize (
1118 ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback,
1119 bp_options, // baton
1120 eInputReaderGranularityLine, // token size, for feeding data to callback function
1121 "DONE", // end token
1122 "> ", // prompt
1123 true); // echo input
1124
1125 if (err.Success())
Greg Clayton63094e02010-06-23 01:19:29 +00001126 debugger.PushInputReader (reader_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001127 else
1128 {
1129 result.AppendError (err.AsCString());
1130 result.SetStatus (eReturnStatusFailed);
1131 }
1132 }
1133 else
1134 {
1135 result.AppendError("out of memory");
1136 result.SetStatus (eReturnStatusFailed);
1137 }
1138}
1139
Johnny Chen3e0571b2010-09-11 00:23:59 +00001140// Set a Python one-liner as the callback for the breakpoint.
Johnny Chend1c2dca2010-09-10 18:21:10 +00001141void
Greg Clayton238c0a12010-09-18 01:14:36 +00001142ScriptInterpreterPython::SetBreakpointCommandCallback (BreakpointOptions *bp_options,
Johnny Chend1c2dca2010-09-10 18:21:10 +00001143 const char *oneliner)
1144{
1145 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1146
1147 // It's necessary to set both user_source and script_source to the oneliner.
1148 // The former is used to generate callback description (as in breakpoint command list)
1149 // while the latter is used for Python to interpret during the actual callback.
Caroline Tice5136f942010-09-27 21:35:15 +00001150
Johnny Chend1c2dca2010-09-10 18:21:10 +00001151 data_ap->user_source.AppendString (oneliner);
Johnny Chend1c2dca2010-09-10 18:21:10 +00001152
Caroline Tice5136f942010-09-27 21:35:15 +00001153 if (GenerateBreakpointCommandCallbackData (data_ap->user_source, data_ap->script_source))
1154 {
1155 if (data_ap->script_source.GetSize() == 1)
1156 {
1157 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1158 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
1159 }
1160 }
1161
Johnny Chend1c2dca2010-09-10 18:21:10 +00001162 return;
1163}
1164
Chris Lattner24943d22010-06-08 16:52:24 +00001165bool
1166ScriptInterpreterPython::ExportFunctionDefinitionToInterpreter (StringList &function_def)
1167{
1168 // Convert StringList to one long, newline delimited, const char *.
1169 std::string function_def_string;
1170
1171 int num_lines = function_def.GetSize();
1172
1173 for (int i = 0; i < num_lines; ++i)
1174 {
1175 function_def_string.append (function_def.GetStringAtIndex(i));
1176 if (function_def_string.at (function_def_string.length() - 1) != '\n')
1177 function_def_string.append ("\n");
1178
1179 }
1180
1181 return ExecuteMultipleLines (function_def_string.c_str());
1182}
1183
Enrico Granataf7a9b142011-07-15 02:26:42 +00001184// TODO move both GenerateTypeScriptFunction and GenerateBreakpointCommandCallbackData to actually
1185// use this code to generate their functions
1186bool
1187ScriptInterpreterPython::GenerateFunction(std::string& signature, StringList &input, StringList &output)
1188{
1189 int num_lines = input.GetSize ();
1190 if (num_lines == 0)
1191 return false;
1192 StreamString sstr;
1193 StringList auto_generated_function;
1194 auto_generated_function.AppendString (signature.c_str());
1195 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1196 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1197 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1198 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1199 // global dictionary.
1200
1201 // Wrap everything up inside the function, increasing the indentation.
1202
1203 for (int i = 0; i < num_lines; ++i)
1204 {
1205 sstr.Clear ();
1206 sstr.Printf (" %s", input.GetStringAtIndex (i));
1207 auto_generated_function.AppendString (sstr.GetData());
1208 }
1209 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1210 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1211 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1212 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1213
1214 // Verify that the results are valid Python.
1215
1216 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1217 return false;
1218
1219 return true;
1220
1221}
1222
1223// this implementation is identical to GenerateBreakpointCommandCallbackData (apart from the name
1224// given to generated functions, of course)
1225bool
1226ScriptInterpreterPython::GenerateTypeScriptFunction (StringList &user_input, StringList &output)
1227{
1228 static int num_created_functions = 0;
1229 user_input.RemoveBlankLines ();
1230 int num_lines = user_input.GetSize ();
1231 StreamString sstr;
1232
1233 // Check to see if we have any data; if not, just return.
1234 if (user_input.GetSize() == 0)
1235 return false;
1236
1237 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1238 // ValueObject as parameter to the function.
1239
1240 sstr.Printf ("lldb_autogen_python_type_print_func_%d", num_created_functions);
1241 ++num_created_functions;
1242 std::string auto_generated_function_name = sstr.GetData();
1243
1244 sstr.Clear();
1245 StringList auto_generated_function;
1246
1247 // Create the function name & definition string.
1248
1249 sstr.Printf ("def %s (valobj, dict):", auto_generated_function_name.c_str());
1250 auto_generated_function.AppendString (sstr.GetData());
1251
1252 // Pre-pend code for setting up the session dictionary.
1253
1254 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1255 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1256 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1257 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1258 // global dictionary.
1259
1260 // Wrap everything up inside the function, increasing the indentation.
1261
1262 for (int i = 0; i < num_lines; ++i)
1263 {
1264 sstr.Clear ();
1265 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1266 auto_generated_function.AppendString (sstr.GetData());
1267 }
1268
1269 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1270 // got written to the values in the global dictionary, not the session dictionary).
1271
1272 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1273 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1274 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1275 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1276
1277 // Verify that the results are valid Python.
1278
1279 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1280 return false;
1281
1282 // Store the name of the auto-generated function to be called.
1283
1284 output.AppendString (auto_generated_function_name.c_str());
1285 return true;
1286}
1287
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001288bool
Enrico Granatac2a28252011-08-16 16:49:25 +00001289ScriptInterpreterPython::GenerateScriptAliasFunction (StringList &user_input, StringList &output)
1290{
1291 static int num_created_functions = 0;
1292 user_input.RemoveBlankLines ();
1293 int num_lines = user_input.GetSize ();
1294 StreamString sstr;
1295
1296 // Check to see if we have any data; if not, just return.
1297 if (user_input.GetSize() == 0)
1298 return false;
1299
1300 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1301 // ValueObject as parameter to the function.
1302
1303 sstr.Printf ("lldb_autogen_python_cmd_alias_func_%d", num_created_functions);
1304 ++num_created_functions;
1305 std::string auto_generated_function_name = sstr.GetData();
1306
1307 sstr.Clear();
1308 StringList auto_generated_function;
1309
1310 // Create the function name & definition string.
1311
Enrico Granata271568f2011-09-09 01:41:30 +00001312 sstr.Printf ("def %s (debugger, args, result, dict):", auto_generated_function_name.c_str());
Enrico Granatac2a28252011-08-16 16:49:25 +00001313 auto_generated_function.AppendString (sstr.GetData());
1314
1315 // Pre-pend code for setting up the session dictionary.
1316
1317 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1318 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1319 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1320 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1321 // global dictionary.
1322
1323 // Wrap everything up inside the function, increasing the indentation.
1324
1325 for (int i = 0; i < num_lines; ++i)
1326 {
1327 sstr.Clear ();
1328 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1329 auto_generated_function.AppendString (sstr.GetData());
1330 }
1331
1332 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1333 // got written to the values in the global dictionary, not the session dictionary).
1334
1335 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1336 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1337 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1338 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1339
1340 // Verify that the results are valid Python.
1341
1342 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1343 return false;
1344
1345 // Store the name of the auto-generated function to be called.
1346
1347 output.AppendString (auto_generated_function_name.c_str());
1348 return true;
1349}
1350
1351
1352bool
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001353ScriptInterpreterPython::GenerateTypeSynthClass (StringList &user_input, StringList &output)
1354{
1355 static int num_created_classes = 0;
1356 user_input.RemoveBlankLines ();
1357 int num_lines = user_input.GetSize ();
1358 StreamString sstr;
1359
1360 // Check to see if we have any data; if not, just return.
1361 if (user_input.GetSize() == 0)
1362 return false;
1363
1364 // Wrap all user input into a Python class
1365
1366 sstr.Printf ("lldb_autogen_python_type_synth_class_%d", num_created_classes);
1367 ++num_created_classes;
1368 std::string auto_generated_class_name = sstr.GetData();
1369
1370 sstr.Clear();
1371 StringList auto_generated_class;
1372
1373 // Create the function name & definition string.
1374
1375 sstr.Printf ("class %s:", auto_generated_class_name.c_str());
1376 auto_generated_class.AppendString (sstr.GetData());
1377
1378 // Wrap everything up inside the class, increasing the indentation.
1379
1380 for (int i = 0; i < num_lines; ++i)
1381 {
1382 sstr.Clear ();
1383 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1384 auto_generated_class.AppendString (sstr.GetData());
1385 }
1386
1387
1388 // Verify that the results are valid Python.
1389 // (even though the method is ExportFunctionDefinitionToInterpreter, a class will actually be exported)
1390 // (TODO: rename that method to ExportDefinitionToInterpreter)
1391 if (!ExportFunctionDefinitionToInterpreter (auto_generated_class))
1392 return false;
1393
1394 // Store the name of the auto-generated class
1395
1396 output.AppendString (auto_generated_class_name.c_str());
1397 return true;
1398}
1399
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001400void*
1401ScriptInterpreterPython::CreateSyntheticScriptedProvider (std::string class_name,
1402 lldb::ValueObjectSP valobj)
1403{
1404 if (class_name.empty())
1405 return NULL;
1406
1407 if (!valobj.get())
1408 return NULL;
1409
Enrico Granata979e20d2011-07-29 19:53:35 +00001410 Target *target = valobj->GetUpdatePoint().GetTargetSP().get();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001411
1412 if (!target)
1413 return NULL;
1414
1415 Debugger &debugger = target->GetDebugger();
1416 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1417 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1418
1419 if (!script_interpreter)
1420 return NULL;
1421
1422 void* ret_val;
1423
1424 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
Enrico Granata91544802011-09-06 19:20:51 +00001425
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001426 {
Enrico Granata91544802011-09-06 19:20:51 +00001427 Locker py_lock(this, tmp_fh);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001428 ret_val = g_swig_synthetic_script (class_name,
1429 python_interpreter->m_dictionary_name.c_str(),
1430 valobj);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001431 }
1432
1433 return ret_val;
1434}
1435
Enrico Granataf7a9b142011-07-15 02:26:42 +00001436bool
1437ScriptInterpreterPython::GenerateTypeScriptFunction (const char* oneliner, StringList &output)
1438{
1439 StringList input(oneliner);
1440 return GenerateTypeScriptFunction(input, output);
1441}
1442
Chris Lattner24943d22010-06-08 16:52:24 +00001443bool
1444ScriptInterpreterPython::GenerateBreakpointCommandCallbackData (StringList &user_input, StringList &callback_data)
1445{
1446 static int num_created_functions = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001447 user_input.RemoveBlankLines ();
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001448 int num_lines = user_input.GetSize ();
1449 StreamString sstr;
Chris Lattner24943d22010-06-08 16:52:24 +00001450
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001451 // Check to see if we have any data; if not, just return.
1452 if (user_input.GetSize() == 0)
1453 return false;
1454
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001455 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1456 // frame and breakpoint location as parameters to the function.
Caroline Ticeb447e842010-09-21 19:25:28 +00001457
Caroline Ticeb447e842010-09-21 19:25:28 +00001458
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001459 sstr.Printf ("lldb_autogen_python_bp_callback_func_%d", num_created_functions);
1460 ++num_created_functions;
1461 std::string auto_generated_function_name = sstr.GetData();
Caroline Ticeb447e842010-09-21 19:25:28 +00001462
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001463 sstr.Clear();
Caroline Ticeb447e842010-09-21 19:25:28 +00001464 StringList auto_generated_function;
Caroline Ticeb447e842010-09-21 19:25:28 +00001465
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001466 // Create the function name & definition string.
1467
Caroline Tice0aa2e552011-01-14 00:29:16 +00001468 sstr.Printf ("def %s (frame, bp_loc, dict):", auto_generated_function_name.c_str());
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001469 auto_generated_function.AppendString (sstr.GetData());
Caroline Tice0aa2e552011-01-14 00:29:16 +00001470
1471 // Pre-pend code for setting up the session dictionary.
1472
1473 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
1474 auto_generated_function.AppendString (" new_keys = dict.keys()"); // Make a list of keys in the session dict
1475 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
1476 auto_generated_function.AppendString (" global_dict.update (dict)"); // Add the session dictionary to the
1477 // global dictionary.
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001478
1479 // Wrap everything up inside the function, increasing the indentation.
Chris Lattner24943d22010-06-08 16:52:24 +00001480
1481 for (int i = 0; i < num_lines; ++i)
1482 {
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001483 sstr.Clear ();
1484 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1485 auto_generated_function.AppendString (sstr.GetData());
Caroline Ticeb447e842010-09-21 19:25:28 +00001486 }
Chris Lattner24943d22010-06-08 16:52:24 +00001487
Caroline Tice0aa2e552011-01-14 00:29:16 +00001488 // Append code to clean up the global dictionary and update the session dictionary (all updates in the function
1489 // got written to the values in the global dictionary, not the session dictionary).
1490
1491 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
1492 auto_generated_function.AppendString (" dict[key] = global_dict[key]"); // Update session dict values
1493 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1494 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1495
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001496 // Verify that the results are valid Python.
Chris Lattner24943d22010-06-08 16:52:24 +00001497
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001498 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
Caroline Ticeb447e842010-09-21 19:25:28 +00001499 {
Caroline Ticeb447e842010-09-21 19:25:28 +00001500 return false;
Chris Lattner24943d22010-06-08 16:52:24 +00001501 }
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001502
1503 // Store the name of the auto-generated function to be called.
1504
1505 callback_data.AppendString (auto_generated_function_name.c_str());
1506 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001507}
1508
Enrico Granataf7a9b142011-07-15 02:26:42 +00001509std::string
1510ScriptInterpreterPython::CallPythonScriptFunction (const char *python_function_name,
1511 lldb::ValueObjectSP valobj)
1512{
1513
1514 if (!python_function_name || !(*python_function_name))
1515 return "<no function>";
1516
1517 if (!valobj.get())
1518 return "<no object>";
1519
Enrico Granata979e20d2011-07-29 19:53:35 +00001520 Target *target = valobj->GetUpdatePoint().GetTargetSP().get();
Enrico Granataf7a9b142011-07-15 02:26:42 +00001521
1522 if (!target)
1523 return "<no target>";
1524
1525 Debugger &debugger = target->GetDebugger();
1526 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1527 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1528
1529 if (!script_interpreter)
1530 return "<no python>";
1531
1532 std::string ret_val;
1533
1534 if (python_function_name
1535 && *python_function_name)
1536 {
1537 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
Enrico Granata91544802011-09-06 19:20:51 +00001538
Enrico Granataf7a9b142011-07-15 02:26:42 +00001539 {
Enrico Granata91544802011-09-06 19:20:51 +00001540 Locker py_lock(python_interpreter, tmp_fh);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001541 ret_val = g_swig_typescript_callback (python_function_name,
1542 python_interpreter->m_dictionary_name.c_str(),
1543 valobj);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001544 }
1545 }
1546 else
1547 return "<no function name>";
1548
1549 return ret_val;
1550
1551}
1552
Greg Clayton5144f382010-10-07 17:14:24 +00001553bool
1554ScriptInterpreterPython::BreakpointCallbackFunction
1555(
1556 void *baton,
1557 StoppointCallbackContext *context,
1558 user_id_t break_id,
1559 user_id_t break_loc_id
1560)
1561{
1562 BreakpointOptions::CommandData *bp_option_data = (BreakpointOptions::CommandData *) baton;
1563 const char *python_function_name = bp_option_data->script_source.GetStringAtIndex (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001564
1565 if (!context)
1566 return true;
1567
Greg Clayton567e7f32011-09-22 04:58:26 +00001568 Target *target = context->exe_ctx.GetTargetPtr();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001569
1570 if (!target)
1571 return true;
1572
1573 Debugger &debugger = target->GetDebugger();
1574 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1575 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1576
1577 if (!script_interpreter)
1578 return true;
Greg Clayton5144f382010-10-07 17:14:24 +00001579
1580 if (python_function_name != NULL
1581 && python_function_name[0] != '\0')
1582 {
Greg Clayton567e7f32011-09-22 04:58:26 +00001583 const StackFrameSP stop_frame_sp (context->exe_ctx.GetFrameSP());
Greg Clayton5144f382010-10-07 17:14:24 +00001584 BreakpointSP breakpoint_sp = target->GetBreakpointByID (break_id);
Greg Claytone86cbb92011-03-22 01:14:58 +00001585 if (breakpoint_sp)
Caroline Tice0aa2e552011-01-14 00:29:16 +00001586 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001587 const BreakpointLocationSP bp_loc_sp (breakpoint_sp->FindLocationByID (break_loc_id));
1588
1589 if (stop_frame_sp && bp_loc_sp)
Caroline Tice202f6b82011-01-17 21:55:19 +00001590 {
Greg Claytone86cbb92011-03-22 01:14:58 +00001591 bool ret_val = true;
1592 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
Enrico Granata91544802011-09-06 19:20:51 +00001593
Greg Claytone86cbb92011-03-22 01:14:58 +00001594 {
Enrico Granata91544802011-09-06 19:20:51 +00001595 Locker py_lock(python_interpreter, tmp_fh);
Greg Claytone86cbb92011-03-22 01:14:58 +00001596 ret_val = g_swig_breakpoint_callback (python_function_name,
1597 python_interpreter->m_dictionary_name.c_str(),
1598 stop_frame_sp,
1599 bp_loc_sp);
Greg Claytone86cbb92011-03-22 01:14:58 +00001600 }
1601 return ret_val;
Caroline Tice202f6b82011-01-17 21:55:19 +00001602 }
Caroline Tice0aa2e552011-01-14 00:29:16 +00001603 }
Greg Clayton5144f382010-10-07 17:14:24 +00001604 }
1605 // We currently always true so we stop in case anything goes wrong when
1606 // trying to call the script function
1607 return true;
1608}
Caroline Tice2ade6112010-11-10 19:18:14 +00001609
1610lldb::thread_result_t
1611ScriptInterpreterPython::RunEmbeddedPythonInterpreter (lldb::thread_arg_t baton)
1612{
1613 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
1614
1615 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
1616
1617 if (log)
1618 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread starting...", baton);
1619
1620 char error_str[1024];
1621 const char *pty_slave_name = script_interpreter->m_embedded_python_pty.GetSlaveName (error_str, sizeof (error_str));
Caroline Tice202f6b82011-01-17 21:55:19 +00001622 bool need_to_release_lock = true;
1623 bool safe_to_run = false;
Caroline Tice0aa2e552011-01-14 00:29:16 +00001624
Caroline Tice202f6b82011-01-17 21:55:19 +00001625 if (CurrentThreadHasPythonLock())
1626 {
1627 safe_to_run = true;
1628 need_to_release_lock = false;
1629 }
1630 else
1631 {
1632 int interval = 1;
1633 safe_to_run = GetPythonLock (interval);
1634 while (!safe_to_run)
1635 {
1636 interval = interval * 2;
1637 safe_to_run = GetPythonLock (interval);
1638 }
1639 }
1640
1641 if (pty_slave_name != NULL && safe_to_run)
1642 {
Caroline Tice2ade6112010-11-10 19:18:14 +00001643 StreamString run_string;
Caroline Tice2ade6112010-11-10 19:18:14 +00001644
Caroline Tice202f6b82011-01-17 21:55:19 +00001645 script_interpreter->EnterSession ();
1646
Caroline Tice0aa2e552011-01-14 00:29:16 +00001647 run_string.Printf ("run_one_line (%s, 'save_stderr = sys.stderr')", script_interpreter->m_dictionary_name.c_str());
1648 PyRun_SimpleString (run_string.GetData());
1649 run_string.Clear ();
1650
1651 run_string.Printf ("run_one_line (%s, 'sys.stderr = sys.stdout')", script_interpreter->m_dictionary_name.c_str());
1652 PyRun_SimpleString (run_string.GetData());
1653 run_string.Clear ();
1654
1655 run_string.Printf ("run_one_line (%s, 'save_stdin = sys.stdin')", script_interpreter->m_dictionary_name.c_str());
1656 PyRun_SimpleString (run_string.GetData());
1657 run_string.Clear ();
1658
1659 run_string.Printf ("run_one_line (%s, \"sys.stdin = open ('%s', 'r')\")", script_interpreter->m_dictionary_name.c_str(),
1660 pty_slave_name);
1661 PyRun_SimpleString (run_string.GetData());
1662 run_string.Clear ();
1663
Johnny Chen8054ba32011-03-11 00:28:50 +00001664 // The following call drops into the embedded interpreter loop and stays there until the
1665 // user chooses to exit from the Python interpreter.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001666
Caroline Ticece207c12011-03-11 00:21:55 +00001667 // When in the embedded interpreter, the user can call arbitrary system and Python stuff, which may require
Johnny Chen8054ba32011-03-11 00:28:50 +00001668 // 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 +00001669 // calls to Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS.
1670
1671 // We ALSO need to surround the call to the embedded interpreter with calls to PyGILState_Ensure and
1672 // PyGILState_Release. This is because this embedded interpreter is being run on a DIFFERENT THREAD than
1673 // the thread on which the call to Py_Initialize (and PyEval_InitThreads) was called. Those initializations
1674 // called PyGILState_Ensure on *that* thread, but it also needs to be called on *this* thread. Otherwise,
1675 // if the user calls Python code that does threading stuff, the interpreter state will be off, and things could
1676 // hang (it's happened before).
1677
Caroline Tice9d352ce2011-03-07 23:24:28 +00001678 Py_BEGIN_ALLOW_THREADS
1679 PyGILState_STATE gstate = PyGILState_Ensure();
1680
Caroline Tice0aa2e552011-01-14 00:29:16 +00001681 run_string.Printf ("run_python_interpreter (%s)", script_interpreter->m_dictionary_name.c_str());
1682 PyRun_SimpleString (run_string.GetData());
1683 run_string.Clear ();
Caroline Tice2ade6112010-11-10 19:18:14 +00001684
Caroline Tice9d352ce2011-03-07 23:24:28 +00001685 PyGILState_Release (gstate);
1686 Py_END_ALLOW_THREADS
1687
Caroline Tice0aa2e552011-01-14 00:29:16 +00001688 run_string.Printf ("run_one_line (%s, 'sys.stdin = save_stdin')", script_interpreter->m_dictionary_name.c_str());
1689 PyRun_SimpleString (run_string.GetData());
1690 run_string.Clear();
1691
1692 run_string.Printf ("run_one_line (%s, 'sys.stderr = save_stderr')", script_interpreter->m_dictionary_name.c_str());
1693 PyRun_SimpleString (run_string.GetData());
1694 run_string.Clear();
Caroline Tice202f6b82011-01-17 21:55:19 +00001695
1696 script_interpreter->LeaveSession ();
1697
Caroline Tice2ade6112010-11-10 19:18:14 +00001698 }
1699
Caroline Tice202f6b82011-01-17 21:55:19 +00001700 if (!safe_to_run)
1701 fprintf ((script_interpreter->m_dbg_stdout ? script_interpreter->m_dbg_stdout : stdout),
1702 "Python interpreter locked on another thread; unable to acquire lock.\n");
1703
1704 if (need_to_release_lock)
1705 ReleasePythonLock ();
1706
Caroline Tice2ade6112010-11-10 19:18:14 +00001707 if (script_interpreter->m_embedded_thread_input_reader_sp)
1708 script_interpreter->m_embedded_thread_input_reader_sp->SetIsDone (true);
1709
1710 script_interpreter->m_embedded_python_pty.CloseSlaveFileDescriptor();
Caroline Tice0aa2e552011-01-14 00:29:16 +00001711
1712 script_interpreter->m_pty_slave_is_open = false;
Caroline Tice2ade6112010-11-10 19:18:14 +00001713
1714 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT);
1715 if (log)
1716 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread exiting...", baton);
1717
1718
Johnny Chen8054ba32011-03-11 00:28:50 +00001719 // Clean up the input reader and make the debugger pop it off the stack.
Caroline Tice0aa2e552011-01-14 00:29:16 +00001720 Debugger &debugger = script_interpreter->GetCommandInterpreter().GetDebugger();
Caroline Tice2ade6112010-11-10 19:18:14 +00001721 const InputReaderSP reader_sp = script_interpreter->m_embedded_thread_input_reader_sp;
1722 script_interpreter->m_embedded_thread_input_reader_sp.reset();
1723 debugger.PopInputReader (reader_sp);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001724
Caroline Tice2ade6112010-11-10 19:18:14 +00001725 return NULL;
1726}
1727
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001728uint32_t
1729ScriptInterpreterPython::CalculateNumChildren (void *implementor)
1730{
1731 if (!implementor)
1732 return 0;
1733
1734 if (!g_swig_calc_children)
1735 return 0;
1736
1737 ScriptInterpreterPython *python_interpreter = this;
1738
1739 uint32_t ret_val = 0;
1740
1741 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
Enrico Granata91544802011-09-06 19:20:51 +00001742
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001743 {
Enrico Granata91544802011-09-06 19:20:51 +00001744 Locker py_lock(python_interpreter, tmp_fh);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001745 ret_val = g_swig_calc_children (implementor);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001746 }
1747
1748 return ret_val;
1749}
1750
Enrico Granata91544802011-09-06 19:20:51 +00001751lldb::ValueObjectSP
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001752ScriptInterpreterPython::GetChildAtIndex (void *implementor, uint32_t idx)
1753{
1754 if (!implementor)
Enrico Granata91544802011-09-06 19:20:51 +00001755 return lldb::ValueObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001756
Enrico Granata91544802011-09-06 19:20:51 +00001757 if (!g_swig_get_child_index || !g_swig_cast_to_sbvalue)
1758 return lldb::ValueObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001759
1760 ScriptInterpreterPython *python_interpreter = this;
1761
Enrico Granata91544802011-09-06 19:20:51 +00001762 void* child_ptr = NULL;
1763 lldb::SBValue* value_sb = NULL;
1764 lldb::ValueObjectSP ret_val;
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001765
1766 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
Enrico Granata91544802011-09-06 19:20:51 +00001767
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001768 {
Enrico Granata91544802011-09-06 19:20:51 +00001769 Locker py_lock(python_interpreter, tmp_fh);
1770 child_ptr = g_swig_get_child_index (implementor,idx);
1771 if (child_ptr != NULL && child_ptr != Py_None)
1772 {
1773 value_sb = (lldb::SBValue*)g_swig_cast_to_sbvalue(child_ptr);
1774 if (value_sb == NULL)
1775 Py_XDECREF(child_ptr);
1776 else
1777 ret_val = value_sb->get_sp();
1778 }
1779 else
1780 {
1781 Py_XDECREF(child_ptr);
1782 }
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001783 }
1784
1785 return ret_val;
1786}
1787
1788int
1789ScriptInterpreterPython::GetIndexOfChildWithName (void *implementor, const char* child_name)
1790{
1791 if (!implementor)
1792 return UINT32_MAX;
1793
1794 if (!g_swig_get_index_child)
1795 return UINT32_MAX;
1796
1797 ScriptInterpreterPython *python_interpreter = this;
1798
1799 int ret_val = UINT32_MAX;
1800
1801 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
Enrico Granata91544802011-09-06 19:20:51 +00001802
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001803 {
Enrico Granata91544802011-09-06 19:20:51 +00001804 Locker py_lock(python_interpreter, tmp_fh);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001805 ret_val = g_swig_get_index_child (implementor, child_name);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001806 }
1807
1808 return ret_val;
1809}
1810
Enrico Granata979e20d2011-07-29 19:53:35 +00001811void
1812ScriptInterpreterPython::UpdateSynthProviderInstance (void* implementor)
1813{
1814 if (!implementor)
1815 return;
1816
1817 if (!g_swig_update_provider)
1818 return;
1819
1820 ScriptInterpreterPython *python_interpreter = this;
1821
1822 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
Enrico Granata91544802011-09-06 19:20:51 +00001823
Enrico Granata979e20d2011-07-29 19:53:35 +00001824 {
Enrico Granata91544802011-09-06 19:20:51 +00001825 Locker py_lock(python_interpreter, tmp_fh);
Enrico Granata979e20d2011-07-29 19:53:35 +00001826 g_swig_update_provider (implementor);
Enrico Granata979e20d2011-07-29 19:53:35 +00001827 }
1828
1829 return;
1830}
1831
Enrico Granatac2a28252011-08-16 16:49:25 +00001832bool
Enrico Granata59df36f2011-10-17 21:45:27 +00001833ScriptInterpreterPython::LoadScriptingModule (const char* pathname,
1834 lldb_private::Error& error)
1835{
1836 if (!pathname || !pathname[0])
1837 {
1838 error.SetErrorString("invalid pathname");
1839 return false;
1840 }
1841
1842 if (!g_swig_call_module_init)
1843 {
1844 error.SetErrorString("internal helper function missing");
1845 return false;
1846 }
1847
1848 ScriptInterpreterPython *python_interpreter = this;
1849
1850 lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().GetSP();
1851
1852 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
1853
1854 {
1855 Locker py_lock(python_interpreter, tmp_fh);
1856
1857 FileSpec target_file(pathname, true);
1858
1859 // TODO: would we want to reject any other value?
1860 if (target_file.GetFileType() == FileSpec::eFileTypeInvalid ||
1861 target_file.GetFileType() == FileSpec::eFileTypeUnknown)
1862 {
1863 error.SetErrorString("invalid pathname");
1864 return false;
1865 }
1866
1867 const char* directory = target_file.GetDirectory().GetCString();
1868 std::string basename(target_file.GetFilename().GetCString());
1869
1870 // now make sure that Python has "directory" in the search path
1871 StreamString command_stream;
1872 command_stream.Printf("if not (sys.path.__contains__('%s')):\n sys.path.append('%s');\n\n",
1873 directory,
1874 directory);
1875 bool syspath_retval = python_interpreter->ExecuteMultipleLines(command_stream.GetData());
1876 if (!syspath_retval)
1877 {
1878 error.SetErrorString("Python sys.path handling failed");
1879 return false;
1880 }
1881
1882 // strip .py or .pyc extension
1883 ConstString extension = target_file.GetFileNameExtension();
1884 if (::strcmp(extension.GetCString(), "py") == 0)
1885 basename.resize(basename.length()-3);
1886 else if(::strcmp(extension.GetCString(), "pyc") == 0)
1887 basename.resize(basename.length()-4);
1888
1889 // check if the module is already import-ed
1890 command_stream.Clear();
1891 command_stream.Printf("sys.getrefcount(%s)",basename.c_str());
1892 int refcount = 0;
1893 // this call will fail if the module does not exist (because the parameter to it is not a string
1894 // but an actual Python module object, which is non-existant if the module was not imported before)
1895 if (python_interpreter->ExecuteOneLineWithReturn(command_stream.GetData(),
1896 ScriptInterpreterPython::eScriptReturnTypeInt, &refcount) && refcount > 0)
1897 {
1898 error.SetErrorString("module already imported");
1899 return false;
1900 }
1901
1902 // now actually do the import
1903 command_stream.Clear();
1904 command_stream.Printf("import %s",basename.c_str());
1905 bool import_retval = python_interpreter->ExecuteOneLine(command_stream.GetData(), NULL);
1906 if (!import_retval)
1907 {
1908 error.SetErrorString("Python import statement failed");
1909 return false;
1910 }
1911
1912 // call __lldb_module_init(debugger,dict)
1913 if (!g_swig_call_module_init (basename,
1914 python_interpreter->m_dictionary_name.c_str(),
1915 debugger_sp))
1916 {
1917 error.SetErrorString("calling __lldb_module_init failed");
1918 return false;
1919 }
1920 return true;
1921 }
1922}
1923
1924bool
Enrico Granatac2a28252011-08-16 16:49:25 +00001925ScriptInterpreterPython::RunScriptBasedCommand(const char* impl_function,
1926 const char* args,
Enrico Granata6b1596d2011-08-16 23:24:13 +00001927 lldb_private::CommandReturnObject& cmd_retobj,
Enrico Granatac2a28252011-08-16 16:49:25 +00001928 Error& error)
1929{
1930 if (!impl_function)
1931 {
1932 error.SetErrorString("no function to execute");
1933 return false;
1934 }
1935
1936 if (!g_swig_call_command)
1937 {
1938 error.SetErrorString("no helper function to run scripted commands");
1939 return false;
1940 }
1941
1942 ScriptInterpreterPython *python_interpreter = this;
Enrico Granata3370f0c2011-08-19 23:56:34 +00001943
Enrico Granatac2a28252011-08-16 16:49:25 +00001944 lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().GetSP();
1945
1946 bool ret_val;
1947
1948 std::string err_msg;
1949
1950 FILE *tmp_fh = (python_interpreter->m_dbg_stdout ? python_interpreter->m_dbg_stdout : stdout);
Enrico Granata91544802011-09-06 19:20:51 +00001951
Enrico Granatac2a28252011-08-16 16:49:25 +00001952 {
Enrico Granata91544802011-09-06 19:20:51 +00001953 Locker py_lock(python_interpreter, tmp_fh);
Enrico Granatac2a28252011-08-16 16:49:25 +00001954 ret_val = g_swig_call_command (impl_function,
1955 python_interpreter->m_dictionary_name.c_str(),
1956 debugger_sp,
1957 args,
1958 err_msg,
Enrico Granata3370f0c2011-08-19 23:56:34 +00001959 cmd_retobj);
Enrico Granatac2a28252011-08-16 16:49:25 +00001960 }
1961
1962 if (!ret_val)
1963 error.SetErrorString(err_msg.c_str());
1964 else
1965 error.Clear();
Enrico Granata3370f0c2011-08-19 23:56:34 +00001966
Enrico Granatac2a28252011-08-16 16:49:25 +00001967 return ret_val;
1968
1969
1970 return true;
1971
1972}
1973
Enrico Granatae5e34cb2011-08-17 01:30:04 +00001974// in Python, a special attribute __doc__ contains the docstring
1975// for an object (function, method, class, ...) if any is defined
1976// Otherwise, the attribute's value is None
1977std::string
1978ScriptInterpreterPython::GetDocumentationForItem(const char* item)
1979{
1980 std::string command(item);
1981 command += ".__doc__";
1982
1983 char* result_ptr = NULL; // Python is going to point this to valid data if ExecuteOneLineWithReturn returns successfully
1984
1985 if (ExecuteOneLineWithReturn (command.c_str(),
Enrico Granata59df36f2011-10-17 21:45:27 +00001986 ScriptInterpreter::eScriptReturnTypeCharStrOrNone,
Enrico Granatae5e34cb2011-08-17 01:30:04 +00001987 &result_ptr) && result_ptr)
1988 {
1989 return std::string(result_ptr);
1990 }
1991 else
1992 return std::string("");
1993}
Caroline Tice2ade6112010-11-10 19:18:14 +00001994
Caroline Tice0aa2e552011-01-14 00:29:16 +00001995void
Greg Claytone86cbb92011-03-22 01:14:58 +00001996ScriptInterpreterPython::InitializeInterpreter (SWIGInitCallback python_swig_init_callback,
Enrico Granataf7a9b142011-07-15 02:26:42 +00001997 SWIGBreakpointCallbackFunction python_swig_breakpoint_callback,
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001998 SWIGPythonTypeScriptCallbackFunction python_swig_typescript_callback,
1999 SWIGPythonCreateSyntheticProvider python_swig_synthetic_script,
2000 SWIGPythonCalculateNumChildren python_swig_calc_children,
2001 SWIGPythonGetChildAtIndex python_swig_get_child_index,
2002 SWIGPythonGetIndexOfChildWithName python_swig_get_index_child,
Enrico Granata979e20d2011-07-29 19:53:35 +00002003 SWIGPythonCastPyObjectToSBValue python_swig_cast_to_sbvalue,
Enrico Granatac2a28252011-08-16 16:49:25 +00002004 SWIGPythonUpdateSynthProviderInstance python_swig_update_provider,
Enrico Granata59df36f2011-10-17 21:45:27 +00002005 SWIGPythonCallCommand python_swig_call_command,
2006 SWIGPythonCallModuleInit python_swig_call_mod_init)
Greg Claytone86cbb92011-03-22 01:14:58 +00002007{
2008 g_swig_init_callback = python_swig_init_callback;
Enrico Granataf7a9b142011-07-15 02:26:42 +00002009 g_swig_breakpoint_callback = python_swig_breakpoint_callback;
2010 g_swig_typescript_callback = python_swig_typescript_callback;
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002011 g_swig_synthetic_script = python_swig_synthetic_script;
2012 g_swig_calc_children = python_swig_calc_children;
2013 g_swig_get_child_index = python_swig_get_child_index;
2014 g_swig_get_index_child = python_swig_get_index_child;
2015 g_swig_cast_to_sbvalue = python_swig_cast_to_sbvalue;
Enrico Granata979e20d2011-07-29 19:53:35 +00002016 g_swig_update_provider = python_swig_update_provider;
Enrico Granatac2a28252011-08-16 16:49:25 +00002017 g_swig_call_command = python_swig_call_command;
Enrico Granata59df36f2011-10-17 21:45:27 +00002018 g_swig_call_module_init = python_swig_call_mod_init;
Greg Claytone86cbb92011-03-22 01:14:58 +00002019}
2020
2021void
2022ScriptInterpreterPython::InitializePrivate ()
Caroline Tice0aa2e552011-01-14 00:29:16 +00002023{
Caroline Tice0aa2e552011-01-14 00:29:16 +00002024 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
2025
Greg Clayton0fdd4a02011-02-07 23:24:47 +00002026 // Python will muck with STDIN terminal state, so save off any current TTY
2027 // settings so we can restore them.
2028 TerminalState stdin_tty_state;
2029 stdin_tty_state.Save(STDIN_FILENO, false);
Caroline Tice0aa2e552011-01-14 00:29:16 +00002030
Caroline Tice9d352ce2011-03-07 23:24:28 +00002031 PyEval_InitThreads ();
Caroline Ticea54461d2011-06-02 22:09:43 +00002032 Py_InitializeEx (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00002033
Greg Claytone86cbb92011-03-22 01:14:58 +00002034 // Initialize SWIG after setting up python
2035 assert (g_swig_init_callback != NULL);
2036 g_swig_init_callback ();
Caroline Tice0aa2e552011-01-14 00:29:16 +00002037
2038 // Update the path python uses to search for modules to include the current directory.
2039
Caroline Ticed4d92832011-06-13 21:33:00 +00002040 PyRun_SimpleString ("import sys");
2041 PyRun_SimpleString ("sys.path.append ('.')");
Jim Ingham2a19ef92011-08-27 01:24:08 +00002042
2043 // Find the module that owns this code and use that path we get to
2044 // set the sys.path appropriately.
2045
2046 FileSpec file_spec;
2047 char python_dir_path[PATH_MAX];
2048 if (Host::GetLLDBPath (ePathTypePythonDir, file_spec))
2049 {
2050 std::string python_path("sys.path.insert(0,\"");
2051 size_t orig_len = python_path.length();
2052 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
2053 {
2054 python_path.append (python_dir_path);
2055 python_path.append ("\")");
2056 PyRun_SimpleString (python_path.c_str());
2057 python_path.resize (orig_len);
2058 }
2059
2060 if (Host::GetLLDBPath (ePathTypeLLDBShlibDir, file_spec))
2061 {
2062 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
2063 {
2064 python_path.append (python_dir_path);
2065 python_path.append ("\")");
2066 PyRun_SimpleString (python_path.c_str());
2067 python_path.resize (orig_len);
2068 }
2069 }
2070 }
2071
Jim Ingham4dfa5112011-08-22 19:10:09 +00002072 PyRun_SimpleString ("sys.dont_write_bytecode = 1");
Caroline Tice0aa2e552011-01-14 00:29:16 +00002073
Caroline Ticed4d92832011-06-13 21:33:00 +00002074 PyRun_SimpleString ("import embedded_interpreter");
Caroline Tice0aa2e552011-01-14 00:29:16 +00002075
Caroline Ticed4d92832011-06-13 21:33:00 +00002076 PyRun_SimpleString ("from embedded_interpreter import run_python_interpreter");
2077 PyRun_SimpleString ("from embedded_interpreter import run_one_line");
Caroline Ticed4d92832011-06-13 21:33:00 +00002078 PyRun_SimpleString ("from termios import *");
Greg Clayton99208582011-02-07 19:04:58 +00002079
Greg Clayton0fdd4a02011-02-07 23:24:47 +00002080 stdin_tty_state.Restore();
Caroline Tice0aa2e552011-01-14 00:29:16 +00002081}
2082
Greg Claytone86cbb92011-03-22 01:14:58 +00002083//void
2084//ScriptInterpreterPython::Terminate ()
2085//{
2086// // We are intentionally NOT calling Py_Finalize here (this would be the logical place to call it). Calling
2087// // Py_Finalize here causes test suite runs to seg fault: The test suite runs in Python. It registers
2088// // SBDebugger::Terminate to be called 'at_exit'. When the test suite Python harness finishes up, it calls
2089// // Py_Finalize, which calls all the 'at_exit' registered functions. SBDebugger::Terminate calls Debugger::Terminate,
2090// // which calls lldb::Terminate, which calls ScriptInterpreter::Terminate, which calls
2091// // ScriptInterpreterPython::Terminate. So if we call Py_Finalize here, we end up with Py_Finalize being called from
2092// // within Py_Finalize, which results in a seg fault.
2093// //
2094// // Since this function only gets called when lldb is shutting down and going away anyway, the fact that we don't
2095// // actually call Py_Finalize should not cause any problems (everything should shut down/go away anyway when the
2096// // process exits).
2097// //
2098//// Py_Finalize ();
2099//}