blob: a94f8709a41204dbacd59b0c7b876bd57c247034 [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.
Greg Clayton3e4238d2011-11-04 03:34:56 +000012#ifdef LLDB_DISABLE_PYTHON
13
14// Python is disabled in this build
15
16#else
Benjamin Kramerc28bbdb2011-10-23 16:49:03 +000017
18#if defined (__APPLE__)
19#include <Python/Python.h>
20#else
21#include <Python.h>
22#endif
Chris Lattner24943d22010-06-08 16:52:24 +000023
24#include "lldb/Interpreter/ScriptInterpreterPython.h"
25
Chris Lattner24943d22010-06-08 16:52:24 +000026#include <stdlib.h>
27#include <stdio.h>
28
29#include <string>
30
Enrico Granata91544802011-09-06 19:20:51 +000031#include "lldb/API/SBValue.h"
Greg Clayton987c7eb2011-09-17 08:33:22 +000032#include "lldb/Breakpoint/BreakpointLocation.h"
Greg Clayton63094e02010-06-23 01:19:29 +000033#include "lldb/Breakpoint/StoppointCallbackContext.h"
Johnny Chenf3ec4612012-08-09 23:09:42 +000034#include "lldb/Breakpoint/WatchpointOptions.h"
Chris Lattner24943d22010-06-08 16:52:24 +000035#include "lldb/Core/Debugger.h"
Chris Lattner24943d22010-06-08 16:52:24 +000036#include "lldb/Core/Timer.h"
37#include "lldb/Host/Host.h"
38#include "lldb/Interpreter/CommandInterpreter.h"
39#include "lldb/Interpreter/CommandReturnObject.h"
Greg Clayton5144f382010-10-07 17:14:24 +000040#include "lldb/Target/Thread.h"
Chris Lattner24943d22010-06-08 16:52:24 +000041
Chris Lattner24943d22010-06-08 16:52:24 +000042using namespace lldb;
43using namespace lldb_private;
44
Greg Claytone86cbb92011-03-22 01:14:58 +000045
46static ScriptInterpreter::SWIGInitCallback g_swig_init_callback = NULL;
47static ScriptInterpreter::SWIGBreakpointCallbackFunction g_swig_breakpoint_callback = NULL;
Johnny Chenf3ec4612012-08-09 23:09:42 +000048static ScriptInterpreter::SWIGWatchpointCallbackFunction g_swig_watchpoint_callback = NULL;
Enrico Granataf7a9b142011-07-15 02:26:42 +000049static ScriptInterpreter::SWIGPythonTypeScriptCallbackFunction g_swig_typescript_callback = NULL;
Enrico Granata9ae7cef2011-07-24 00:14:56 +000050static ScriptInterpreter::SWIGPythonCreateSyntheticProvider g_swig_synthetic_script = NULL;
51static ScriptInterpreter::SWIGPythonCalculateNumChildren g_swig_calc_children = NULL;
52static ScriptInterpreter::SWIGPythonGetChildAtIndex g_swig_get_child_index = NULL;
53static ScriptInterpreter::SWIGPythonGetIndexOfChildWithName g_swig_get_index_child = NULL;
54static ScriptInterpreter::SWIGPythonCastPyObjectToSBValue g_swig_cast_to_sbvalue = NULL;
Enrico Granata979e20d2011-07-29 19:53:35 +000055static ScriptInterpreter::SWIGPythonUpdateSynthProviderInstance g_swig_update_provider = NULL;
Enrico Granata800332c2012-10-23 19:54:09 +000056static ScriptInterpreter::SWIGPythonMightHaveChildrenSynthProviderInstance g_swig_mighthavechildren_provider = NULL;
Enrico Granatac2a28252011-08-16 16:49:25 +000057static ScriptInterpreter::SWIGPythonCallCommand g_swig_call_command = NULL;
Enrico Granata59df36f2011-10-17 21:45:27 +000058static ScriptInterpreter::SWIGPythonCallModuleInit g_swig_call_module_init = NULL;
Enrico Granata155ee912012-08-24 00:30:47 +000059static ScriptInterpreter::SWIGPythonCreateOSPlugin g_swig_create_os_plugin = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +000060
Enrico Granata1328b142012-02-29 03:28:49 +000061// these are the Pythonic implementations of the required callbacks
62// these are scripting-language specific, which is why they belong here
63// we still need to use function pointers to them instead of relying
64// on linkage-time resolution because the SWIG stuff and this file
65// get built at different times
66extern "C" bool
67LLDBSwigPythonBreakpointCallbackFunction
68(
69 const char *python_function_name,
70 const char *session_dictionary_name,
71 const lldb::StackFrameSP& sb_frame,
72 const lldb::BreakpointLocationSP& sb_bp_loc
73 );
74
75extern "C" bool
Johnny Chenf3ec4612012-08-09 23:09:42 +000076LLDBSwigPythonWatchpointCallbackFunction
77(
78 const char *python_function_name,
79 const char *session_dictionary_name,
80 const lldb::StackFrameSP& sb_frame,
81 const lldb::WatchpointSP& sb_wp
82 );
83
84extern "C" bool
Enrico Granata1328b142012-02-29 03:28:49 +000085LLDBSwigPythonCallTypeScript
86(
87 const char *python_function_name,
88 void *session_dictionary,
89 const lldb::ValueObjectSP& valobj_sp,
90 void** pyfunct_wrapper,
91 std::string& retval
92 );
93
94extern "C" void*
95LLDBSwigPythonCreateSyntheticProvider
96(
97 const std::string python_class_name,
98 const char *session_dictionary_name,
99 const lldb::ValueObjectSP& valobj_sp
100 );
101
102
Enrico Granata800332c2012-10-23 19:54:09 +0000103extern "C" uint32_t LLDBSwigPython_CalculateNumChildren (void *implementor);
104extern "C" void* LLDBSwigPython_GetChildAtIndex (void *implementor, uint32_t idx);
105extern "C" int LLDBSwigPython_GetIndexOfChildWithName (void *implementor, const char* child_name);
106extern "C" void* LLDBSWIGPython_CastPyObjectToSBValue (void* data);
107extern "C" bool LLDBSwigPython_UpdateSynthProviderInstance (void* implementor);
108extern "C" bool LLDBSwigPython_MightHaveChildrenSynthProviderInstance (void* implementor);
Enrico Granata1328b142012-02-29 03:28:49 +0000109
110extern "C" bool LLDBSwigPythonCallCommand
111(
112 const char *python_function_name,
113 const char *session_dictionary_name,
114 lldb::DebuggerSP& debugger,
115 const char* args,
116 std::string& err_msg,
117 lldb_private::CommandReturnObject& cmd_retobj
118 );
119
120extern "C" bool LLDBSwigPythonCallModuleInit
121(
122 const std::string python_module_name,
123 const char *session_dictionary_name,
124 lldb::DebuggerSP& debugger
125 );
126
Enrico Granata155ee912012-08-24 00:30:47 +0000127extern "C" void* LLDBSWIGPythonCreateOSPlugin
128(
129 const std::string python_class_name,
130 const char *session_dictionary_name,
131 const lldb::ProcessSP& process_sp
132);
133
Chris Lattner24943d22010-06-08 16:52:24 +0000134static int
135_check_and_flush (FILE *stream)
136{
137 int prev_fail = ferror (stream);
138 return fflush (stream) || prev_fail ? EOF : 0;
139}
140
Enrico Granatafa1f6172011-10-24 17:22:21 +0000141ScriptInterpreterPython::Locker::Locker (ScriptInterpreterPython *py_interpreter,
142 uint16_t on_entry,
143 uint16_t on_leave,
144 FILE* wait_msg_handle) :
145 m_need_session( (on_leave & TearDownSession) == TearDownSession ),
Enrico Granatafa1f6172011-10-24 17:22:21 +0000146 m_python_interpreter(py_interpreter),
147 m_tmp_fh(wait_msg_handle)
Enrico Granata91544802011-09-06 19:20:51 +0000148{
Enrico Granatafa1f6172011-10-24 17:22:21 +0000149 if (m_python_interpreter && !m_tmp_fh)
150 m_tmp_fh = (m_python_interpreter->m_dbg_stdout ? m_python_interpreter->m_dbg_stdout : stdout);
Johnny Chen8165d432012-08-18 04:14:54 +0000151
152 DoAcquireLock();
Jim Ingham14e71ec2012-12-07 17:43:38 +0000153 if ((on_entry & InitSession) == InitSession)
154 DoInitSession((on_entry & InitGlobals) == InitGlobals);
Enrico Granatafa1f6172011-10-24 17:22:21 +0000155}
156
157bool
158ScriptInterpreterPython::Locker::DoAcquireLock()
159{
Johnny Chen8165d432012-08-18 04:14:54 +0000160 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT | LIBLLDB_LOG_VERBOSE));
161 m_GILState = PyGILState_Ensure();
162 if (log)
163 log->Printf("Ensured PyGILState. Previous state = %slocked\n", m_GILState == PyGILState_UNLOCKED ? "un" : "");
Enrico Granatafa1f6172011-10-24 17:22:21 +0000164 return true;
165}
166
167bool
Jim Ingham14e71ec2012-12-07 17:43:38 +0000168ScriptInterpreterPython::Locker::DoInitSession(bool init_lldb_globals)
Enrico Granatafa1f6172011-10-24 17:22:21 +0000169{
170 if (!m_python_interpreter)
171 return false;
Jim Ingham14e71ec2012-12-07 17:43:38 +0000172 m_python_interpreter->EnterSession (init_lldb_globals);
Enrico Granatafa1f6172011-10-24 17:22:21 +0000173 return true;
174}
175
176bool
177ScriptInterpreterPython::Locker::DoFreeLock()
178{
Johnny Chen8165d432012-08-18 04:14:54 +0000179 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT | LIBLLDB_LOG_VERBOSE));
180 if (log)
181 log->Printf("Releasing PyGILState. Returning to state = %slocked\n", m_GILState == PyGILState_UNLOCKED ? "un" : "");
182 PyGILState_Release(m_GILState);
Enrico Granatafa1f6172011-10-24 17:22:21 +0000183 return true;
184}
185
186bool
187ScriptInterpreterPython::Locker::DoTearDownSession()
188{
189 if (!m_python_interpreter)
190 return false;
191 m_python_interpreter->LeaveSession ();
192 return true;
Enrico Granata91544802011-09-06 19:20:51 +0000193}
194
195ScriptInterpreterPython::Locker::~Locker()
196{
197 if (m_need_session)
Enrico Granatafa1f6172011-10-24 17:22:21 +0000198 DoTearDownSession();
Johnny Chen8165d432012-08-18 04:14:54 +0000199 DoFreeLock();
Enrico Granata91544802011-09-06 19:20:51 +0000200}
201
Enrico Granataa1ba3142012-06-07 00:17:18 +0000202ScriptInterpreterPython::PythonInputReaderManager::PythonInputReaderManager (ScriptInterpreterPython *interpreter) :
203m_interpreter(interpreter),
204m_debugger_sp(),
205m_reader_sp(),
206m_error(false)
207{
208 if (m_interpreter == NULL)
209 {
210 m_error = true;
211 return;
212 }
213
214 m_debugger_sp = m_interpreter->GetCommandInterpreter().GetDebugger().shared_from_this();
215
216 if (!m_debugger_sp)
217 {
218 m_error = true;
219 return;
220 }
221
222 m_reader_sp = InputReaderSP(new InputReader(*m_debugger_sp.get()));
223
224 if (!m_reader_sp)
225 {
226 m_error = true;
227 return;
228 }
229
230 Error error (m_reader_sp->Initialize (ScriptInterpreterPython::PythonInputReaderManager::InputReaderCallback,
231 m_interpreter, // baton
232 eInputReaderGranularityLine, // token size, to pass to callback function
233 NULL, // end token
234 NULL, // prompt
235 true)); // echo input
236 if (error.Fail())
237 m_error = true;
238 else
239 {
240 m_debugger_sp->PushInputReader (m_reader_sp);
241 m_interpreter->m_embedded_thread_input_reader_sp = m_reader_sp;
242 }
243}
244
245ScriptInterpreterPython::PythonInputReaderManager::~PythonInputReaderManager()
246{
Johnny Chen8121d7a2012-08-17 23:44:35 +0000247 // Nothing to do if either m_interpreter or m_reader_sp is invalid.
248 if (!m_interpreter || !m_reader_sp)
249 return;
250
251 m_reader_sp->SetIsDone (true);
252 if (m_debugger_sp)
253 m_debugger_sp->PopInputReader(m_reader_sp);
254
255 // Only mess with m_interpreter's counterpart if, indeed, they are the same object.
256 if (m_reader_sp.get() == m_interpreter->m_embedded_thread_input_reader_sp.get())
Enrico Granataa1ba3142012-06-07 00:17:18 +0000257 {
Johnny Chen8121d7a2012-08-17 23:44:35 +0000258 m_interpreter->m_embedded_thread_pty.CloseSlaveFileDescriptor();
Enrico Granataa1ba3142012-06-07 00:17:18 +0000259 m_interpreter->m_embedded_thread_input_reader_sp.reset();
Johnny Chen8121d7a2012-08-17 23:44:35 +0000260 }
Enrico Granataa1ba3142012-06-07 00:17:18 +0000261}
262
263size_t
264ScriptInterpreterPython::PythonInputReaderManager::InputReaderCallback
265(
266 void *baton,
267 InputReader &reader,
268 InputReaderAction notification,
269 const char *bytes,
270 size_t bytes_len
271 )
272{
273 lldb::thread_t embedded_interpreter_thread;
274 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
275
276 if (baton == NULL)
277 return 0;
278
279 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
280
281 if (script_interpreter->m_script_lang != eScriptLanguagePython)
282 return 0;
283
284 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
285
286 switch (notification)
287 {
288 case eInputReaderActivate:
289 {
290 // Save terminal settings if we can
291 int input_fd = reader.GetDebugger().GetInputFile().GetDescriptor();
292 if (input_fd == File::kInvalidDescriptor)
293 input_fd = STDIN_FILENO;
294
295 script_interpreter->SaveTerminalState(input_fd);
Johnny Chen8165d432012-08-18 04:14:54 +0000296
Enrico Granataa1ba3142012-06-07 00:17:18 +0000297 char error_str[1024];
Johnny Chen8121d7a2012-08-17 23:44:35 +0000298 if (script_interpreter->m_embedded_thread_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, error_str,
Enrico Granataa1ba3142012-06-07 00:17:18 +0000299 sizeof(error_str)))
300 {
301 if (log)
302 log->Printf ("ScriptInterpreterPython::NonInteractiveInputReaderCallback, Activate, succeeded in opening master pty (fd = %d).",
Johnny Chen8121d7a2012-08-17 23:44:35 +0000303 script_interpreter->m_embedded_thread_pty.GetMasterFileDescriptor());
Enrico Granataa1ba3142012-06-07 00:17:18 +0000304 {
305 StreamString run_string;
306 char error_str[1024];
Johnny Chen8121d7a2012-08-17 23:44:35 +0000307 const char *pty_slave_name = script_interpreter->m_embedded_thread_pty.GetSlaveName (error_str, sizeof (error_str));
Enrico Granataca2c7072012-07-31 16:58:12 +0000308 if (pty_slave_name != NULL && PyThreadState_GetDict() != NULL)
Enrico Granataa1ba3142012-06-07 00:17:18 +0000309 {
Johnny Chen8165d432012-08-18 04:14:54 +0000310 ScriptInterpreterPython::Locker locker(script_interpreter,
Jim Ingham14e71ec2012-12-07 17:43:38 +0000311 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession | ScriptInterpreterPython::Locker::InitGlobals,
Johnny Chen8165d432012-08-18 04:14:54 +0000312 ScriptInterpreterPython::Locker::FreeAcquiredLock);
Enrico Granataa1ba3142012-06-07 00:17:18 +0000313 run_string.Printf ("run_one_line (%s, 'save_stderr = sys.stderr')", script_interpreter->m_dictionary_name.c_str());
314 PyRun_SimpleString (run_string.GetData());
315 run_string.Clear ();
316
317 run_string.Printf ("run_one_line (%s, 'sys.stderr = sys.stdout')", script_interpreter->m_dictionary_name.c_str());
318 PyRun_SimpleString (run_string.GetData());
319 run_string.Clear ();
320
321 run_string.Printf ("run_one_line (%s, 'save_stdin = sys.stdin')", script_interpreter->m_dictionary_name.c_str());
322 PyRun_SimpleString (run_string.GetData());
323 run_string.Clear ();
324
325 run_string.Printf ("run_one_line (%s, \"sys.stdin = open ('%s', 'r')\")", script_interpreter->m_dictionary_name.c_str(),
326 pty_slave_name);
327 PyRun_SimpleString (run_string.GetData());
328 run_string.Clear ();
329 }
330 }
331 embedded_interpreter_thread = Host::ThreadCreate ("<lldb.script-interpreter.noninteractive-python>",
332 ScriptInterpreterPython::PythonInputReaderManager::RunPythonInputReader,
333 script_interpreter, NULL);
334 if (IS_VALID_LLDB_HOST_THREAD(embedded_interpreter_thread))
335 {
336 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +0000337 log->Printf ("ScriptInterpreterPython::NonInteractiveInputReaderCallback, Activate, succeeded in creating thread (thread_t = %p)", (void *)embedded_interpreter_thread);
Enrico Granataa1ba3142012-06-07 00:17:18 +0000338 Error detach_error;
339 Host::ThreadDetach (embedded_interpreter_thread, &detach_error);
340 }
341 else
342 {
343 if (log)
344 log->Printf ("ScriptInterpreterPython::NonInteractiveInputReaderCallback, Activate, failed in creating thread");
345 reader.SetIsDone (true);
346 }
347 }
348 else
349 {
350 if (log)
351 log->Printf ("ScriptInterpreterPython::NonInteractiveInputReaderCallback, Activate, failed to open master pty ");
352 reader.SetIsDone (true);
353 }
354 }
355 break;
356
357 case eInputReaderDeactivate:
358 // When another input reader is pushed, don't leave the session...
359 //script_interpreter->LeaveSession ();
360 break;
361
362 case eInputReaderReactivate:
Greg Clayton3b1afc62012-09-01 00:38:36 +0000363// {
364// ScriptInterpreterPython::Locker locker(script_interpreter,
365// ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
366// ScriptInterpreterPython::Locker::FreeAcquiredLock);
367// }
Enrico Granataa1ba3142012-06-07 00:17:18 +0000368 break;
369
370 case eInputReaderAsynchronousOutputWritten:
371 break;
372
373 case eInputReaderInterrupt:
374 reader.SetIsDone(true);
375 break;
376
377 case eInputReaderEndOfFile:
378 reader.SetIsDone(true);
379 break;
380
381 case eInputReaderGotToken:
Johnny Chen8121d7a2012-08-17 23:44:35 +0000382 if (script_interpreter->m_embedded_thread_pty.GetMasterFileDescriptor() != -1)
Enrico Granataa1ba3142012-06-07 00:17:18 +0000383 {
384 if (log)
385 log->Printf ("ScriptInterpreterPython::NonInteractiveInputReaderCallback, GotToken, bytes='%s', byte_len = %lu", bytes,
386 bytes_len);
387 if (bytes && bytes_len)
Johnny Chen8121d7a2012-08-17 23:44:35 +0000388 ::write (script_interpreter->m_embedded_thread_pty.GetMasterFileDescriptor(), bytes, bytes_len);
389 ::write (script_interpreter->m_embedded_thread_pty.GetMasterFileDescriptor(), "\n", 1);
Enrico Granataa1ba3142012-06-07 00:17:18 +0000390 }
391 else
392 {
393 if (log)
394 log->Printf ("ScriptInterpreterPython::NonInteractiveInputReaderCallback, GotToken, bytes='%s', byte_len = %lu, Master File Descriptor is bad.",
395 bytes,
396 bytes_len);
397 reader.SetIsDone (true);
398 }
399
400 break;
401
402 case eInputReaderDone:
403 {
404 StreamString run_string;
405 char error_str[1024];
Johnny Chen8121d7a2012-08-17 23:44:35 +0000406 const char *pty_slave_name = script_interpreter->m_embedded_thread_pty.GetSlaveName (error_str, sizeof (error_str));
Enrico Granataca2c7072012-07-31 16:58:12 +0000407 if (pty_slave_name != NULL && PyThreadState_GetDict() != NULL)
Enrico Granataa1ba3142012-06-07 00:17:18 +0000408 {
Johnny Chen8165d432012-08-18 04:14:54 +0000409 ScriptInterpreterPython::Locker locker(script_interpreter,
410 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
411 ScriptInterpreterPython::Locker::FreeAcquiredLock);
Enrico Granataa1ba3142012-06-07 00:17:18 +0000412 run_string.Printf ("run_one_line (%s, 'sys.stdin = save_stdin')", script_interpreter->m_dictionary_name.c_str());
413 PyRun_SimpleString (run_string.GetData());
414 run_string.Clear();
415
416 run_string.Printf ("run_one_line (%s, 'sys.stderr = save_stderr')", script_interpreter->m_dictionary_name.c_str());
417 PyRun_SimpleString (run_string.GetData());
418 run_string.Clear();
419 }
420 }
421
422 // Restore terminal settings if they were validly saved
423 if (log)
424 log->Printf ("ScriptInterpreterPython::NonInteractiveInputReaderCallback, Done, closing down input reader.");
425
426 script_interpreter->RestoreTerminalState ();
427
Johnny Chen8121d7a2012-08-17 23:44:35 +0000428 script_interpreter->m_embedded_thread_pty.CloseMasterFileDescriptor();
Enrico Granataa1ba3142012-06-07 00:17:18 +0000429 break;
430 }
431
432 return bytes_len;
433}
434
Greg Clayton63094e02010-06-23 01:19:29 +0000435ScriptInterpreterPython::ScriptInterpreterPython (CommandInterpreter &interpreter) :
Greg Clayton238c0a12010-09-18 01:14:36 +0000436 ScriptInterpreter (interpreter, eScriptLanguagePython),
Johnny Chen8121d7a2012-08-17 23:44:35 +0000437 m_embedded_thread_pty (),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000438 m_embedded_python_pty (),
439 m_embedded_thread_input_reader_sp (),
Johnny Chen8121d7a2012-08-17 23:44:35 +0000440 m_embedded_python_input_reader_sp (),
Greg Clayton58928562011-02-09 01:08:52 +0000441 m_dbg_stdout (interpreter.GetDebugger().GetOutputFile().GetStream()),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000442 m_new_sysout (NULL),
Johnny Chenc65046d2012-03-08 20:53:04 +0000443 m_old_sysout (NULL),
444 m_old_syserr (NULL),
Enrico Granata400105d2012-03-06 23:42:15 +0000445 m_run_one_line (NULL),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000446 m_dictionary_name (interpreter.GetDebugger().GetInstanceName().AsCString()),
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000447 m_terminal_state (),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000448 m_session_is_active (false),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000449 m_valid_session (true)
Chris Lattner24943d22010-06-08 16:52:24 +0000450{
451
Greg Clayton7c330d62011-01-27 01:01:10 +0000452 static int g_initialized = false;
453
454 if (!g_initialized)
455 {
456 g_initialized = true;
Greg Claytone86cbb92011-03-22 01:14:58 +0000457 ScriptInterpreterPython::InitializePrivate ();
Greg Clayton7c330d62011-01-27 01:01:10 +0000458 }
459
Caroline Tice0aa2e552011-01-14 00:29:16 +0000460 m_dictionary_name.append("_dict");
461 StreamString run_string;
462 run_string.Printf ("%s = dict()", m_dictionary_name.c_str());
Johnny Chen8165d432012-08-18 04:14:54 +0000463
464 Locker locker(this,
465 ScriptInterpreterPython::Locker::AcquireLock,
466 ScriptInterpreterPython::Locker::FreeAcquiredLock);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000467 PyRun_SimpleString (run_string.GetData());
Caroline Tice5867f6b2010-10-18 18:24:17 +0000468
Caroline Tice0aa2e552011-01-14 00:29:16 +0000469 run_string.Clear();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000470
471 // Importing 'lldb' module calls SBDebugger::Initialize, which calls Debugger::Initialize, which increments a
472 // global debugger ref-count; therefore we need to check the ref-count before and after importing lldb, and if the
473 // ref-count increased we need to call Debugger::Terminate here to decrement the ref-count so that when the final
474 // call to Debugger::Terminate is made, the ref-count has the correct value.
475 //
476 // Bonus question: Why doesn't the ref-count always increase? Because sometimes lldb has already been imported, in
477 // which case the code inside it, including the call to SBDebugger::Initialize(), does not get executed.
Caroline Tice5867f6b2010-10-18 18:24:17 +0000478
Caroline Tice0aa2e552011-01-14 00:29:16 +0000479 int old_count = Debugger::TestDebuggerRefCount();
Greg Claytonb302dff2012-02-01 08:09:32 +0000480
Greg Clayton4e651b12012-04-25 00:58:03 +0000481 run_string.Printf ("run_one_line (%s, 'import copy, os, re, sys, uuid, lldb')", m_dictionary_name.c_str());
Caroline Tice0aa2e552011-01-14 00:29:16 +0000482 PyRun_SimpleString (run_string.GetData());
Greg Clayton24b48ff2010-10-17 22:03:32 +0000483
Enrico Granata8f84cfb2012-02-23 23:10:03 +0000484 // WARNING: temporary code that loads Cocoa formatters - this should be done on a per-platform basis rather than loading the whole set
485 // and letting the individual formatter classes exploit APIs to check whether they can/cannot do their task
486 run_string.Clear();
Enrico Granata14cf90e2012-10-22 19:09:28 +0000487 run_string.Printf ("run_one_line (%s, 'import lldb.runtime.objc, lldb.formatters, lldb.formatters.objc, lldb.formatters.cpp, pydoc')", m_dictionary_name.c_str());
Enrico Granata8f84cfb2012-02-23 23:10:03 +0000488 PyRun_SimpleString (run_string.GetData());
Greg Claytonb302dff2012-02-01 08:09:32 +0000489
Caroline Tice0aa2e552011-01-14 00:29:16 +0000490 int new_count = Debugger::TestDebuggerRefCount();
Chris Lattner24943d22010-06-08 16:52:24 +0000491
Caroline Tice0aa2e552011-01-14 00:29:16 +0000492 if (new_count > old_count)
493 Debugger::Terminate();
Caroline Tice5867f6b2010-10-18 18:24:17 +0000494
Caroline Tice0aa2e552011-01-14 00:29:16 +0000495 run_string.Clear();
Daniel Malea5f35a4b2012-11-29 21:49:15 +0000496 run_string.Printf ("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64 "; pydoc.pager = pydoc.plainpager')", m_dictionary_name.c_str(),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000497 interpreter.GetDebugger().GetID());
498 PyRun_SimpleString (run_string.GetData());
499
500 if (m_dbg_stdout != NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000501 {
Caroline Tice0aa2e552011-01-14 00:29:16 +0000502 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
Caroline Tice5867f6b2010-10-18 18:24:17 +0000503 }
Enrico Granatadb054912012-10-29 21:18:03 +0000504
505 // get the output file handle from the debugger (if any)
506 File& out_file = interpreter.GetDebugger().GetOutputFile();
507 if (out_file.IsValid())
508 ResetOutputFileHandle(out_file.GetStream());
Chris Lattner24943d22010-06-08 16:52:24 +0000509}
510
511ScriptInterpreterPython::~ScriptInterpreterPython ()
512{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000513 Debugger &debugger = GetCommandInterpreter().GetDebugger();
514
515 if (m_embedded_thread_input_reader_sp.get() != NULL)
516 {
517 m_embedded_thread_input_reader_sp->SetIsDone (true);
Johnny Chen8121d7a2012-08-17 23:44:35 +0000518 m_embedded_thread_pty.CloseSlaveFileDescriptor();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000519 const InputReaderSP reader_sp = m_embedded_thread_input_reader_sp;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000520 debugger.PopInputReader (reader_sp);
Johnny Chen8121d7a2012-08-17 23:44:35 +0000521 m_embedded_thread_input_reader_sp.reset();
522 }
523
524 if (m_embedded_python_input_reader_sp.get() != NULL)
525 {
526 m_embedded_python_input_reader_sp->SetIsDone (true);
527 m_embedded_python_pty.CloseSlaveFileDescriptor();
528 const InputReaderSP reader_sp = m_embedded_python_input_reader_sp;
529 debugger.PopInputReader (reader_sp);
530 m_embedded_python_input_reader_sp.reset();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000531 }
532
533 if (m_new_sysout)
534 {
Enrico Granatafa1f6172011-10-24 17:22:21 +0000535 Locker locker(this,
536 ScriptInterpreterPython::Locker::AcquireLock,
537 ScriptInterpreterPython::Locker::FreeLock);
538 Py_DECREF ((PyObject*)m_new_sysout);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000539 }
Chris Lattner24943d22010-06-08 16:52:24 +0000540}
541
Caroline Tice0aa2e552011-01-14 00:29:16 +0000542void
543ScriptInterpreterPython::ResetOutputFileHandle (FILE *fh)
544{
545 if (fh == NULL)
546 return;
547
548 m_dbg_stdout = fh;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000549
Johnny Chenc65046d2012-03-08 20:53:04 +0000550 Locker locker(this,
551 ScriptInterpreterPython::Locker::AcquireLock,
552 ScriptInterpreterPython::Locker::FreeAcquiredLock);
553
Enrico Granata91544802011-09-06 19:20:51 +0000554 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000555}
556
557void
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000558ScriptInterpreterPython::SaveTerminalState (int fd)
559{
560 // Python mucks with the terminal state of STDIN. If we can possibly avoid
561 // this by setting the file handles up correctly prior to entering the
562 // interpreter we should. For now we save and restore the terminal state
563 // on the input file handle.
564 m_terminal_state.Save (fd, false);
565}
566
567void
568ScriptInterpreterPython::RestoreTerminalState ()
569{
570 // Python mucks with the terminal state of STDIN. If we can possibly avoid
571 // this by setting the file handles up correctly prior to entering the
572 // interpreter we should. For now we save and restore the terminal state
573 // on the input file handle.
574 m_terminal_state.Restore();
575}
576
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000577void
Caroline Tice0aa2e552011-01-14 00:29:16 +0000578ScriptInterpreterPython::LeaveSession ()
579{
Enrico Granata7aa754c2012-04-04 17:31:29 +0000580 // checking that we have a valid thread state - since we use our own threading and locking
581 // in some (rare) cases during cleanup Python may end up believing we have no thread state
582 // and PyImport_AddModule will crash if that is the case - since that seems to only happen
583 // when destroying the SBDebugger, we can make do without clearing up stdout and stderr
Johnny Chen2b536952012-05-04 20:37:11 +0000584
585 // rdar://problem/11292882
586 // When the current thread state is NULL, PyThreadState_Get() issues a fatal error.
587 if (PyThreadState_GetDict())
Johnny Chen41641f92012-02-29 01:52:13 +0000588 {
Enrico Granata7aa754c2012-04-04 17:31:29 +0000589 PyObject *sysmod = PyImport_AddModule ("sys");
590 PyObject *sysdict = PyModule_GetDict (sysmod);
591
592 if (m_new_sysout && sysmod && sysdict)
593 {
594 if (m_old_sysout)
595 PyDict_SetItemString (sysdict, "stdout", (PyObject*)m_old_sysout);
596 if (m_old_syserr)
597 PyDict_SetItemString (sysdict, "stderr", (PyObject*)m_old_syserr);
598 }
Johnny Chen41641f92012-02-29 01:52:13 +0000599 }
600
Caroline Tice0aa2e552011-01-14 00:29:16 +0000601 m_session_is_active = false;
602}
603
604void
Jim Ingham14e71ec2012-12-07 17:43:38 +0000605ScriptInterpreterPython::EnterSession (bool init_lldb_globals)
Caroline Tice0aa2e552011-01-14 00:29:16 +0000606{
607 // If we have already entered the session, without having officially 'left' it, then there is no need to
608 // 'enter' it again.
609
610 if (m_session_is_active)
611 return;
612
613 m_session_is_active = true;
614
Caroline Tice202f6b82011-01-17 21:55:19 +0000615 StreamString run_string;
616
Jim Ingham14e71ec2012-12-07 17:43:38 +0000617 if (init_lldb_globals)
618 {
619 run_string.Printf ( "run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64, m_dictionary_name.c_str(), GetCommandInterpreter().GetDebugger().GetID());
620 run_string.Printf ( "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64 ")", GetCommandInterpreter().GetDebugger().GetID());
621 run_string.PutCString ("; lldb.target = lldb.debugger.GetSelectedTarget()");
622 run_string.PutCString ("; lldb.process = lldb.target.GetProcess()");
623 run_string.PutCString ("; lldb.thread = lldb.process.GetSelectedThread ()");
624 run_string.PutCString ("; lldb.frame = lldb.thread.GetSelectedFrame ()");
625 run_string.PutCString ("')");
626 }
Jim Ingham1dba0772012-12-08 02:02:04 +0000627 else
628 {
629 // If we aren't initing the globals, we should still always set the debugger (since that is always unique.)
630 run_string.Printf ( "run_one_line (%s, \"lldb.debugger_unique_id = %" PRIu64, m_dictionary_name.c_str(), GetCommandInterpreter().GetDebugger().GetID());
631 run_string.Printf ( "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64 ")", GetCommandInterpreter().GetDebugger().GetID());
632 run_string.PutCString ("\")");
633 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000634
Caroline Tice6af65cb2011-05-03 21:21:50 +0000635 PyRun_SimpleString (run_string.GetData());
636 run_string.Clear();
Johnny Chen41641f92012-02-29 01:52:13 +0000637
Caroline Tice0aa2e552011-01-14 00:29:16 +0000638 PyObject *sysmod = PyImport_AddModule ("sys");
639 PyObject *sysdict = PyModule_GetDict (sysmod);
Johnny Chen41641f92012-02-29 01:52:13 +0000640
Greg Clayton2fecc452012-01-28 02:11:02 +0000641 if (m_new_sysout && sysmod && sysdict)
642 {
Johnny Chen41641f92012-02-29 01:52:13 +0000643 m_old_sysout = PyDict_GetItemString(sysdict, "stdout");
644 m_old_syserr = PyDict_GetItemString(sysdict, "stderr");
Johnny Chenc65046d2012-03-08 20:53:04 +0000645 if (m_new_sysout)
646 {
647 PyDict_SetItemString (sysdict, "stdout", (PyObject*)m_new_sysout);
648 PyDict_SetItemString (sysdict, "stderr", (PyObject*)m_new_sysout);
649 }
Greg Clayton2fecc452012-01-28 02:11:02 +0000650 }
Johnny Chen41641f92012-02-29 01:52:13 +0000651
Caroline Tice0aa2e552011-01-14 00:29:16 +0000652 if (PyErr_Occurred())
653 PyErr_Clear ();
Greg Clayton2fecc452012-01-28 02:11:02 +0000654}
Caroline Tice0aa2e552011-01-14 00:29:16 +0000655
Enrico Granata400105d2012-03-06 23:42:15 +0000656static PyObject*
657FindSessionDictionary (const char* dict_name)
658{
659 static std::map<ConstString,PyObject*> g_dict_map;
660
661 ConstString dict(dict_name);
662
663 std::map<ConstString,PyObject*>::iterator iter = g_dict_map.find(dict);
664
665 if (iter != g_dict_map.end())
666 return iter->second;
667
668 PyObject *main_mod = PyImport_AddModule ("__main__");
669 if (main_mod != NULL)
670 {
671 PyObject *main_dict = PyModule_GetDict (main_mod);
672 if ((main_dict != NULL)
673 && PyDict_Check (main_dict))
674 {
675 // Go through the main dictionary looking for the correct python script interpreter dictionary
676 PyObject *key, *value;
677 Py_ssize_t pos = 0;
678
679 while (PyDict_Next (main_dict, &pos, &key, &value))
680 {
681 // We have stolen references to the key and value objects in the dictionary; we need to increment
682 // them now so that Python's garbage collector doesn't collect them out from under us.
683 Py_INCREF (key);
684 Py_INCREF (value);
685 if (strcmp (PyString_AsString (key), dict_name) == 0)
686 {
687 g_dict_map[dict] = value;
688 return value;
689 }
690 }
691 }
692 }
693 return NULL;
694}
695
696static std::string
697GenerateUniqueName (const char* base_name_wanted,
698 uint32_t& functions_counter,
699 void* name_token = NULL)
700{
701 StreamString sstr;
702
703 if (!base_name_wanted)
704 return std::string();
705
706 if (!name_token)
707 sstr.Printf ("%s_%d", base_name_wanted, functions_counter++);
708 else
709 sstr.Printf ("%s_%p", base_name_wanted, name_token);
710
711 return sstr.GetString();
712}
713
Johnny Chen60dde642010-07-30 22:33:14 +0000714bool
Enrico Granatafd670c22012-10-31 00:01:26 +0000715ScriptInterpreterPython::ExecuteOneLine (const char *command, CommandReturnObject *result, const ExecuteScriptOptions &options)
Chris Lattner24943d22010-06-08 16:52:24 +0000716{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000717 if (!m_valid_session)
718 return false;
719
Caroline Tice4a461da2011-01-14 21:09:29 +0000720 // We want to call run_one_line, passing in the dictionary and the command string. We cannot do this through
721 // PyRun_SimpleString here because the command string may contain escaped characters, and putting it inside
722 // another string to pass to PyRun_SimpleString messes up the escaping. So we use the following more complicated
723 // method to pass the command string directly down to Python.
724
Enrico Granatafa1f6172011-10-24 17:22:21 +0000725 Locker locker(this,
Jim Ingham14e71ec2012-12-07 17:43:38 +0000726 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession | (options.GetSetLLDBGlobals() ? ScriptInterpreterPython::Locker::InitGlobals : 0),
Enrico Granatafd670c22012-10-31 00:01:26 +0000727 ScriptInterpreterPython::Locker::FreeAcquiredLock | (options.GetSetLLDBGlobals() ? ScriptInterpreterPython::Locker::TearDownSession : 0));
Caroline Tice4a461da2011-01-14 21:09:29 +0000728
729 bool success = false;
730
Greg Clayton63094e02010-06-23 01:19:29 +0000731 if (command)
Chris Lattner24943d22010-06-08 16:52:24 +0000732 {
Caroline Tice4a461da2011-01-14 21:09:29 +0000733 // Find the correct script interpreter dictionary in the main module.
Enrico Granata400105d2012-03-06 23:42:15 +0000734 PyObject *script_interpreter_dict = FindSessionDictionary(m_dictionary_name.c_str());
735 if (script_interpreter_dict != NULL)
Caroline Tice4a461da2011-01-14 21:09:29 +0000736 {
Enrico Granata400105d2012-03-06 23:42:15 +0000737 PyObject *pfunc = (PyObject*)m_run_one_line;
Greg Clayton6f2f0ab2012-04-25 01:49:50 +0000738 PyObject *pmod = PyImport_AddModule ("lldb.embedded_interpreter");
Enrico Granata400105d2012-03-06 23:42:15 +0000739 if (pmod != NULL)
Caroline Tice4a461da2011-01-14 21:09:29 +0000740 {
Enrico Granata400105d2012-03-06 23:42:15 +0000741 PyObject *pmod_dict = PyModule_GetDict (pmod);
742 if ((pmod_dict != NULL)
743 && PyDict_Check (pmod_dict))
Caroline Tice4a461da2011-01-14 21:09:29 +0000744 {
Enrico Granata400105d2012-03-06 23:42:15 +0000745 if (!pfunc)
Caroline Tice4a461da2011-01-14 21:09:29 +0000746 {
747 PyObject *key, *value;
748 Py_ssize_t pos = 0;
749
750 while (PyDict_Next (pmod_dict, &pos, &key, &value))
751 {
752 Py_INCREF (key);
753 Py_INCREF (value);
754 if (strcmp (PyString_AsString (key), "run_one_line") == 0)
755 {
756 pfunc = value;
757 break;
758 }
759 }
Enrico Granata400105d2012-03-06 23:42:15 +0000760 m_run_one_line = pfunc;
761 }
762
763 if (pfunc && PyCallable_Check (pfunc))
764 {
765 PyObject *pargs = Py_BuildValue("(Os)",script_interpreter_dict,command);
766 if (pargs != NULL)
Caroline Tice4a461da2011-01-14 21:09:29 +0000767 {
Enrico Granataa1ba3142012-06-07 00:17:18 +0000768 PyObject *pvalue = NULL;
769 { // scope for PythonInputReaderManager
Enrico Granatafd670c22012-10-31 00:01:26 +0000770 PythonInputReaderManager py_input(options.GetEnableIO() ? this : NULL);
Enrico Granataa1ba3142012-06-07 00:17:18 +0000771 pvalue = PyObject_CallObject (pfunc, pargs);
772 }
Enrico Granata400105d2012-03-06 23:42:15 +0000773 Py_DECREF (pargs);
774 if (pvalue != NULL)
Caroline Tice4a461da2011-01-14 21:09:29 +0000775 {
Enrico Granata400105d2012-03-06 23:42:15 +0000776 Py_DECREF (pvalue);
777 success = true;
778 }
Enrico Granatafd670c22012-10-31 00:01:26 +0000779 else if (options.GetMaskoutErrors() && PyErr_Occurred ())
Enrico Granata400105d2012-03-06 23:42:15 +0000780 {
781 PyErr_Print();
782 PyErr_Clear();
Caroline Tice4a461da2011-01-14 21:09:29 +0000783 }
784 }
785 }
786 }
Caroline Tice4a461da2011-01-14 21:09:29 +0000787 }
Enrico Granata400105d2012-03-06 23:42:15 +0000788 Py_INCREF (script_interpreter_dict);
Caroline Tice4a461da2011-01-14 21:09:29 +0000789 }
Greg Clayton63094e02010-06-23 01:19:29 +0000790
Caroline Tice4a461da2011-01-14 21:09:29 +0000791 if (success)
Johnny Chen60dde642010-07-30 22:33:14 +0000792 return true;
793
794 // The one-liner failed. Append the error message.
795 if (result)
796 result->AppendErrorWithFormat ("python failed attempting to evaluate '%s'\n", command);
797 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000798 }
Johnny Chen60dde642010-07-30 22:33:14 +0000799
800 if (result)
801 result->AppendError ("empty command passed to python\n");
802 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000803}
804
Chris Lattner24943d22010-06-08 16:52:24 +0000805size_t
806ScriptInterpreterPython::InputReaderCallback
807(
808 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000809 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000810 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000811 const char *bytes,
812 size_t bytes_len
813)
814{
Caroline Tice2ade6112010-11-10 19:18:14 +0000815 lldb::thread_t embedded_interpreter_thread;
816 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
817
Chris Lattner24943d22010-06-08 16:52:24 +0000818 if (baton == NULL)
819 return 0;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000820
821 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
Enrico Granatafa1f6172011-10-24 17:22:21 +0000822
Caroline Tice0aa2e552011-01-14 00:29:16 +0000823 if (script_interpreter->m_script_lang != eScriptLanguagePython)
824 return 0;
825
Caroline Tice892fadd2011-06-16 16:27:19 +0000826 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
827 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
828
Chris Lattner24943d22010-06-08 16:52:24 +0000829 switch (notification)
830 {
831 case eInputReaderActivate:
832 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000833 if (!batch_mode)
834 {
835 out_stream->Printf ("Python Interactive Interpreter. To exit, type 'quit()', 'exit()' or Ctrl-D.\n");
836 out_stream->Flush();
837 }
Greg Clayton58928562011-02-09 01:08:52 +0000838
Chris Lattner24943d22010-06-08 16:52:24 +0000839 // Save terminal settings if we can
Greg Clayton58928562011-02-09 01:08:52 +0000840 int input_fd = reader.GetDebugger().GetInputFile().GetDescriptor();
841 if (input_fd == File::kInvalidDescriptor)
Greg Clayton24b48ff2010-10-17 22:03:32 +0000842 input_fd = STDIN_FILENO;
Caroline Ticec95c6d12010-09-14 22:49:06 +0000843
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000844 script_interpreter->SaveTerminalState(input_fd);
Greg Clayton99208582011-02-07 19:04:58 +0000845
Caroline Tice202f6b82011-01-17 21:55:19 +0000846 {
Enrico Granatafa1f6172011-10-24 17:22:21 +0000847 ScriptInterpreterPython::Locker locker(script_interpreter,
Jim Ingham14e71ec2012-12-07 17:43:38 +0000848 ScriptInterpreterPython::Locker::AcquireLock
849 | ScriptInterpreterPython::Locker::InitSession
850 | ScriptInterpreterPython::Locker::InitGlobals,
Enrico Granatafa1f6172011-10-24 17:22:21 +0000851 ScriptInterpreterPython::Locker::FreeAcquiredLock);
Caroline Tice202f6b82011-01-17 21:55:19 +0000852 }
Caroline Tice202f6b82011-01-17 21:55:19 +0000853
Caroline Tice2ade6112010-11-10 19:18:14 +0000854 char error_str[1024];
855 if (script_interpreter->m_embedded_python_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, error_str,
856 sizeof(error_str)))
857 {
858 if (log)
859 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in opening master pty (fd = %d).",
860 script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor());
861 embedded_interpreter_thread = Host::ThreadCreate ("<lldb.script-interpreter.embedded-python-loop>",
862 ScriptInterpreterPython::RunEmbeddedPythonInterpreter,
863 script_interpreter, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +0000864 if (IS_VALID_LLDB_HOST_THREAD(embedded_interpreter_thread))
Caroline Tice2ade6112010-11-10 19:18:14 +0000865 {
866 if (log)
Daniel Malea5f35a4b2012-11-29 21:49:15 +0000867 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in creating thread (thread_t = %p)", (void *)embedded_interpreter_thread);
Caroline Tice2ade6112010-11-10 19:18:14 +0000868 Error detach_error;
869 Host::ThreadDetach (embedded_interpreter_thread, &detach_error);
870 }
871 else
872 {
873 if (log)
874 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed in creating thread");
875 reader.SetIsDone (true);
876 }
877 }
878 else
879 {
880 if (log)
881 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed to open master pty ");
882 reader.SetIsDone (true);
883 }
Chris Lattner24943d22010-06-08 16:52:24 +0000884 }
885 break;
886
887 case eInputReaderDeactivate:
Greg Claytona1cec242012-01-06 00:47:38 +0000888 // When another input reader is pushed, don't leave the session...
889 //script_interpreter->LeaveSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000890 break;
891
892 case eInputReaderReactivate:
Caroline Tice202f6b82011-01-17 21:55:19 +0000893 {
Johnny Chen8165d432012-08-18 04:14:54 +0000894 ScriptInterpreterPython::Locker locker(script_interpreter,
Jim Ingham14e71ec2012-12-07 17:43:38 +0000895 ScriptInterpreterPython::Locker::AcquireLock
896 | ScriptInterpreterPython::Locker::InitSession
897 | ScriptInterpreterPython::Locker::InitGlobals,
Johnny Chen8165d432012-08-18 04:14:54 +0000898 ScriptInterpreterPython::Locker::FreeAcquiredLock);
Caroline Tice202f6b82011-01-17 21:55:19 +0000899 }
Chris Lattner24943d22010-06-08 16:52:24 +0000900 break;
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000901
Caroline Tice4a348082011-05-02 20:41:46 +0000902 case eInputReaderAsynchronousOutputWritten:
903 break;
904
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000905 case eInputReaderInterrupt:
906 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "raise KeyboardInterrupt\n", 24);
907 break;
908
909 case eInputReaderEndOfFile:
910 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()\n", 7);
911 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000912
913 case eInputReaderGotToken:
Caroline Tice2ade6112010-11-10 19:18:14 +0000914 if (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor() != -1)
Chris Lattner24943d22010-06-08 16:52:24 +0000915 {
Caroline Tice2ade6112010-11-10 19:18:14 +0000916 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000917 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %lu", bytes,
Caroline Tice2ade6112010-11-10 19:18:14 +0000918 bytes_len);
919 if (bytes && bytes_len)
920 {
921 if ((int) bytes[0] == 4)
922 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()", 6);
923 else
924 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), bytes, bytes_len);
925 }
926 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "\n", 1);
Chris Lattner24943d22010-06-08 16:52:24 +0000927 }
Caroline Tice2ade6112010-11-10 19:18:14 +0000928 else
929 {
930 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000931 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %lu, Master File Descriptor is bad.",
Caroline Tice2ade6112010-11-10 19:18:14 +0000932 bytes,
933 bytes_len);
934 reader.SetIsDone (true);
935 }
936
Chris Lattner24943d22010-06-08 16:52:24 +0000937 break;
938
939 case eInputReaderDone:
Johnny Chen8165d432012-08-18 04:14:54 +0000940 {
941 Locker locker(script_interpreter,
942 ScriptInterpreterPython::Locker::AcquireLock,
943 ScriptInterpreterPython::Locker::FreeAcquiredLock);
944 script_interpreter->LeaveSession ();
945 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000946
Chris Lattner24943d22010-06-08 16:52:24 +0000947 // Restore terminal settings if they were validly saved
Caroline Tice2ade6112010-11-10 19:18:14 +0000948 if (log)
949 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Done, closing down input reader.");
Caroline Ticec95c6d12010-09-14 22:49:06 +0000950
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000951 script_interpreter->RestoreTerminalState ();
952
Caroline Tice2ade6112010-11-10 19:18:14 +0000953 script_interpreter->m_embedded_python_pty.CloseMasterFileDescriptor();
Chris Lattner24943d22010-06-08 16:52:24 +0000954 break;
955 }
956
957 return bytes_len;
958}
959
960
961void
Greg Clayton238c0a12010-09-18 01:14:36 +0000962ScriptInterpreterPython::ExecuteInterpreterLoop ()
Chris Lattner24943d22010-06-08 16:52:24 +0000963{
964 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
965
Caroline Tice0aa2e552011-01-14 00:29:16 +0000966 Debugger &debugger = GetCommandInterpreter().GetDebugger();
Caroline Ticec95c6d12010-09-14 22:49:06 +0000967
968 // At the moment, the only time the debugger does not have an input file handle is when this is called
969 // directly from Python, in which case it is both dangerous and unnecessary (not to mention confusing) to
970 // try to embed a running interpreter loop inside the already running Python interpreter loop, so we won't
971 // do it.
972
Greg Clayton58928562011-02-09 01:08:52 +0000973 if (!debugger.GetInputFile().IsValid())
Caroline Ticec95c6d12010-09-14 22:49:06 +0000974 return;
975
Greg Clayton63094e02010-06-23 01:19:29 +0000976 InputReaderSP reader_sp (new InputReader(debugger));
Chris Lattner24943d22010-06-08 16:52:24 +0000977 if (reader_sp)
978 {
979 Error error (reader_sp->Initialize (ScriptInterpreterPython::InputReaderCallback,
980 this, // baton
981 eInputReaderGranularityLine, // token size, to pass to callback function
982 NULL, // end token
983 NULL, // prompt
984 true)); // echo input
985
986 if (error.Success())
987 {
Greg Clayton63094e02010-06-23 01:19:29 +0000988 debugger.PushInputReader (reader_sp);
Johnny Chen8121d7a2012-08-17 23:44:35 +0000989 m_embedded_python_input_reader_sp = reader_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000990 }
991 }
992}
993
994bool
995ScriptInterpreterPython::ExecuteOneLineWithReturn (const char *in_string,
Enrico Granata59df36f2011-10-17 21:45:27 +0000996 ScriptInterpreter::ScriptReturnType return_type,
Enrico Granataa1ba3142012-06-07 00:17:18 +0000997 void *ret_value,
Enrico Granatafd670c22012-10-31 00:01:26 +0000998 const ExecuteScriptOptions &options)
Chris Lattner24943d22010-06-08 16:52:24 +0000999{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001000
Enrico Granatafa1f6172011-10-24 17:22:21 +00001001 Locker locker(this,
Jim Ingham14e71ec2012-12-07 17:43:38 +00001002 ScriptInterpreterPython::Locker::AcquireLock
1003 | ScriptInterpreterPython::Locker::InitSession
1004 | (options.GetSetLLDBGlobals() ? ScriptInterpreterPython::Locker::InitGlobals : 0),
Enrico Granatafd670c22012-10-31 00:01:26 +00001005 ScriptInterpreterPython::Locker::FreeAcquiredLock | (options.GetSetLLDBGlobals() ? ScriptInterpreterPython::Locker::TearDownSession : 0));
Caroline Tice0aa2e552011-01-14 00:29:16 +00001006
Chris Lattner24943d22010-06-08 16:52:24 +00001007 PyObject *py_return = NULL;
1008 PyObject *mainmod = PyImport_AddModule ("__main__");
1009 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001010 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +00001011 PyObject *py_error = NULL;
Johnny Chen60a7df52011-08-11 19:17:45 +00001012 bool ret_success = false;
Caroline Tice0aa2e552011-01-14 00:29:16 +00001013 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +00001014 int success;
Caroline Tice0aa2e552011-01-14 00:29:16 +00001015
Enrico Granata400105d2012-03-06 23:42:15 +00001016 locals = FindSessionDictionary(m_dictionary_name.c_str());
1017
Caroline Tice0aa2e552011-01-14 00:29:16 +00001018 if (locals == NULL)
1019 {
1020 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
1021 should_decrement_locals = true;
1022 }
1023
1024 if (locals == NULL)
1025 {
1026 locals = globals;
1027 should_decrement_locals = false;
1028 }
1029
1030 py_error = PyErr_Occurred();
1031 if (py_error != NULL)
1032 PyErr_Clear();
1033
Chris Lattner24943d22010-06-08 16:52:24 +00001034 if (in_string != NULL)
1035 {
Enrico Granataa1ba3142012-06-07 00:17:18 +00001036 { // scope for PythonInputReaderManager
Enrico Granatafd670c22012-10-31 00:01:26 +00001037 PythonInputReaderManager py_input(options.GetEnableIO() ? this : NULL);
Enrico Granataa1ba3142012-06-07 00:17:18 +00001038 py_return = PyRun_String (in_string, Py_eval_input, globals, locals);
1039 if (py_return == NULL)
1040 {
1041 py_error = PyErr_Occurred ();
1042 if (py_error != NULL)
1043 PyErr_Clear ();
Chris Lattner24943d22010-06-08 16:52:24 +00001044
Enrico Granataa1ba3142012-06-07 00:17:18 +00001045 py_return = PyRun_String (in_string, Py_single_input, globals, locals);
1046 }
Chris Lattner24943d22010-06-08 16:52:24 +00001047 }
1048
Caroline Tice0aa2e552011-01-14 00:29:16 +00001049 if (locals != NULL
1050 && should_decrement_locals)
1051 Py_DECREF (locals);
1052
Chris Lattner24943d22010-06-08 16:52:24 +00001053 if (py_return != NULL)
1054 {
1055 switch (return_type)
1056 {
Enrico Granata59df36f2011-10-17 21:45:27 +00001057 case eScriptReturnTypeCharPtr: // "char *"
Chris Lattner24943d22010-06-08 16:52:24 +00001058 {
1059 const char format[3] = "s#";
Enrico Granatae5e34cb2011-08-17 01:30:04 +00001060 success = PyArg_Parse (py_return, format, (char **) ret_value);
Chris Lattner24943d22010-06-08 16:52:24 +00001061 break;
1062 }
Enrico Granata59df36f2011-10-17 21:45:27 +00001063 case eScriptReturnTypeCharStrOrNone: // char* or NULL if py_return == Py_None
Enrico Granatac2a28252011-08-16 16:49:25 +00001064 {
1065 const char format[3] = "z";
Enrico Granatae5e34cb2011-08-17 01:30:04 +00001066 success = PyArg_Parse (py_return, format, (char **) ret_value);
Enrico Granatac2a28252011-08-16 16:49:25 +00001067 break;
1068 }
Enrico Granata59df36f2011-10-17 21:45:27 +00001069 case eScriptReturnTypeBool:
Chris Lattner24943d22010-06-08 16:52:24 +00001070 {
1071 const char format[2] = "b";
1072 success = PyArg_Parse (py_return, format, (bool *) ret_value);
1073 break;
1074 }
Enrico Granata59df36f2011-10-17 21:45:27 +00001075 case eScriptReturnTypeShortInt:
Chris Lattner24943d22010-06-08 16:52:24 +00001076 {
1077 const char format[2] = "h";
1078 success = PyArg_Parse (py_return, format, (short *) ret_value);
1079 break;
1080 }
Enrico Granata59df36f2011-10-17 21:45:27 +00001081 case eScriptReturnTypeShortIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +00001082 {
1083 const char format[2] = "H";
1084 success = PyArg_Parse (py_return, format, (unsigned short *) ret_value);
1085 break;
1086 }
Enrico Granata59df36f2011-10-17 21:45:27 +00001087 case eScriptReturnTypeInt:
Chris Lattner24943d22010-06-08 16:52:24 +00001088 {
1089 const char format[2] = "i";
1090 success = PyArg_Parse (py_return, format, (int *) ret_value);
1091 break;
1092 }
Enrico Granata59df36f2011-10-17 21:45:27 +00001093 case eScriptReturnTypeIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +00001094 {
1095 const char format[2] = "I";
1096 success = PyArg_Parse (py_return, format, (unsigned int *) ret_value);
1097 break;
1098 }
Enrico Granata59df36f2011-10-17 21:45:27 +00001099 case eScriptReturnTypeLongInt:
Chris Lattner24943d22010-06-08 16:52:24 +00001100 {
1101 const char format[2] = "l";
1102 success = PyArg_Parse (py_return, format, (long *) ret_value);
1103 break;
1104 }
Enrico Granata59df36f2011-10-17 21:45:27 +00001105 case eScriptReturnTypeLongIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +00001106 {
1107 const char format[2] = "k";
1108 success = PyArg_Parse (py_return, format, (unsigned long *) ret_value);
1109 break;
1110 }
Enrico Granata59df36f2011-10-17 21:45:27 +00001111 case eScriptReturnTypeLongLong:
Chris Lattner24943d22010-06-08 16:52:24 +00001112 {
1113 const char format[2] = "L";
1114 success = PyArg_Parse (py_return, format, (long long *) ret_value);
1115 break;
1116 }
Enrico Granata59df36f2011-10-17 21:45:27 +00001117 case eScriptReturnTypeLongLongUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +00001118 {
1119 const char format[2] = "K";
1120 success = PyArg_Parse (py_return, format, (unsigned long long *) ret_value);
1121 break;
1122 }
Enrico Granata59df36f2011-10-17 21:45:27 +00001123 case eScriptReturnTypeFloat:
Chris Lattner24943d22010-06-08 16:52:24 +00001124 {
1125 const char format[2] = "f";
1126 success = PyArg_Parse (py_return, format, (float *) ret_value);
1127 break;
1128 }
Enrico Granata59df36f2011-10-17 21:45:27 +00001129 case eScriptReturnTypeDouble:
Chris Lattner24943d22010-06-08 16:52:24 +00001130 {
1131 const char format[2] = "d";
1132 success = PyArg_Parse (py_return, format, (double *) ret_value);
1133 break;
1134 }
Enrico Granata59df36f2011-10-17 21:45:27 +00001135 case eScriptReturnTypeChar:
Chris Lattner24943d22010-06-08 16:52:24 +00001136 {
1137 const char format[2] = "c";
1138 success = PyArg_Parse (py_return, format, (char *) ret_value);
1139 break;
1140 }
Chris Lattner24943d22010-06-08 16:52:24 +00001141 }
1142 Py_DECREF (py_return);
1143 if (success)
1144 ret_success = true;
1145 else
1146 ret_success = false;
1147 }
1148 }
1149
1150 py_error = PyErr_Occurred();
1151 if (py_error != NULL)
1152 {
Chris Lattner24943d22010-06-08 16:52:24 +00001153 ret_success = false;
Enrico Granatafd670c22012-10-31 00:01:26 +00001154 if (options.GetMaskoutErrors())
1155 {
1156 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
1157 PyErr_Print ();
1158 PyErr_Clear();
1159 }
Chris Lattner24943d22010-06-08 16:52:24 +00001160 }
Caroline Tice202f6b82011-01-17 21:55:19 +00001161
Chris Lattner24943d22010-06-08 16:52:24 +00001162 return ret_success;
1163}
1164
1165bool
Enrico Granatafd670c22012-10-31 00:01:26 +00001166ScriptInterpreterPython::ExecuteMultipleLines (const char *in_string, const ExecuteScriptOptions &options)
Chris Lattner24943d22010-06-08 16:52:24 +00001167{
Enrico Granatafa1f6172011-10-24 17:22:21 +00001168
1169
1170 Locker locker(this,
Jim Ingham14e71ec2012-12-07 17:43:38 +00001171 ScriptInterpreterPython::Locker::AcquireLock
1172 | ScriptInterpreterPython::Locker::InitSession
1173 | (options.GetSetLLDBGlobals() ? ScriptInterpreterPython::Locker::InitGlobals : 0),
Enrico Granatafd670c22012-10-31 00:01:26 +00001174 ScriptInterpreterPython::Locker::FreeAcquiredLock | (options.GetSetLLDBGlobals() ? ScriptInterpreterPython::Locker::TearDownSession : 0));
Caroline Tice0aa2e552011-01-14 00:29:16 +00001175
Chris Lattner24943d22010-06-08 16:52:24 +00001176 bool success = false;
1177 PyObject *py_return = NULL;
1178 PyObject *mainmod = PyImport_AddModule ("__main__");
1179 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001180 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +00001181 PyObject *py_error = NULL;
Caroline Tice0aa2e552011-01-14 00:29:16 +00001182 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +00001183
Enrico Granata400105d2012-03-06 23:42:15 +00001184 locals = FindSessionDictionary(m_dictionary_name.c_str());
1185
Caroline Tice0aa2e552011-01-14 00:29:16 +00001186 if (locals == NULL)
1187 {
1188 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
1189 should_decrement_locals = true;
1190 }
1191
1192 if (locals == NULL)
1193 {
1194 locals = globals;
1195 should_decrement_locals = false;
1196 }
1197
1198 py_error = PyErr_Occurred();
1199 if (py_error != NULL)
1200 PyErr_Clear();
1201
Chris Lattner24943d22010-06-08 16:52:24 +00001202 if (in_string != NULL)
1203 {
1204 struct _node *compiled_node = PyParser_SimpleParseString (in_string, Py_file_input);
1205 if (compiled_node)
1206 {
1207 PyCodeObject *compiled_code = PyNode_Compile (compiled_node, "temp.py");
1208 if (compiled_code)
1209 {
Enrico Granataa1ba3142012-06-07 00:17:18 +00001210 { // scope for PythonInputReaderManager
Enrico Granatafd670c22012-10-31 00:01:26 +00001211 PythonInputReaderManager py_input(options.GetEnableIO() ? this : NULL);
Enrico Granataa1ba3142012-06-07 00:17:18 +00001212 py_return = PyEval_EvalCode (compiled_code, globals, locals);
1213 }
Chris Lattner24943d22010-06-08 16:52:24 +00001214 if (py_return != NULL)
1215 {
1216 success = true;
1217 Py_DECREF (py_return);
1218 }
Caroline Tice0aa2e552011-01-14 00:29:16 +00001219 if (locals && should_decrement_locals)
1220 Py_DECREF (locals);
Chris Lattner24943d22010-06-08 16:52:24 +00001221 }
1222 }
1223 }
1224
1225 py_error = PyErr_Occurred ();
1226 if (py_error != NULL)
1227 {
Chris Lattner24943d22010-06-08 16:52:24 +00001228 success = false;
Enrico Granatafd670c22012-10-31 00:01:26 +00001229 if (options.GetMaskoutErrors())
1230 {
1231 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
1232 PyErr_Print ();
1233 PyErr_Clear();
1234 }
Chris Lattner24943d22010-06-08 16:52:24 +00001235 }
1236
1237 return success;
1238}
1239
1240static const char *g_reader_instructions = "Enter your Python command(s). Type 'DONE' to end.";
1241
1242size_t
1243ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback
1244(
1245 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +00001246 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +00001247 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +00001248 const char *bytes,
1249 size_t bytes_len
1250)
1251{
Caroline Tice892fadd2011-06-16 16:27:19 +00001252 static StringList commands_in_progress;
1253
1254 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
1255 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
1256
Chris Lattner24943d22010-06-08 16:52:24 +00001257 switch (notification)
1258 {
1259 case eInputReaderActivate:
1260 {
1261 commands_in_progress.Clear();
Caroline Tice892fadd2011-06-16 16:27:19 +00001262 if (!batch_mode)
Chris Lattner24943d22010-06-08 16:52:24 +00001263 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001264 out_stream->Printf ("%s\n", g_reader_instructions);
Greg Clayton63094e02010-06-23 01:19:29 +00001265 if (reader.GetPrompt())
Caroline Tice892fadd2011-06-16 16:27:19 +00001266 out_stream->Printf ("%s", reader.GetPrompt());
1267 out_stream->Flush ();
Chris Lattner24943d22010-06-08 16:52:24 +00001268 }
1269 }
1270 break;
1271
1272 case eInputReaderDeactivate:
1273 break;
1274
1275 case eInputReaderReactivate:
Caroline Tice892fadd2011-06-16 16:27:19 +00001276 if (reader.GetPrompt() && !batch_mode)
Caroline Ticef81b4c52010-10-27 18:34:42 +00001277 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001278 out_stream->Printf ("%s", reader.GetPrompt());
1279 out_stream->Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +00001280 }
Chris Lattner24943d22010-06-08 16:52:24 +00001281 break;
1282
Caroline Tice4a348082011-05-02 20:41:46 +00001283 case eInputReaderAsynchronousOutputWritten:
1284 break;
1285
Chris Lattner24943d22010-06-08 16:52:24 +00001286 case eInputReaderGotToken:
1287 {
1288 std::string temp_string (bytes, bytes_len);
1289 commands_in_progress.AppendString (temp_string.c_str());
Caroline Tice892fadd2011-06-16 16:27:19 +00001290 if (!reader.IsDone() && reader.GetPrompt() && !batch_mode)
Caroline Ticef81b4c52010-10-27 18:34:42 +00001291 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001292 out_stream->Printf ("%s", reader.GetPrompt());
1293 out_stream->Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +00001294 }
Chris Lattner24943d22010-06-08 16:52:24 +00001295 }
1296 break;
1297
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001298 case eInputReaderEndOfFile:
1299 case eInputReaderInterrupt:
1300 // Control-c (SIGINT) & control-d both mean finish & exit.
1301 reader.SetIsDone(true);
1302
1303 // Control-c (SIGINT) ALSO means cancel; do NOT create a breakpoint command.
1304 if (notification == eInputReaderInterrupt)
1305 commands_in_progress.Clear();
1306
1307 // Fall through here...
1308
Chris Lattner24943d22010-06-08 16:52:24 +00001309 case eInputReaderDone:
1310 {
1311 BreakpointOptions *bp_options = (BreakpointOptions *)baton;
1312 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1313 data_ap->user_source.AppendList (commands_in_progress);
1314 if (data_ap.get())
1315 {
Greg Clayton63094e02010-06-23 01:19:29 +00001316 ScriptInterpreter *interpreter = reader.GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
Chris Lattner24943d22010-06-08 16:52:24 +00001317 if (interpreter)
1318 {
1319 if (interpreter->GenerateBreakpointCommandCallbackData (data_ap->user_source,
1320 data_ap->script_source))
1321 {
Enrico Granata400105d2012-03-06 23:42:15 +00001322 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1323 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001324 }
Caroline Tice892fadd2011-06-16 16:27:19 +00001325 else if (!batch_mode)
1326 {
1327 out_stream->Printf ("Warning: No command attached to breakpoint.\n");
1328 out_stream->Flush();
1329 }
Chris Lattner24943d22010-06-08 16:52:24 +00001330 }
1331 else
1332 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001333 if (!batch_mode)
1334 {
1335 out_stream->Printf ("Warning: Unable to find script intepreter; no command attached to breakpoint.\n");
1336 out_stream->Flush();
1337 }
Chris Lattner24943d22010-06-08 16:52:24 +00001338 }
1339 }
1340 }
1341 break;
1342
1343 }
1344
1345 return bytes_len;
1346}
1347
Johnny Chenf3ec4612012-08-09 23:09:42 +00001348size_t
1349ScriptInterpreterPython::GenerateWatchpointOptionsCommandCallback
1350(
1351 void *baton,
1352 InputReader &reader,
1353 InputReaderAction notification,
1354 const char *bytes,
1355 size_t bytes_len
1356)
1357{
1358 static StringList commands_in_progress;
1359
1360 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
1361 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
1362
1363 switch (notification)
1364 {
1365 case eInputReaderActivate:
1366 {
1367 commands_in_progress.Clear();
1368 if (!batch_mode)
1369 {
1370 out_stream->Printf ("%s\n", g_reader_instructions);
1371 if (reader.GetPrompt())
1372 out_stream->Printf ("%s", reader.GetPrompt());
1373 out_stream->Flush ();
1374 }
1375 }
1376 break;
1377
1378 case eInputReaderDeactivate:
1379 break;
1380
1381 case eInputReaderReactivate:
1382 if (reader.GetPrompt() && !batch_mode)
1383 {
1384 out_stream->Printf ("%s", reader.GetPrompt());
1385 out_stream->Flush ();
1386 }
1387 break;
1388
1389 case eInputReaderAsynchronousOutputWritten:
1390 break;
1391
1392 case eInputReaderGotToken:
1393 {
1394 std::string temp_string (bytes, bytes_len);
1395 commands_in_progress.AppendString (temp_string.c_str());
1396 if (!reader.IsDone() && reader.GetPrompt() && !batch_mode)
1397 {
1398 out_stream->Printf ("%s", reader.GetPrompt());
1399 out_stream->Flush ();
1400 }
1401 }
1402 break;
1403
1404 case eInputReaderEndOfFile:
1405 case eInputReaderInterrupt:
1406 // Control-c (SIGINT) & control-d both mean finish & exit.
1407 reader.SetIsDone(true);
1408
1409 // Control-c (SIGINT) ALSO means cancel; do NOT create a breakpoint command.
1410 if (notification == eInputReaderInterrupt)
1411 commands_in_progress.Clear();
1412
1413 // Fall through here...
1414
1415 case eInputReaderDone:
1416 {
1417 WatchpointOptions *wp_options = (WatchpointOptions *)baton;
1418 std::auto_ptr<WatchpointOptions::CommandData> data_ap(new WatchpointOptions::CommandData());
1419 data_ap->user_source.AppendList (commands_in_progress);
1420 if (data_ap.get())
1421 {
1422 ScriptInterpreter *interpreter = reader.GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
1423 if (interpreter)
1424 {
1425 if (interpreter->GenerateWatchpointCommandCallbackData (data_ap->user_source,
1426 data_ap->script_source))
1427 {
1428 BatonSP baton_sp (new WatchpointOptions::CommandBaton (data_ap.release()));
1429 wp_options->SetCallback (ScriptInterpreterPython::WatchpointCallbackFunction, baton_sp);
1430 }
1431 else if (!batch_mode)
1432 {
1433 out_stream->Printf ("Warning: No command attached to breakpoint.\n");
1434 out_stream->Flush();
1435 }
1436 }
1437 else
1438 {
1439 if (!batch_mode)
1440 {
1441 out_stream->Printf ("Warning: Unable to find script intepreter; no command attached to breakpoint.\n");
1442 out_stream->Flush();
1443 }
1444 }
1445 }
1446 }
1447 break;
1448
1449 }
1450
1451 return bytes_len;
1452}
1453
Chris Lattner24943d22010-06-08 16:52:24 +00001454void
Greg Clayton238c0a12010-09-18 01:14:36 +00001455ScriptInterpreterPython::CollectDataForBreakpointCommandCallback (BreakpointOptions *bp_options,
Chris Lattner24943d22010-06-08 16:52:24 +00001456 CommandReturnObject &result)
1457{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001458 Debugger &debugger = GetCommandInterpreter().GetDebugger();
1459
Greg Clayton63094e02010-06-23 01:19:29 +00001460 InputReaderSP reader_sp (new InputReader (debugger));
Chris Lattner24943d22010-06-08 16:52:24 +00001461
1462 if (reader_sp)
1463 {
1464 Error err = reader_sp->Initialize (
1465 ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback,
1466 bp_options, // baton
1467 eInputReaderGranularityLine, // token size, for feeding data to callback function
1468 "DONE", // end token
1469 "> ", // prompt
1470 true); // echo input
1471
1472 if (err.Success())
Greg Clayton63094e02010-06-23 01:19:29 +00001473 debugger.PushInputReader (reader_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001474 else
1475 {
1476 result.AppendError (err.AsCString());
1477 result.SetStatus (eReturnStatusFailed);
1478 }
1479 }
1480 else
1481 {
1482 result.AppendError("out of memory");
1483 result.SetStatus (eReturnStatusFailed);
1484 }
1485}
1486
Johnny Chenf3ec4612012-08-09 23:09:42 +00001487void
1488ScriptInterpreterPython::CollectDataForWatchpointCommandCallback (WatchpointOptions *wp_options,
1489 CommandReturnObject &result)
1490{
1491 Debugger &debugger = GetCommandInterpreter().GetDebugger();
1492
1493 InputReaderSP reader_sp (new InputReader (debugger));
1494
1495 if (reader_sp)
1496 {
1497 Error err = reader_sp->Initialize (
1498 ScriptInterpreterPython::GenerateWatchpointOptionsCommandCallback,
1499 wp_options, // baton
1500 eInputReaderGranularityLine, // token size, for feeding data to callback function
1501 "DONE", // end token
1502 "> ", // prompt
1503 true); // echo input
1504
1505 if (err.Success())
1506 debugger.PushInputReader (reader_sp);
1507 else
1508 {
1509 result.AppendError (err.AsCString());
1510 result.SetStatus (eReturnStatusFailed);
1511 }
1512 }
1513 else
1514 {
1515 result.AppendError("out of memory");
1516 result.SetStatus (eReturnStatusFailed);
1517 }
1518}
1519
Johnny Chen3e0571b2010-09-11 00:23:59 +00001520// Set a Python one-liner as the callback for the breakpoint.
Johnny Chend1c2dca2010-09-10 18:21:10 +00001521void
Greg Clayton238c0a12010-09-18 01:14:36 +00001522ScriptInterpreterPython::SetBreakpointCommandCallback (BreakpointOptions *bp_options,
Johnny Chend1c2dca2010-09-10 18:21:10 +00001523 const char *oneliner)
1524{
1525 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1526
1527 // It's necessary to set both user_source and script_source to the oneliner.
1528 // The former is used to generate callback description (as in breakpoint command list)
1529 // while the latter is used for Python to interpret during the actual callback.
Caroline Tice5136f942010-09-27 21:35:15 +00001530
Johnny Chend1c2dca2010-09-10 18:21:10 +00001531 data_ap->user_source.AppendString (oneliner);
Johnny Chenf3ec4612012-08-09 23:09:42 +00001532 data_ap->script_source.assign (oneliner);
Johnny Chend1c2dca2010-09-10 18:21:10 +00001533
Caroline Tice5136f942010-09-27 21:35:15 +00001534 if (GenerateBreakpointCommandCallbackData (data_ap->user_source, data_ap->script_source))
1535 {
Enrico Granata400105d2012-03-06 23:42:15 +00001536 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1537 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
Caroline Tice5136f942010-09-27 21:35:15 +00001538 }
1539
Johnny Chend1c2dca2010-09-10 18:21:10 +00001540 return;
1541}
1542
Johnny Chenf3ec4612012-08-09 23:09:42 +00001543// Set a Python one-liner as the callback for the watchpoint.
1544void
1545ScriptInterpreterPython::SetWatchpointCommandCallback (WatchpointOptions *wp_options,
1546 const char *oneliner)
1547{
1548 std::auto_ptr<WatchpointOptions::CommandData> data_ap(new WatchpointOptions::CommandData());
1549
1550 // It's necessary to set both user_source and script_source to the oneliner.
1551 // The former is used to generate callback description (as in watchpoint command list)
1552 // while the latter is used for Python to interpret during the actual callback.
1553
1554 data_ap->user_source.AppendString (oneliner);
1555 data_ap->script_source.assign (oneliner);
1556
1557 if (GenerateWatchpointCommandCallbackData (data_ap->user_source, data_ap->script_source))
1558 {
1559 BatonSP baton_sp (new WatchpointOptions::CommandBaton (data_ap.release()));
1560 wp_options->SetCallback (ScriptInterpreterPython::WatchpointCallbackFunction, baton_sp);
1561 }
1562
1563 return;
1564}
1565
Chris Lattner24943d22010-06-08 16:52:24 +00001566bool
1567ScriptInterpreterPython::ExportFunctionDefinitionToInterpreter (StringList &function_def)
1568{
1569 // Convert StringList to one long, newline delimited, const char *.
Enrico Granata400105d2012-03-06 23:42:15 +00001570 std::string function_def_string(function_def.CopyList());
Chris Lattner24943d22010-06-08 16:52:24 +00001571
Enrico Granatafd670c22012-10-31 00:01:26 +00001572 return ExecuteMultipleLines (function_def_string.c_str(), ScriptInterpreter::ExecuteScriptOptions().SetEnableIO(false));
Chris Lattner24943d22010-06-08 16:52:24 +00001573}
1574
Enrico Granataf7a9b142011-07-15 02:26:42 +00001575bool
Enrico Granata400105d2012-03-06 23:42:15 +00001576ScriptInterpreterPython::GenerateFunction(const char *signature, const StringList &input)
Enrico Granataf7a9b142011-07-15 02:26:42 +00001577{
1578 int num_lines = input.GetSize ();
1579 if (num_lines == 0)
1580 return false;
Enrico Granata400105d2012-03-06 23:42:15 +00001581
1582 if (!signature || *signature == 0)
1583 return false;
1584
Enrico Granataf7a9b142011-07-15 02:26:42 +00001585 StreamString sstr;
1586 StringList auto_generated_function;
Enrico Granata400105d2012-03-06 23:42:15 +00001587 auto_generated_function.AppendString (signature);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001588 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
Enrico Granatac1ca9dc2012-08-08 02:06:30 +00001589 auto_generated_function.AppendString (" new_keys = internal_dict.keys()"); // Make a list of keys in the session dict
Enrico Granataf7a9b142011-07-15 02:26:42 +00001590 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
Enrico Granatac1ca9dc2012-08-08 02:06:30 +00001591 auto_generated_function.AppendString (" global_dict.update (internal_dict)"); // Add the session dictionary to the
Enrico Granataf7a9b142011-07-15 02:26:42 +00001592 // global dictionary.
1593
1594 // Wrap everything up inside the function, increasing the indentation.
1595
1596 for (int i = 0; i < num_lines; ++i)
1597 {
1598 sstr.Clear ();
1599 sstr.Printf (" %s", input.GetStringAtIndex (i));
1600 auto_generated_function.AppendString (sstr.GetData());
1601 }
1602 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
Enrico Granatac1ca9dc2012-08-08 02:06:30 +00001603 auto_generated_function.AppendString (" internal_dict[key] = global_dict[key]"); // Update session dict values
Enrico Granataf7a9b142011-07-15 02:26:42 +00001604 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1605 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1606
1607 // Verify that the results are valid Python.
1608
1609 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1610 return false;
1611
1612 return true;
1613
1614}
1615
Enrico Granataf7a9b142011-07-15 02:26:42 +00001616bool
Enrico Granata400105d2012-03-06 23:42:15 +00001617ScriptInterpreterPython::GenerateTypeScriptFunction (StringList &user_input, std::string& output, void* name_token)
Enrico Granataf7a9b142011-07-15 02:26:42 +00001618{
Enrico Granata400105d2012-03-06 23:42:15 +00001619 static uint32_t num_created_functions = 0;
Enrico Granataf7a9b142011-07-15 02:26:42 +00001620 user_input.RemoveBlankLines ();
Enrico Granataf7a9b142011-07-15 02:26:42 +00001621 StreamString sstr;
1622
1623 // Check to see if we have any data; if not, just return.
1624 if (user_input.GetSize() == 0)
1625 return false;
1626
1627 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1628 // ValueObject as parameter to the function.
1629
Enrico Granata400105d2012-03-06 23:42:15 +00001630 std::string auto_generated_function_name(GenerateUniqueName("lldb_autogen_python_type_print_func", num_created_functions, name_token));
Enrico Granatac1ca9dc2012-08-08 02:06:30 +00001631 sstr.Printf ("def %s (valobj, internal_dict):", auto_generated_function_name.c_str());
Enrico Granataf7a9b142011-07-15 02:26:42 +00001632
Enrico Granata400105d2012-03-06 23:42:15 +00001633 if (!GenerateFunction(sstr.GetData(), user_input))
Enrico Granataf7a9b142011-07-15 02:26:42 +00001634 return false;
Enrico Granata400105d2012-03-06 23:42:15 +00001635
Enrico Granataf7a9b142011-07-15 02:26:42 +00001636 // Store the name of the auto-generated function to be called.
Enrico Granata400105d2012-03-06 23:42:15 +00001637 output.assign(auto_generated_function_name);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001638 return true;
1639}
1640
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001641bool
Enrico Granata400105d2012-03-06 23:42:15 +00001642ScriptInterpreterPython::GenerateScriptAliasFunction (StringList &user_input, std::string &output)
Enrico Granatac2a28252011-08-16 16:49:25 +00001643{
Enrico Granata400105d2012-03-06 23:42:15 +00001644 static uint32_t num_created_functions = 0;
Enrico Granatac2a28252011-08-16 16:49:25 +00001645 user_input.RemoveBlankLines ();
Enrico Granatac2a28252011-08-16 16:49:25 +00001646 StreamString sstr;
1647
1648 // Check to see if we have any data; if not, just return.
1649 if (user_input.GetSize() == 0)
1650 return false;
1651
Enrico Granata400105d2012-03-06 23:42:15 +00001652 std::string auto_generated_function_name(GenerateUniqueName("lldb_autogen_python_cmd_alias_func", num_created_functions));
1653
Enrico Granatac1ca9dc2012-08-08 02:06:30 +00001654 sstr.Printf ("def %s (debugger, args, result, internal_dict):", auto_generated_function_name.c_str());
Enrico Granatac2a28252011-08-16 16:49:25 +00001655
Enrico Granata400105d2012-03-06 23:42:15 +00001656 if (!GenerateFunction(sstr.GetData(),user_input))
Enrico Granatac2a28252011-08-16 16:49:25 +00001657 return false;
1658
1659 // Store the name of the auto-generated function to be called.
Enrico Granata400105d2012-03-06 23:42:15 +00001660 output.assign(auto_generated_function_name);
Enrico Granatac2a28252011-08-16 16:49:25 +00001661 return true;
1662}
1663
1664
1665bool
Enrico Granata400105d2012-03-06 23:42:15 +00001666ScriptInterpreterPython::GenerateTypeSynthClass (StringList &user_input, std::string &output, void* name_token)
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001667{
Enrico Granata400105d2012-03-06 23:42:15 +00001668 static uint32_t num_created_classes = 0;
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001669 user_input.RemoveBlankLines ();
1670 int num_lines = user_input.GetSize ();
1671 StreamString sstr;
1672
1673 // Check to see if we have any data; if not, just return.
1674 if (user_input.GetSize() == 0)
1675 return false;
1676
1677 // Wrap all user input into a Python class
1678
Enrico Granata400105d2012-03-06 23:42:15 +00001679 std::string auto_generated_class_name(GenerateUniqueName("lldb_autogen_python_type_synth_class",num_created_classes,name_token));
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001680
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001681 StringList auto_generated_class;
1682
1683 // Create the function name & definition string.
1684
1685 sstr.Printf ("class %s:", auto_generated_class_name.c_str());
1686 auto_generated_class.AppendString (sstr.GetData());
1687
1688 // Wrap everything up inside the class, increasing the indentation.
1689
1690 for (int i = 0; i < num_lines; ++i)
1691 {
1692 sstr.Clear ();
1693 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1694 auto_generated_class.AppendString (sstr.GetData());
1695 }
1696
1697
1698 // Verify that the results are valid Python.
1699 // (even though the method is ExportFunctionDefinitionToInterpreter, a class will actually be exported)
1700 // (TODO: rename that method to ExportDefinitionToInterpreter)
1701 if (!ExportFunctionDefinitionToInterpreter (auto_generated_class))
1702 return false;
1703
1704 // Store the name of the auto-generated class
1705
Enrico Granata400105d2012-03-06 23:42:15 +00001706 output.assign(auto_generated_class_name);
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001707 return true;
1708}
1709
Enrico Granata400105d2012-03-06 23:42:15 +00001710lldb::ScriptInterpreterObjectSP
Enrico Granata155ee912012-08-24 00:30:47 +00001711ScriptInterpreterPython::CreateOSPlugin (std::string class_name,
1712 lldb::ProcessSP process_sp)
1713{
1714 if (class_name.empty())
1715 return lldb::ScriptInterpreterObjectSP();
1716
1717 if (!process_sp)
1718 return lldb::ScriptInterpreterObjectSP();
1719
1720 void* ret_val;
1721
1722 {
Enrico Granatacec963a2012-08-24 01:34:39 +00001723 Locker py_lock(this,Locker::AcquireLock,Locker::FreeLock);
Enrico Granata155ee912012-08-24 00:30:47 +00001724 ret_val = g_swig_create_os_plugin (class_name,
1725 m_dictionary_name.c_str(),
1726 process_sp);
1727 }
1728
1729 return MakeScriptObject(ret_val);
1730}
1731
1732lldb::ScriptInterpreterObjectSP
1733ScriptInterpreterPython::OSPlugin_QueryForRegisterInfo (lldb::ScriptInterpreterObjectSP object)
1734{
Enrico Granatacec963a2012-08-24 01:34:39 +00001735 Locker py_lock(this,Locker::AcquireLock,Locker::FreeLock);
1736
Enrico Granata155ee912012-08-24 00:30:47 +00001737 static char callee_name[] = "get_register_info";
1738
1739 if (!object)
1740 return lldb::ScriptInterpreterObjectSP();
1741
1742 PyObject* implementor = (PyObject*)object->GetObject();
1743
1744 if (implementor == NULL || implementor == Py_None)
1745 return lldb::ScriptInterpreterObjectSP();
1746
1747 PyObject* pmeth = PyObject_GetAttrString(implementor, callee_name);
1748
1749 if (PyErr_Occurred())
1750 {
1751 PyErr_Clear();
1752 }
1753
1754 if (pmeth == NULL || pmeth == Py_None)
1755 {
1756 Py_XDECREF(pmeth);
1757 return lldb::ScriptInterpreterObjectSP();
1758 }
1759
1760 if (PyCallable_Check(pmeth) == 0)
1761 {
1762 if (PyErr_Occurred())
1763 {
1764 PyErr_Clear();
1765 }
1766
1767 Py_XDECREF(pmeth);
1768 return lldb::ScriptInterpreterObjectSP();
1769 }
1770
1771 if (PyErr_Occurred())
1772 {
1773 PyErr_Clear();
1774 }
1775
1776 Py_XDECREF(pmeth);
1777
1778 // right now we know this function exists and is callable..
1779 PyObject* py_return = PyObject_CallMethod(implementor, callee_name, NULL);
1780
1781 // if it fails, print the error but otherwise go on
1782 if (PyErr_Occurred())
1783 {
1784 PyErr_Print();
1785 PyErr_Clear();
1786 }
1787
1788 return MakeScriptObject(py_return);
1789}
1790
1791lldb::ScriptInterpreterObjectSP
Enrico Granata3e85b632012-08-24 00:51:29 +00001792ScriptInterpreterPython::OSPlugin_QueryForThreadsInfo (lldb::ScriptInterpreterObjectSP object)
1793{
Enrico Granatacec963a2012-08-24 01:34:39 +00001794 Locker py_lock(this,Locker::AcquireLock,Locker::FreeLock);
1795
Enrico Granata3e85b632012-08-24 00:51:29 +00001796 static char callee_name[] = "get_thread_info";
1797
1798 if (!object)
1799 return lldb::ScriptInterpreterObjectSP();
1800
1801 PyObject* implementor = (PyObject*)object->GetObject();
1802
1803 if (implementor == NULL || implementor == Py_None)
1804 return lldb::ScriptInterpreterObjectSP();
1805
1806 PyObject* pmeth = PyObject_GetAttrString(implementor, callee_name);
1807
1808 if (PyErr_Occurred())
1809 {
1810 PyErr_Clear();
1811 }
1812
1813 if (pmeth == NULL || pmeth == Py_None)
1814 {
1815 Py_XDECREF(pmeth);
1816 return lldb::ScriptInterpreterObjectSP();
1817 }
1818
1819 if (PyCallable_Check(pmeth) == 0)
1820 {
1821 if (PyErr_Occurred())
1822 {
1823 PyErr_Clear();
1824 }
1825
1826 Py_XDECREF(pmeth);
1827 return lldb::ScriptInterpreterObjectSP();
1828 }
1829
1830 if (PyErr_Occurred())
1831 {
1832 PyErr_Clear();
1833 }
1834
1835 Py_XDECREF(pmeth);
1836
1837 // right now we know this function exists and is callable..
1838 PyObject* py_return = PyObject_CallMethod(implementor, callee_name, NULL);
1839
1840 // if it fails, print the error but otherwise go on
1841 if (PyErr_Occurred())
1842 {
1843 PyErr_Print();
1844 PyErr_Clear();
1845 }
1846
1847 return MakeScriptObject(py_return);
1848}
1849
1850lldb::ScriptInterpreterObjectSP
Greg Claytonb8f126a2012-08-24 05:45:15 +00001851ScriptInterpreterPython::OSPlugin_QueryForRegisterContextData (lldb::ScriptInterpreterObjectSP object,
1852 lldb::tid_t thread_id)
Enrico Granata3e85b632012-08-24 00:51:29 +00001853{
Enrico Granatacec963a2012-08-24 01:34:39 +00001854 Locker py_lock(this,Locker::AcquireLock,Locker::FreeLock);
1855
Enrico Granata3e85b632012-08-24 00:51:29 +00001856 static char callee_name[] = "get_register_data";
1857 static char param_format[] = "l";
1858
1859 if (!object)
1860 return lldb::ScriptInterpreterObjectSP();
1861
1862 PyObject* implementor = (PyObject*)object->GetObject();
1863
1864 if (implementor == NULL || implementor == Py_None)
1865 return lldb::ScriptInterpreterObjectSP();
1866
1867 PyObject* pmeth = PyObject_GetAttrString(implementor, callee_name);
1868
1869 if (PyErr_Occurred())
1870 {
1871 PyErr_Clear();
1872 }
1873
1874 if (pmeth == NULL || pmeth == Py_None)
1875 {
1876 Py_XDECREF(pmeth);
1877 return lldb::ScriptInterpreterObjectSP();
1878 }
1879
1880 if (PyCallable_Check(pmeth) == 0)
1881 {
1882 if (PyErr_Occurred())
1883 {
1884 PyErr_Clear();
1885 }
1886
1887 Py_XDECREF(pmeth);
1888 return lldb::ScriptInterpreterObjectSP();
1889 }
1890
1891 if (PyErr_Occurred())
1892 {
1893 PyErr_Clear();
1894 }
1895
1896 Py_XDECREF(pmeth);
1897
1898 // right now we know this function exists and is callable..
1899 PyObject* py_return = PyObject_CallMethod(implementor, callee_name, param_format, thread_id);
1900
1901 // if it fails, print the error but otherwise go on
1902 if (PyErr_Occurred())
1903 {
1904 PyErr_Print();
1905 PyErr_Clear();
1906 }
1907
1908 return MakeScriptObject(py_return);
1909}
1910
1911lldb::ScriptInterpreterObjectSP
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001912ScriptInterpreterPython::CreateSyntheticScriptedProvider (std::string class_name,
1913 lldb::ValueObjectSP valobj)
1914{
1915 if (class_name.empty())
Enrico Granata400105d2012-03-06 23:42:15 +00001916 return lldb::ScriptInterpreterObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001917
1918 if (!valobj.get())
Enrico Granata400105d2012-03-06 23:42:15 +00001919 return lldb::ScriptInterpreterObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001920
Greg Claytonb4d7fc02012-02-17 07:49:44 +00001921 ExecutionContext exe_ctx (valobj->GetExecutionContextRef());
1922 Target *target = exe_ctx.GetTargetPtr();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001923
1924 if (!target)
Enrico Granata400105d2012-03-06 23:42:15 +00001925 return lldb::ScriptInterpreterObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001926
1927 Debugger &debugger = target->GetDebugger();
1928 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1929 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1930
1931 if (!script_interpreter)
Enrico Granata400105d2012-03-06 23:42:15 +00001932 return lldb::ScriptInterpreterObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001933
1934 void* ret_val;
Enrico Granatafa1f6172011-10-24 17:22:21 +00001935
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001936 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001937 Locker py_lock(this);
Enrico Granata3d656c72012-10-22 18:18:36 +00001938 ret_val = g_swig_synthetic_script (class_name,
1939 python_interpreter->m_dictionary_name.c_str(),
1940 valobj);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001941 }
1942
Enrico Granata400105d2012-03-06 23:42:15 +00001943 return MakeScriptObject(ret_val);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001944}
1945
Enrico Granataf7a9b142011-07-15 02:26:42 +00001946bool
Enrico Granata400105d2012-03-06 23:42:15 +00001947ScriptInterpreterPython::GenerateTypeScriptFunction (const char* oneliner, std::string& output, void* name_token)
Enrico Granataf7a9b142011-07-15 02:26:42 +00001948{
Enrico Granata16376ed2012-02-15 02:34:21 +00001949 StringList input;
1950 input.SplitIntoLines(oneliner, strlen(oneliner));
1951 return GenerateTypeScriptFunction(input, output, name_token);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001952}
1953
Chris Lattner24943d22010-06-08 16:52:24 +00001954bool
Enrico Granata400105d2012-03-06 23:42:15 +00001955ScriptInterpreterPython::GenerateTypeSynthClass (const char* oneliner, std::string& output, void* name_token)
Enrico Granata16376ed2012-02-15 02:34:21 +00001956{
1957 StringList input;
1958 input.SplitIntoLines(oneliner, strlen(oneliner));
1959 return GenerateTypeSynthClass(input, output, name_token);
1960}
1961
1962
1963bool
Enrico Granata400105d2012-03-06 23:42:15 +00001964ScriptInterpreterPython::GenerateBreakpointCommandCallbackData (StringList &user_input, std::string& output)
Chris Lattner24943d22010-06-08 16:52:24 +00001965{
Enrico Granata400105d2012-03-06 23:42:15 +00001966 static uint32_t num_created_functions = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001967 user_input.RemoveBlankLines ();
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001968 StreamString sstr;
Chris Lattner24943d22010-06-08 16:52:24 +00001969
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001970 if (user_input.GetSize() == 0)
1971 return false;
1972
Enrico Granata400105d2012-03-06 23:42:15 +00001973 std::string auto_generated_function_name(GenerateUniqueName("lldb_autogen_python_bp_callback_func_",num_created_functions));
Enrico Granatac1ca9dc2012-08-08 02:06:30 +00001974 sstr.Printf ("def %s (frame, bp_loc, internal_dict):", auto_generated_function_name.c_str());
Caroline Tice0aa2e552011-01-14 00:29:16 +00001975
Enrico Granata400105d2012-03-06 23:42:15 +00001976 if (!GenerateFunction(sstr.GetData(), user_input))
Caroline Ticeb447e842010-09-21 19:25:28 +00001977 return false;
Enrico Granata400105d2012-03-06 23:42:15 +00001978
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001979 // Store the name of the auto-generated function to be called.
Enrico Granata400105d2012-03-06 23:42:15 +00001980 output.assign(auto_generated_function_name);
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001981 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001982}
1983
Enrico Granata1328b142012-02-29 03:28:49 +00001984bool
Johnny Chenf3ec4612012-08-09 23:09:42 +00001985ScriptInterpreterPython::GenerateWatchpointCommandCallbackData (StringList &user_input, std::string& output)
1986{
1987 static uint32_t num_created_functions = 0;
1988 user_input.RemoveBlankLines ();
1989 StreamString sstr;
1990
1991 if (user_input.GetSize() == 0)
1992 return false;
1993
1994 std::string auto_generated_function_name(GenerateUniqueName("lldb_autogen_python_wp_callback_func_",num_created_functions));
1995 sstr.Printf ("def %s (frame, wp, internal_dict):", auto_generated_function_name.c_str());
1996
1997 if (!GenerateFunction(sstr.GetData(), user_input))
1998 return false;
1999
2000 // Store the name of the auto-generated function to be called.
2001 output.assign(auto_generated_function_name);
2002 return true;
2003}
2004
2005bool
Enrico Granata1328b142012-02-29 03:28:49 +00002006ScriptInterpreterPython::GetScriptedSummary (const char *python_function_name,
2007 lldb::ValueObjectSP valobj,
2008 lldb::ScriptInterpreterObjectSP& callee_wrapper_sp,
2009 std::string& retval)
Enrico Granataf7a9b142011-07-15 02:26:42 +00002010{
2011
Enrico Granata1328b142012-02-29 03:28:49 +00002012 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
Enrico Granataf7a9b142011-07-15 02:26:42 +00002013
2014 if (!valobj.get())
Enrico Granata1328b142012-02-29 03:28:49 +00002015 {
2016 retval.assign("<no object>");
2017 return false;
2018 }
Enrico Granataf7a9b142011-07-15 02:26:42 +00002019
Enrico Granata1328b142012-02-29 03:28:49 +00002020 void* old_callee = (callee_wrapper_sp ? callee_wrapper_sp->GetObject() : NULL);
2021 void* new_callee = old_callee;
Enrico Granataf7a9b142011-07-15 02:26:42 +00002022
Enrico Granata1328b142012-02-29 03:28:49 +00002023 bool ret_val;
Enrico Granataf7a9b142011-07-15 02:26:42 +00002024 if (python_function_name
2025 && *python_function_name)
2026 {
Enrico Granataf7a9b142011-07-15 02:26:42 +00002027 {
Enrico Granata1328b142012-02-29 03:28:49 +00002028 Locker py_lock(this);
2029 {
2030 Timer scoped_timer ("g_swig_typescript_callback","g_swig_typescript_callback");
2031 ret_val = g_swig_typescript_callback (python_function_name,
2032 FindSessionDictionary(m_dictionary_name.c_str()),
2033 valobj,
2034 &new_callee,
2035 retval);
2036 }
Enrico Granataf7a9b142011-07-15 02:26:42 +00002037 }
2038 }
2039 else
Enrico Granata1328b142012-02-29 03:28:49 +00002040 {
2041 retval.assign("<no function name>");
2042 return false;
2043 }
2044
2045 if (new_callee && old_callee != new_callee)
2046 callee_wrapper_sp = MakeScriptObject(new_callee);
Enrico Granataf7a9b142011-07-15 02:26:42 +00002047
2048 return ret_val;
2049
2050}
2051
Greg Clayton5144f382010-10-07 17:14:24 +00002052bool
2053ScriptInterpreterPython::BreakpointCallbackFunction
2054(
2055 void *baton,
2056 StoppointCallbackContext *context,
2057 user_id_t break_id,
2058 user_id_t break_loc_id
2059)
2060{
2061 BreakpointOptions::CommandData *bp_option_data = (BreakpointOptions::CommandData *) baton;
Enrico Granata400105d2012-03-06 23:42:15 +00002062 const char *python_function_name = bp_option_data->script_source.c_str();
Caroline Tice0aa2e552011-01-14 00:29:16 +00002063
2064 if (!context)
2065 return true;
2066
Greg Claytonf4124de2012-02-21 00:09:25 +00002067 ExecutionContext exe_ctx (context->exe_ctx_ref);
2068 Target *target = exe_ctx.GetTargetPtr();
Caroline Tice0aa2e552011-01-14 00:29:16 +00002069
2070 if (!target)
2071 return true;
2072
2073 Debugger &debugger = target->GetDebugger();
2074 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
2075 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
2076
2077 if (!script_interpreter)
2078 return true;
Greg Clayton5144f382010-10-07 17:14:24 +00002079
2080 if (python_function_name != NULL
2081 && python_function_name[0] != '\0')
2082 {
Greg Claytonf4124de2012-02-21 00:09:25 +00002083 const StackFrameSP stop_frame_sp (exe_ctx.GetFrameSP());
Greg Clayton5144f382010-10-07 17:14:24 +00002084 BreakpointSP breakpoint_sp = target->GetBreakpointByID (break_id);
Greg Claytone86cbb92011-03-22 01:14:58 +00002085 if (breakpoint_sp)
Caroline Tice0aa2e552011-01-14 00:29:16 +00002086 {
Greg Claytone86cbb92011-03-22 01:14:58 +00002087 const BreakpointLocationSP bp_loc_sp (breakpoint_sp->FindLocationByID (break_loc_id));
2088
2089 if (stop_frame_sp && bp_loc_sp)
Caroline Tice202f6b82011-01-17 21:55:19 +00002090 {
Greg Claytone86cbb92011-03-22 01:14:58 +00002091 bool ret_val = true;
Greg Claytone86cbb92011-03-22 01:14:58 +00002092 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00002093 Locker py_lock(python_interpreter);
Greg Claytone86cbb92011-03-22 01:14:58 +00002094 ret_val = g_swig_breakpoint_callback (python_function_name,
2095 python_interpreter->m_dictionary_name.c_str(),
2096 stop_frame_sp,
2097 bp_loc_sp);
Greg Claytone86cbb92011-03-22 01:14:58 +00002098 }
2099 return ret_val;
Caroline Tice202f6b82011-01-17 21:55:19 +00002100 }
Caroline Tice0aa2e552011-01-14 00:29:16 +00002101 }
Greg Clayton5144f382010-10-07 17:14:24 +00002102 }
2103 // We currently always true so we stop in case anything goes wrong when
2104 // trying to call the script function
2105 return true;
2106}
Caroline Tice2ade6112010-11-10 19:18:14 +00002107
Johnny Chenf3ec4612012-08-09 23:09:42 +00002108bool
2109ScriptInterpreterPython::WatchpointCallbackFunction
2110(
2111 void *baton,
2112 StoppointCallbackContext *context,
2113 user_id_t watch_id
2114)
2115{
2116 WatchpointOptions::CommandData *wp_option_data = (WatchpointOptions::CommandData *) baton;
2117 const char *python_function_name = wp_option_data->script_source.c_str();
2118
2119 if (!context)
2120 return true;
2121
2122 ExecutionContext exe_ctx (context->exe_ctx_ref);
2123 Target *target = exe_ctx.GetTargetPtr();
2124
2125 if (!target)
2126 return true;
2127
2128 Debugger &debugger = target->GetDebugger();
2129 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
2130 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
2131
2132 if (!script_interpreter)
2133 return true;
2134
2135 if (python_function_name != NULL
2136 && python_function_name[0] != '\0')
2137 {
2138 const StackFrameSP stop_frame_sp (exe_ctx.GetFrameSP());
2139 WatchpointSP wp_sp = target->GetWatchpointList().FindByID (watch_id);
2140 if (wp_sp)
2141 {
2142 if (stop_frame_sp && wp_sp)
2143 {
2144 bool ret_val = true;
2145 {
2146 Locker py_lock(python_interpreter);
2147 ret_val = g_swig_watchpoint_callback (python_function_name,
2148 python_interpreter->m_dictionary_name.c_str(),
2149 stop_frame_sp,
2150 wp_sp);
2151 }
2152 return ret_val;
2153 }
2154 }
2155 }
2156 // We currently always true so we stop in case anything goes wrong when
2157 // trying to call the script function
2158 return true;
2159}
2160
Caroline Tice2ade6112010-11-10 19:18:14 +00002161lldb::thread_result_t
2162ScriptInterpreterPython::RunEmbeddedPythonInterpreter (lldb::thread_arg_t baton)
2163{
2164 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
2165
2166 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
2167
2168 if (log)
2169 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread starting...", baton);
2170
2171 char error_str[1024];
2172 const char *pty_slave_name = script_interpreter->m_embedded_python_pty.GetSlaveName (error_str, sizeof (error_str));
Caroline Tice0aa2e552011-01-14 00:29:16 +00002173
Enrico Granatafa1f6172011-10-24 17:22:21 +00002174 if (pty_slave_name != NULL)
Caroline Tice202f6b82011-01-17 21:55:19 +00002175 {
Caroline Tice2ade6112010-11-10 19:18:14 +00002176 StreamString run_string;
Johnny Chen8165d432012-08-18 04:14:54 +00002177
2178 // Ensure we have the GIL before running any Python code.
2179 // Since we're only running a few one-liners and then dropping to the interpreter (which will release the GIL when needed),
2180 // we can just release the GIL after finishing our work.
2181 // If finer-grained locking is desirable, we can lock and unlock the GIL only when calling a python function.
2182 Locker locker(script_interpreter,
Jim Ingham14e71ec2012-12-07 17:43:38 +00002183 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession | ScriptInterpreterPython::Locker::InitGlobals,
Johnny Chen8165d432012-08-18 04:14:54 +00002184 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
2185
Caroline Tice0aa2e552011-01-14 00:29:16 +00002186 run_string.Printf ("run_one_line (%s, 'save_stderr = sys.stderr')", script_interpreter->m_dictionary_name.c_str());
2187 PyRun_SimpleString (run_string.GetData());
2188 run_string.Clear ();
2189
2190 run_string.Printf ("run_one_line (%s, 'sys.stderr = sys.stdout')", script_interpreter->m_dictionary_name.c_str());
2191 PyRun_SimpleString (run_string.GetData());
2192 run_string.Clear ();
2193
2194 run_string.Printf ("run_one_line (%s, 'save_stdin = sys.stdin')", script_interpreter->m_dictionary_name.c_str());
2195 PyRun_SimpleString (run_string.GetData());
2196 run_string.Clear ();
2197
2198 run_string.Printf ("run_one_line (%s, \"sys.stdin = open ('%s', 'r')\")", script_interpreter->m_dictionary_name.c_str(),
2199 pty_slave_name);
2200 PyRun_SimpleString (run_string.GetData());
2201 run_string.Clear ();
2202
Johnny Chen8054ba32011-03-11 00:28:50 +00002203 // The following call drops into the embedded interpreter loop and stays there until the
2204 // user chooses to exit from the Python interpreter.
Johnny Chen8165d432012-08-18 04:14:54 +00002205 // This embedded interpreter will, as any Python code that performs I/O, unlock the GIL before
2206 // a system call that can hang, and lock it when the syscall has returned.
Caroline Tice0aa2e552011-01-14 00:29:16 +00002207
Johnny Chen8165d432012-08-18 04:14:54 +00002208 // We need to surround the call to the embedded interpreter with calls to PyGILState_Ensure and
2209 // PyGILState_Release (using the Locker above). This is because Python has a global lock which must be held whenever we want
2210 // to touch any Python objects. Otherwise, if the user calls Python code, the interpreter state will be off,
2211 // and things could hang (it's happened before).
Caroline Ticece207c12011-03-11 00:21:55 +00002212
Caroline Tice0aa2e552011-01-14 00:29:16 +00002213 run_string.Printf ("run_python_interpreter (%s)", script_interpreter->m_dictionary_name.c_str());
2214 PyRun_SimpleString (run_string.GetData());
2215 run_string.Clear ();
Johnny Chen8165d432012-08-18 04:14:54 +00002216
Caroline Tice0aa2e552011-01-14 00:29:16 +00002217 run_string.Printf ("run_one_line (%s, 'sys.stdin = save_stdin')", script_interpreter->m_dictionary_name.c_str());
2218 PyRun_SimpleString (run_string.GetData());
2219 run_string.Clear();
Johnny Chen8165d432012-08-18 04:14:54 +00002220
Caroline Tice0aa2e552011-01-14 00:29:16 +00002221 run_string.Printf ("run_one_line (%s, 'sys.stderr = save_stderr')", script_interpreter->m_dictionary_name.c_str());
2222 PyRun_SimpleString (run_string.GetData());
2223 run_string.Clear();
Caroline Tice2ade6112010-11-10 19:18:14 +00002224 }
2225
Johnny Chen8121d7a2012-08-17 23:44:35 +00002226 if (script_interpreter->m_embedded_python_input_reader_sp)
2227 script_interpreter->m_embedded_python_input_reader_sp->SetIsDone (true);
Caroline Tice2ade6112010-11-10 19:18:14 +00002228
2229 script_interpreter->m_embedded_python_pty.CloseSlaveFileDescriptor();
Caroline Tice0aa2e552011-01-14 00:29:16 +00002230
Caroline Tice2ade6112010-11-10 19:18:14 +00002231 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT);
2232 if (log)
2233 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread exiting...", baton);
2234
2235
Johnny Chen8054ba32011-03-11 00:28:50 +00002236 // Clean up the input reader and make the debugger pop it off the stack.
Caroline Tice0aa2e552011-01-14 00:29:16 +00002237 Debugger &debugger = script_interpreter->GetCommandInterpreter().GetDebugger();
Johnny Chen8121d7a2012-08-17 23:44:35 +00002238 const InputReaderSP reader_sp = script_interpreter->m_embedded_python_input_reader_sp;
2239 if (reader_sp)
2240 {
2241 debugger.PopInputReader (reader_sp);
2242 script_interpreter->m_embedded_python_input_reader_sp.reset();
2243 }
Caroline Tice0aa2e552011-01-14 00:29:16 +00002244
Caroline Tice2ade6112010-11-10 19:18:14 +00002245 return NULL;
2246}
2247
Enrico Granataa1ba3142012-06-07 00:17:18 +00002248lldb::thread_result_t
2249ScriptInterpreterPython::PythonInputReaderManager::RunPythonInputReader (lldb::thread_arg_t baton)
2250{
2251 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
2252
2253 const InputReaderSP reader_sp = script_interpreter->m_embedded_thread_input_reader_sp;
2254
2255 if (reader_sp)
2256 reader_sp->WaitOnReaderIsDone();
2257
2258 return NULL;
2259}
2260
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002261uint32_t
Enrico Granata400105d2012-03-06 23:42:15 +00002262ScriptInterpreterPython::CalculateNumChildren (const lldb::ScriptInterpreterObjectSP& implementor_sp)
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002263{
Enrico Granata400105d2012-03-06 23:42:15 +00002264 if (!implementor_sp)
2265 return 0;
2266
2267 void* implementor = implementor_sp->GetObject();
2268
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002269 if (!implementor)
2270 return 0;
2271
2272 if (!g_swig_calc_children)
2273 return 0;
Enrico Granatafa1f6172011-10-24 17:22:21 +00002274
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002275 uint32_t ret_val = 0;
2276
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002277 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00002278 Locker py_lock(this);
Enrico Granata3d656c72012-10-22 18:18:36 +00002279 ret_val = g_swig_calc_children (implementor);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002280 }
2281
2282 return ret_val;
2283}
2284
Enrico Granata91544802011-09-06 19:20:51 +00002285lldb::ValueObjectSP
Enrico Granata400105d2012-03-06 23:42:15 +00002286ScriptInterpreterPython::GetChildAtIndex (const lldb::ScriptInterpreterObjectSP& implementor_sp, uint32_t idx)
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002287{
Enrico Granata400105d2012-03-06 23:42:15 +00002288 if (!implementor_sp)
2289 return lldb::ValueObjectSP();
2290
2291 void* implementor = implementor_sp->GetObject();
2292
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002293 if (!implementor)
Enrico Granata91544802011-09-06 19:20:51 +00002294 return lldb::ValueObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002295
Enrico Granata91544802011-09-06 19:20:51 +00002296 if (!g_swig_get_child_index || !g_swig_cast_to_sbvalue)
2297 return lldb::ValueObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002298
Enrico Granata91544802011-09-06 19:20:51 +00002299 void* child_ptr = NULL;
2300 lldb::SBValue* value_sb = NULL;
2301 lldb::ValueObjectSP ret_val;
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002302
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002303 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00002304 Locker py_lock(this);
Enrico Granata3d656c72012-10-22 18:18:36 +00002305 child_ptr = g_swig_get_child_index (implementor,idx);
Enrico Granata91544802011-09-06 19:20:51 +00002306 if (child_ptr != NULL && child_ptr != Py_None)
2307 {
2308 value_sb = (lldb::SBValue*)g_swig_cast_to_sbvalue(child_ptr);
2309 if (value_sb == NULL)
2310 Py_XDECREF(child_ptr);
2311 else
Greg Claytoneeabe812012-11-01 21:35:16 +00002312 ret_val = value_sb->GetSP();
Enrico Granata91544802011-09-06 19:20:51 +00002313 }
2314 else
2315 {
2316 Py_XDECREF(child_ptr);
2317 }
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002318 }
2319
2320 return ret_val;
2321}
2322
2323int
Enrico Granata400105d2012-03-06 23:42:15 +00002324ScriptInterpreterPython::GetIndexOfChildWithName (const lldb::ScriptInterpreterObjectSP& implementor_sp, const char* child_name)
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002325{
Enrico Granata400105d2012-03-06 23:42:15 +00002326 if (!implementor_sp)
2327 return UINT32_MAX;
2328
2329 void* implementor = implementor_sp->GetObject();
2330
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002331 if (!implementor)
2332 return UINT32_MAX;
2333
2334 if (!g_swig_get_index_child)
2335 return UINT32_MAX;
2336
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002337 int ret_val = UINT32_MAX;
2338
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002339 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00002340 Locker py_lock(this);
Enrico Granata3d656c72012-10-22 18:18:36 +00002341 ret_val = g_swig_get_index_child (implementor, child_name);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002342 }
2343
2344 return ret_val;
2345}
2346
Enrico Granatacf09f882012-03-19 22:58:49 +00002347bool
Enrico Granata400105d2012-03-06 23:42:15 +00002348ScriptInterpreterPython::UpdateSynthProviderInstance (const lldb::ScriptInterpreterObjectSP& implementor_sp)
Enrico Granata979e20d2011-07-29 19:53:35 +00002349{
Enrico Granatacf09f882012-03-19 22:58:49 +00002350 bool ret_val = false;
2351
Enrico Granata400105d2012-03-06 23:42:15 +00002352 if (!implementor_sp)
Enrico Granatacf09f882012-03-19 22:58:49 +00002353 return ret_val;
Enrico Granata400105d2012-03-06 23:42:15 +00002354
2355 void* implementor = implementor_sp->GetObject();
2356
Enrico Granata979e20d2011-07-29 19:53:35 +00002357 if (!implementor)
Enrico Granatacf09f882012-03-19 22:58:49 +00002358 return ret_val;
Enrico Granata979e20d2011-07-29 19:53:35 +00002359
2360 if (!g_swig_update_provider)
Enrico Granatacf09f882012-03-19 22:58:49 +00002361 return ret_val;
Enrico Granata979e20d2011-07-29 19:53:35 +00002362
Enrico Granata979e20d2011-07-29 19:53:35 +00002363 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00002364 Locker py_lock(this);
Enrico Granata3d656c72012-10-22 18:18:36 +00002365 ret_val = g_swig_update_provider (implementor);
Enrico Granata979e20d2011-07-29 19:53:35 +00002366 }
2367
Enrico Granatacf09f882012-03-19 22:58:49 +00002368 return ret_val;
Enrico Granata979e20d2011-07-29 19:53:35 +00002369}
2370
Enrico Granatac2a28252011-08-16 16:49:25 +00002371bool
Enrico Granata800332c2012-10-23 19:54:09 +00002372ScriptInterpreterPython::MightHaveChildrenSynthProviderInstance (const lldb::ScriptInterpreterObjectSP& implementor_sp)
2373{
2374 bool ret_val = false;
2375
2376 if (!implementor_sp)
2377 return ret_val;
2378
2379 void* implementor = implementor_sp->GetObject();
2380
2381 if (!implementor)
2382 return ret_val;
2383
2384 if (!g_swig_mighthavechildren_provider)
2385 return ret_val;
2386
2387 {
2388 Locker py_lock(this);
2389 ret_val = g_swig_mighthavechildren_provider (implementor);
2390 }
2391
2392 return ret_val;
2393}
2394
Enrico Granata9ac7ce32012-11-30 20:15:16 +00002395static std::string
2396ReadPythonBacktrace (PyObject* py_backtrace)
2397{
2398 PyObject* traceback_module = NULL,
2399 *stringIO_module = NULL,
2400 *stringIO_builder = NULL,
2401 *stringIO_buffer = NULL,
2402 *printTB = NULL,
2403 *printTB_args = NULL,
2404 *printTB_result = NULL,
2405 *stringIO_getvalue = NULL,
2406 *printTB_string = NULL;
2407
2408 std::string retval("backtrace unavailable");
2409
2410 if (py_backtrace && py_backtrace != Py_None)
2411 {
2412 traceback_module = PyImport_ImportModule("traceback");
2413 stringIO_module = PyImport_ImportModule("StringIO");
2414
2415 if (traceback_module && traceback_module != Py_None && stringIO_module && stringIO_module != Py_None)
2416 {
2417 stringIO_builder = PyObject_GetAttrString(stringIO_module, "StringIO");
2418 if (stringIO_builder && stringIO_builder != Py_None)
2419 {
2420 stringIO_buffer = PyObject_CallObject(stringIO_builder, NULL);
2421 if (stringIO_buffer && stringIO_buffer != Py_None)
2422 {
2423 printTB = PyObject_GetAttrString(traceback_module, "print_tb");
2424 if (printTB && printTB != Py_None)
2425 {
2426 printTB_args = Py_BuildValue("OOO",py_backtrace,Py_None,stringIO_buffer);
2427 printTB_result = PyObject_CallObject(printTB, printTB_args);
2428 stringIO_getvalue = PyObject_GetAttrString(stringIO_buffer, "getvalue");
2429 if (stringIO_getvalue && stringIO_getvalue != Py_None)
2430 {
2431 printTB_string = PyObject_CallObject (stringIO_getvalue,NULL);
2432 if (printTB_string && printTB_string != Py_None && PyString_Check(printTB_string))
2433 retval.assign(PyString_AsString(printTB_string));
2434 }
2435 }
2436 }
2437 }
2438 }
2439 }
2440 Py_XDECREF(traceback_module);
2441 Py_XDECREF(stringIO_module);
2442 Py_XDECREF(stringIO_builder);
2443 Py_XDECREF(stringIO_buffer);
2444 Py_XDECREF(printTB);
2445 Py_XDECREF(printTB_args);
2446 Py_XDECREF(printTB_result);
2447 Py_XDECREF(stringIO_getvalue);
2448 Py_XDECREF(printTB_string);
2449 return retval;
2450}
2451
Enrico Granata800332c2012-10-23 19:54:09 +00002452bool
Enrico Granata59df36f2011-10-17 21:45:27 +00002453ScriptInterpreterPython::LoadScriptingModule (const char* pathname,
Enrico Granata6010ace2011-11-07 22:57:04 +00002454 bool can_reload,
Jim Ingham14e71ec2012-12-07 17:43:38 +00002455 bool init_session,
Enrico Granata59df36f2011-10-17 21:45:27 +00002456 lldb_private::Error& error)
2457{
2458 if (!pathname || !pathname[0])
2459 {
2460 error.SetErrorString("invalid pathname");
2461 return false;
2462 }
2463
2464 if (!g_swig_call_module_init)
2465 {
2466 error.SetErrorString("internal helper function missing");
2467 return false;
2468 }
2469
Greg Clayton13d24fb2012-01-29 20:56:30 +00002470 lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().shared_from_this();
Enrico Granatafa1f6172011-10-24 17:22:21 +00002471
Enrico Granata59df36f2011-10-17 21:45:27 +00002472 {
Enrico Granata59df36f2011-10-17 21:45:27 +00002473 FileSpec target_file(pathname, true);
2474
2475 // TODO: would we want to reject any other value?
2476 if (target_file.GetFileType() == FileSpec::eFileTypeInvalid ||
2477 target_file.GetFileType() == FileSpec::eFileTypeUnknown)
2478 {
2479 error.SetErrorString("invalid pathname");
2480 return false;
2481 }
2482
2483 const char* directory = target_file.GetDirectory().GetCString();
2484 std::string basename(target_file.GetFilename().GetCString());
Johnny Chen8165d432012-08-18 04:14:54 +00002485
2486 // Before executing Pyton code, lock the GIL.
Greg Clayton2e7f3132012-10-18 22:40:37 +00002487 Locker py_lock (this,
Jim Ingham14e71ec2012-12-07 17:43:38 +00002488 Locker::AcquireLock | (init_session ? Locker::InitSession : 0),
2489 Locker::FreeAcquiredLock | (init_session ? Locker::TearDownSession : 0));
Enrico Granata59df36f2011-10-17 21:45:27 +00002490
2491 // now make sure that Python has "directory" in the search path
2492 StreamString command_stream;
Enrico Granata6f58bbd2012-11-08 02:44:10 +00002493 command_stream.Printf("if not (sys.path.__contains__('%s')):\n sys.path.insert(1,'%s');\n\n",
Enrico Granata59df36f2011-10-17 21:45:27 +00002494 directory,
2495 directory);
Enrico Granatafd670c22012-10-31 00:01:26 +00002496 bool syspath_retval = ExecuteMultipleLines(command_stream.GetData(), ScriptInterpreter::ExecuteScriptOptions().SetEnableIO(false).SetSetLLDBGlobals(false));
Enrico Granata59df36f2011-10-17 21:45:27 +00002497 if (!syspath_retval)
2498 {
2499 error.SetErrorString("Python sys.path handling failed");
2500 return false;
2501 }
2502
2503 // strip .py or .pyc extension
2504 ConstString extension = target_file.GetFileNameExtension();
Sean Callanan3e1d95d2012-12-03 21:28:37 +00002505 if (extension)
2506 {
2507 if (::strcmp(extension.GetCString(), "py") == 0)
2508 basename.resize(basename.length()-3);
2509 else if(::strcmp(extension.GetCString(), "pyc") == 0)
2510 basename.resize(basename.length()-4);
2511 }
Enrico Granata59df36f2011-10-17 21:45:27 +00002512
2513 // check if the module is already import-ed
2514 command_stream.Clear();
2515 command_stream.Printf("sys.getrefcount(%s)",basename.c_str());
2516 int refcount = 0;
2517 // this call will fail if the module does not exist (because the parameter to it is not a string
2518 // but an actual Python module object, which is non-existant if the module was not imported before)
Enrico Granata6010ace2011-11-07 22:57:04 +00002519 bool was_imported = (ExecuteOneLineWithReturn(command_stream.GetData(),
Greg Clayton2e7f3132012-10-18 22:40:37 +00002520 ScriptInterpreterPython::eScriptReturnTypeInt,
2521 &refcount,
Enrico Granatafd670c22012-10-31 00:01:26 +00002522 ScriptInterpreter::ExecuteScriptOptions().SetEnableIO(false).SetSetLLDBGlobals(false)) && refcount > 0);
Enrico Granata6010ace2011-11-07 22:57:04 +00002523 if (was_imported == true && can_reload == false)
Enrico Granata59df36f2011-10-17 21:45:27 +00002524 {
2525 error.SetErrorString("module already imported");
2526 return false;
2527 }
2528
2529 // now actually do the import
2530 command_stream.Clear();
2531 command_stream.Printf("import %s",basename.c_str());
Enrico Granatafd670c22012-10-31 00:01:26 +00002532 bool import_retval = ExecuteMultipleLines(command_stream.GetData(), ScriptInterpreter::ExecuteScriptOptions().SetEnableIO(false).SetSetLLDBGlobals(false).SetMaskoutErrors(false));
2533 PyObject* py_error = PyErr_Occurred(); // per Python docs: "you do not need to Py_DECREF()" the return of this function
2534
2535 if (py_error || !import_retval) // check for failure of the import
Enrico Granata59df36f2011-10-17 21:45:27 +00002536 {
Enrico Granatafd670c22012-10-31 00:01:26 +00002537 if (py_error) // if we have a Python error..
2538 {
Enrico Granata9ac7ce32012-11-30 20:15:16 +00002539 PyObject *type = NULL,*value = NULL,*traceback = NULL;
2540 PyErr_Fetch (&type,&value,&traceback);
2541
Enrico Granatafd670c22012-10-31 00:01:26 +00002542 if (PyErr_GivenExceptionMatches (py_error, PyExc_ImportError)) // and it is an ImportError
2543 {
Enrico Granatafd670c22012-10-31 00:01:26 +00002544 if (value && value != Py_None)
2545 error.SetErrorString(PyString_AsString(PyObject_Str(value)));
2546 else
2547 error.SetErrorString("ImportError raised by imported module");
Enrico Granatafd670c22012-10-31 00:01:26 +00002548 }
2549 else // any other error
2550 {
Enrico Granata9ac7ce32012-11-30 20:15:16 +00002551 // get the backtrace
2552 std::string bt = ReadPythonBacktrace(traceback);
Enrico Granata6cc99d22012-11-13 02:57:43 +00002553
2554 if (value && value != Py_None)
Enrico Granata9ac7ce32012-11-30 20:15:16 +00002555 error.SetErrorStringWithFormat("Python error raised while importing module: %s - traceback: %s", PyString_AsString(PyObject_Str(value)),bt.c_str());
Enrico Granata6cc99d22012-11-13 02:57:43 +00002556 else
Enrico Granata9ac7ce32012-11-30 20:15:16 +00002557 error.SetErrorStringWithFormat("Python raised an error while importing module - traceback: %s",bt.c_str());
Enrico Granatafd670c22012-10-31 00:01:26 +00002558 }
Enrico Granata9ac7ce32012-11-30 20:15:16 +00002559
2560 Py_XDECREF(type);
2561 Py_XDECREF(value);
2562 Py_XDECREF(traceback);
Enrico Granatafd670c22012-10-31 00:01:26 +00002563 }
2564 else // we failed but have no error to explain why
2565 {
2566 error.SetErrorString("unknown error while importing module");
2567 }
2568
2569 // anyway, clear the error indicator and return false
2570 PyErr_Clear();
Enrico Granata59df36f2011-10-17 21:45:27 +00002571 return false;
2572 }
2573
Enrico Granatafd670c22012-10-31 00:01:26 +00002574 // if we are here, everything worked
Enrico Granata16376ed2012-02-15 02:34:21 +00002575 // call __lldb_init_module(debugger,dict)
Enrico Granata59df36f2011-10-17 21:45:27 +00002576 if (!g_swig_call_module_init (basename,
Enrico Granatafa1f6172011-10-24 17:22:21 +00002577 m_dictionary_name.c_str(),
Enrico Granata59df36f2011-10-17 21:45:27 +00002578 debugger_sp))
2579 {
Enrico Granata16376ed2012-02-15 02:34:21 +00002580 error.SetErrorString("calling __lldb_init_module failed");
Enrico Granata59df36f2011-10-17 21:45:27 +00002581 return false;
2582 }
2583 return true;
2584 }
2585}
2586
Enrico Granata1328b142012-02-29 03:28:49 +00002587lldb::ScriptInterpreterObjectSP
2588ScriptInterpreterPython::MakeScriptObject (void* object)
2589{
2590 return lldb::ScriptInterpreterObjectSP(new ScriptInterpreterPythonObject(object));
2591}
2592
Enrico Granata6010ace2011-11-07 22:57:04 +00002593ScriptInterpreterPython::SynchronicityHandler::SynchronicityHandler (lldb::DebuggerSP debugger_sp,
2594 ScriptedCommandSynchronicity synchro) :
2595 m_debugger_sp(debugger_sp),
2596 m_synch_wanted(synchro),
2597 m_old_asynch(debugger_sp->GetAsyncExecution())
2598{
2599 if (m_synch_wanted == eScriptedCommandSynchronicitySynchronous)
2600 m_debugger_sp->SetAsyncExecution(false);
2601 else if (m_synch_wanted == eScriptedCommandSynchronicityAsynchronous)
2602 m_debugger_sp->SetAsyncExecution(true);
2603}
2604
2605ScriptInterpreterPython::SynchronicityHandler::~SynchronicityHandler()
2606{
2607 if (m_synch_wanted != eScriptedCommandSynchronicityCurrentValue)
2608 m_debugger_sp->SetAsyncExecution(m_old_asynch);
2609}
2610
Enrico Granata59df36f2011-10-17 21:45:27 +00002611bool
Enrico Granatac2a28252011-08-16 16:49:25 +00002612ScriptInterpreterPython::RunScriptBasedCommand(const char* impl_function,
2613 const char* args,
Enrico Granata6010ace2011-11-07 22:57:04 +00002614 ScriptedCommandSynchronicity synchronicity,
Enrico Granata6b1596d2011-08-16 23:24:13 +00002615 lldb_private::CommandReturnObject& cmd_retobj,
Enrico Granatac2a28252011-08-16 16:49:25 +00002616 Error& error)
2617{
2618 if (!impl_function)
2619 {
2620 error.SetErrorString("no function to execute");
2621 return false;
2622 }
2623
2624 if (!g_swig_call_command)
2625 {
2626 error.SetErrorString("no helper function to run scripted commands");
2627 return false;
2628 }
2629
Greg Clayton13d24fb2012-01-29 20:56:30 +00002630 lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().shared_from_this();
Enrico Granata6010ace2011-11-07 22:57:04 +00002631
2632 if (!debugger_sp.get())
2633 {
2634 error.SetErrorString("invalid Debugger pointer");
2635 return false;
2636 }
Enrico Granatac2a28252011-08-16 16:49:25 +00002637
2638 bool ret_val;
2639
2640 std::string err_msg;
Enrico Granata6010ace2011-11-07 22:57:04 +00002641
Enrico Granatac2a28252011-08-16 16:49:25 +00002642 {
Jim Ingham14e71ec2012-12-07 17:43:38 +00002643 Locker py_lock(this,
2644 Locker::AcquireLock | Locker::InitSession | Locker::InitGlobals,
2645 Locker::FreeLock | Locker::TearDownSession);
Enrico Granata6010ace2011-11-07 22:57:04 +00002646 SynchronicityHandler synch_handler(debugger_sp,
2647 synchronicity);
2648
Enrico Granataa1ba3142012-06-07 00:17:18 +00002649 PythonInputReaderManager py_input(this);
2650
Enrico Granatac2a28252011-08-16 16:49:25 +00002651 ret_val = g_swig_call_command (impl_function,
Enrico Granatafa1f6172011-10-24 17:22:21 +00002652 m_dictionary_name.c_str(),
Enrico Granatac2a28252011-08-16 16:49:25 +00002653 debugger_sp,
2654 args,
2655 err_msg,
Enrico Granata3370f0c2011-08-19 23:56:34 +00002656 cmd_retobj);
Enrico Granatac2a28252011-08-16 16:49:25 +00002657 }
Enrico Granata6010ace2011-11-07 22:57:04 +00002658
Enrico Granatac2a28252011-08-16 16:49:25 +00002659 if (!ret_val)
2660 error.SetErrorString(err_msg.c_str());
2661 else
2662 error.Clear();
Enrico Granata6010ace2011-11-07 22:57:04 +00002663
Enrico Granatac2a28252011-08-16 16:49:25 +00002664 return ret_val;
Enrico Granatac2a28252011-08-16 16:49:25 +00002665}
2666
Enrico Granatae5e34cb2011-08-17 01:30:04 +00002667// in Python, a special attribute __doc__ contains the docstring
2668// for an object (function, method, class, ...) if any is defined
2669// Otherwise, the attribute's value is None
Enrico Granata5b9f7772012-09-18 21:53:02 +00002670bool
2671ScriptInterpreterPython::GetDocumentationForItem(const char* item, std::string& dest)
Enrico Granatae5e34cb2011-08-17 01:30:04 +00002672{
Enrico Granata5b9f7772012-09-18 21:53:02 +00002673 dest.clear();
2674 if (!item || !*item)
2675 return false;
Enrico Granatae5e34cb2011-08-17 01:30:04 +00002676 std::string command(item);
2677 command += ".__doc__";
2678
2679 char* result_ptr = NULL; // Python is going to point this to valid data if ExecuteOneLineWithReturn returns successfully
2680
2681 if (ExecuteOneLineWithReturn (command.c_str(),
Enrico Granata59df36f2011-10-17 21:45:27 +00002682 ScriptInterpreter::eScriptReturnTypeCharStrOrNone,
Enrico Granatafd670c22012-10-31 00:01:26 +00002683 &result_ptr, ScriptInterpreter::ExecuteScriptOptions().SetEnableIO(false) /*.SetSetLLDBGlobals(false)*/))
Enrico Granatae5e34cb2011-08-17 01:30:04 +00002684 {
Enrico Granatab2c0a122012-09-20 23:23:55 +00002685 if (result_ptr)
2686 dest.assign(result_ptr);
Enrico Granata5b9f7772012-09-18 21:53:02 +00002687 return true;
Enrico Granatae5e34cb2011-08-17 01:30:04 +00002688 }
2689 else
Enrico Granata5b9f7772012-09-18 21:53:02 +00002690 {
2691 StreamString str_stream;
2692 str_stream.Printf("Function %s was not found. Containing module might be missing.",item);
2693 dest.assign(str_stream.GetData());
2694 return false;
2695 }
Enrico Granatae5e34cb2011-08-17 01:30:04 +00002696}
Caroline Tice2ade6112010-11-10 19:18:14 +00002697
Caroline Tice0aa2e552011-01-14 00:29:16 +00002698void
Enrico Granata1328b142012-02-29 03:28:49 +00002699ScriptInterpreterPython::InitializeInterpreter (SWIGInitCallback python_swig_init_callback)
Greg Claytone86cbb92011-03-22 01:14:58 +00002700{
2701 g_swig_init_callback = python_swig_init_callback;
Enrico Granata1328b142012-02-29 03:28:49 +00002702 g_swig_breakpoint_callback = LLDBSwigPythonBreakpointCallbackFunction;
Johnny Chenf3ec4612012-08-09 23:09:42 +00002703 g_swig_watchpoint_callback = LLDBSwigPythonWatchpointCallbackFunction;
Enrico Granata1328b142012-02-29 03:28:49 +00002704 g_swig_typescript_callback = LLDBSwigPythonCallTypeScript;
2705 g_swig_synthetic_script = LLDBSwigPythonCreateSyntheticProvider;
2706 g_swig_calc_children = LLDBSwigPython_CalculateNumChildren;
2707 g_swig_get_child_index = LLDBSwigPython_GetChildAtIndex;
2708 g_swig_get_index_child = LLDBSwigPython_GetIndexOfChildWithName;
2709 g_swig_cast_to_sbvalue = LLDBSWIGPython_CastPyObjectToSBValue;
2710 g_swig_update_provider = LLDBSwigPython_UpdateSynthProviderInstance;
Enrico Granata800332c2012-10-23 19:54:09 +00002711 g_swig_mighthavechildren_provider = LLDBSwigPython_MightHaveChildrenSynthProviderInstance;
Enrico Granata1328b142012-02-29 03:28:49 +00002712 g_swig_call_command = LLDBSwigPythonCallCommand;
2713 g_swig_call_module_init = LLDBSwigPythonCallModuleInit;
Enrico Granata155ee912012-08-24 00:30:47 +00002714 g_swig_create_os_plugin = LLDBSWIGPythonCreateOSPlugin;
Greg Claytone86cbb92011-03-22 01:14:58 +00002715}
2716
2717void
2718ScriptInterpreterPython::InitializePrivate ()
Caroline Tice0aa2e552011-01-14 00:29:16 +00002719{
Caroline Tice0aa2e552011-01-14 00:29:16 +00002720 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
2721
Greg Clayton0fdd4a02011-02-07 23:24:47 +00002722 // Python will muck with STDIN terminal state, so save off any current TTY
2723 // settings so we can restore them.
2724 TerminalState stdin_tty_state;
2725 stdin_tty_state.Save(STDIN_FILENO, false);
Caroline Tice0aa2e552011-01-14 00:29:16 +00002726
Johnny Chen8165d432012-08-18 04:14:54 +00002727 PyGILState_STATE gstate;
2728 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT | LIBLLDB_LOG_VERBOSE));
2729 bool threads_already_initialized = false;
2730 if (PyEval_ThreadsInitialized ()) {
2731 gstate = PyGILState_Ensure ();
2732 if (log)
2733 log->Printf("Ensured PyGILState. Previous state = %slocked\n", gstate == PyGILState_UNLOCKED ? "un" : "");
2734 threads_already_initialized = true;
2735 } else {
2736 // InitThreads acquires the GIL if it hasn't been called before.
2737 PyEval_InitThreads ();
2738 }
Caroline Ticea54461d2011-06-02 22:09:43 +00002739 Py_InitializeEx (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00002740
Greg Claytone86cbb92011-03-22 01:14:58 +00002741 // Initialize SWIG after setting up python
2742 assert (g_swig_init_callback != NULL);
2743 g_swig_init_callback ();
Caroline Tice0aa2e552011-01-14 00:29:16 +00002744
2745 // Update the path python uses to search for modules to include the current directory.
2746
Caroline Ticed4d92832011-06-13 21:33:00 +00002747 PyRun_SimpleString ("import sys");
2748 PyRun_SimpleString ("sys.path.append ('.')");
Jim Ingham2a19ef92011-08-27 01:24:08 +00002749
2750 // Find the module that owns this code and use that path we get to
2751 // set the sys.path appropriately.
2752
2753 FileSpec file_spec;
2754 char python_dir_path[PATH_MAX];
2755 if (Host::GetLLDBPath (ePathTypePythonDir, file_spec))
2756 {
2757 std::string python_path("sys.path.insert(0,\"");
2758 size_t orig_len = python_path.length();
2759 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
2760 {
2761 python_path.append (python_dir_path);
2762 python_path.append ("\")");
2763 PyRun_SimpleString (python_path.c_str());
2764 python_path.resize (orig_len);
2765 }
2766
2767 if (Host::GetLLDBPath (ePathTypeLLDBShlibDir, file_spec))
2768 {
2769 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
2770 {
2771 python_path.append (python_dir_path);
2772 python_path.append ("\")");
2773 PyRun_SimpleString (python_path.c_str());
2774 python_path.resize (orig_len);
2775 }
2776 }
2777 }
2778
Greg Clayton4e651b12012-04-25 00:58:03 +00002779 PyRun_SimpleString ("sys.dont_write_bytecode = 1; import lldb.embedded_interpreter; from lldb.embedded_interpreter import run_python_interpreter; from lldb.embedded_interpreter import run_one_line; from termios import *");
Greg Clayton99208582011-02-07 19:04:58 +00002780
Johnny Chen8165d432012-08-18 04:14:54 +00002781 if (threads_already_initialized) {
2782 if (log)
2783 log->Printf("Releasing PyGILState. Returning to state = %slocked\n", gstate == PyGILState_UNLOCKED ? "un" : "");
2784 PyGILState_Release (gstate);
2785 } else {
2786 // We initialized the threads in this function, just unlock the GIL.
2787 PyEval_SaveThread();
2788 }
2789
Greg Clayton0fdd4a02011-02-07 23:24:47 +00002790 stdin_tty_state.Restore();
Caroline Tice0aa2e552011-01-14 00:29:16 +00002791}
2792
Greg Claytone86cbb92011-03-22 01:14:58 +00002793//void
2794//ScriptInterpreterPython::Terminate ()
2795//{
2796// // We are intentionally NOT calling Py_Finalize here (this would be the logical place to call it). Calling
2797// // Py_Finalize here causes test suite runs to seg fault: The test suite runs in Python. It registers
2798// // SBDebugger::Terminate to be called 'at_exit'. When the test suite Python harness finishes up, it calls
2799// // Py_Finalize, which calls all the 'at_exit' registered functions. SBDebugger::Terminate calls Debugger::Terminate,
2800// // which calls lldb::Terminate, which calls ScriptInterpreter::Terminate, which calls
2801// // ScriptInterpreterPython::Terminate. So if we call Py_Finalize here, we end up with Py_Finalize being called from
2802// // within Py_Finalize, which results in a seg fault.
2803// //
2804// // Since this function only gets called when lldb is shutting down and going away anyway, the fact that we don't
2805// // actually call Py_Finalize should not cause any problems (everything should shut down/go away anyway when the
2806// // process exits).
2807// //
2808//// Py_Finalize ();
2809//}
Greg Clayton3e4238d2011-11-04 03:34:56 +00002810
2811#endif // #ifdef LLDB_DISABLE_PYTHON