blob: 7a12a9e6862b2a00cd302f9d42db686597ea42d9 [file] [log] [blame]
Chris Lattner30fdc8d2010-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 Kramer16954662011-10-23 16:49:03 +000011// the *FIRST* header file included here.
Greg Claytondce502e2011-11-04 03:34:56 +000012#ifdef LLDB_DISABLE_PYTHON
13
14// Python is disabled in this build
15
16#else
Benjamin Kramer16954662011-10-23 16:49:03 +000017
18#if defined (__APPLE__)
19#include <Python/Python.h>
20#else
21#include <Python.h>
22#endif
Chris Lattner30fdc8d2010-06-08 16:52:24 +000023
24#include "lldb/Interpreter/ScriptInterpreterPython.h"
25
Chris Lattner30fdc8d2010-06-08 16:52:24 +000026#include <stdlib.h>
27#include <stdio.h>
28
29#include <string>
30
Enrico Granata9128ee22011-09-06 19:20:51 +000031#include "lldb/API/SBValue.h"
Greg Clayton4d122c42011-09-17 08:33:22 +000032#include "lldb/Breakpoint/BreakpointLocation.h"
Greg Clayton66111032010-06-23 01:19:29 +000033#include "lldb/Breakpoint/StoppointCallbackContext.h"
Johnny Chene9a56272012-08-09 23:09:42 +000034#include "lldb/Breakpoint/WatchpointOptions.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000035#include "lldb/Core/Debugger.h"
Chris Lattner30fdc8d2010-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 Claytonc6ed5422010-10-07 17:14:24 +000040#include "lldb/Target/Thread.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000041
Chris Lattner30fdc8d2010-06-08 16:52:24 +000042using namespace lldb;
43using namespace lldb_private;
44
Greg Claytonfc36f7912011-03-22 01:14:58 +000045
46static ScriptInterpreter::SWIGInitCallback g_swig_init_callback = NULL;
47static ScriptInterpreter::SWIGBreakpointCallbackFunction g_swig_breakpoint_callback = NULL;
Johnny Chene9a56272012-08-09 23:09:42 +000048static ScriptInterpreter::SWIGWatchpointCallbackFunction g_swig_watchpoint_callback = NULL;
Enrico Granataf2bbf712011-07-15 02:26:42 +000049static ScriptInterpreter::SWIGPythonTypeScriptCallbackFunction g_swig_typescript_callback = NULL;
Enrico Granataa37a0652011-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 Granata6f3533f2011-07-29 19:53:35 +000055static ScriptInterpreter::SWIGPythonUpdateSynthProviderInstance g_swig_update_provider = NULL;
Enrico Granataadaf2822012-10-23 19:54:09 +000056static ScriptInterpreter::SWIGPythonMightHaveChildrenSynthProviderInstance g_swig_mighthavechildren_provider = NULL;
Enrico Granatabe93a352011-08-16 16:49:25 +000057static ScriptInterpreter::SWIGPythonCallCommand g_swig_call_command = NULL;
Enrico Granataa9dbf432011-10-17 21:45:27 +000058static ScriptInterpreter::SWIGPythonCallModuleInit g_swig_call_module_init = NULL;
Enrico Granata57907592012-08-24 00:30:47 +000059static ScriptInterpreter::SWIGPythonCreateOSPlugin g_swig_create_os_plugin = NULL;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000060
Enrico Granata7bc0ec32012-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 Chene9a56272012-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 Granata7bc0ec32012-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 Granataadaf2822012-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 Granata7bc0ec32012-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 Granata57907592012-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 Lattner30fdc8d2010-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 Granata47c6f6d2011-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 Granata47c6f6d2011-10-24 17:22:21 +0000146 m_python_interpreter(py_interpreter),
147 m_tmp_fh(wait_msg_handle)
Enrico Granata9128ee22011-09-06 19:20:51 +0000148{
Enrico Granata47c6f6d2011-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 Chen2c90e992012-08-18 04:14:54 +0000151
152 DoAcquireLock();
Jim Ingham6a510852012-12-07 17:43:38 +0000153 if ((on_entry & InitSession) == InitSession)
154 DoInitSession((on_entry & InitGlobals) == InitGlobals);
Enrico Granata47c6f6d2011-10-24 17:22:21 +0000155}
156
157bool
158ScriptInterpreterPython::Locker::DoAcquireLock()
159{
Johnny Chen2c90e992012-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 Granata47c6f6d2011-10-24 17:22:21 +0000164 return true;
165}
166
167bool
Jim Ingham6a510852012-12-07 17:43:38 +0000168ScriptInterpreterPython::Locker::DoInitSession(bool init_lldb_globals)
Enrico Granata47c6f6d2011-10-24 17:22:21 +0000169{
170 if (!m_python_interpreter)
171 return false;
Jim Ingham6a510852012-12-07 17:43:38 +0000172 m_python_interpreter->EnterSession (init_lldb_globals);
Enrico Granata47c6f6d2011-10-24 17:22:21 +0000173 return true;
174}
175
176bool
177ScriptInterpreterPython::Locker::DoFreeLock()
178{
Johnny Chen2c90e992012-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 Granata47c6f6d2011-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 Granata9128ee22011-09-06 19:20:51 +0000193}
194
195ScriptInterpreterPython::Locker::~Locker()
196{
197 if (m_need_session)
Enrico Granata47c6f6d2011-10-24 17:22:21 +0000198 DoTearDownSession();
Johnny Chen2c90e992012-08-18 04:14:54 +0000199 DoFreeLock();
Enrico Granata9128ee22011-09-06 19:20:51 +0000200}
201
Enrico Granata79cc6f72012-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 Chen319e9272012-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 Granata79cc6f72012-06-07 00:17:18 +0000257 {
Johnny Chen319e9272012-08-17 23:44:35 +0000258 m_interpreter->m_embedded_thread_pty.CloseSlaveFileDescriptor();
Enrico Granata79cc6f72012-06-07 00:17:18 +0000259 m_interpreter->m_embedded_thread_input_reader_sp.reset();
Johnny Chen319e9272012-08-17 23:44:35 +0000260 }
Enrico Granata79cc6f72012-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 Chen2c90e992012-08-18 04:14:54 +0000296
Enrico Granata79cc6f72012-06-07 00:17:18 +0000297 char error_str[1024];
Johnny Chen319e9272012-08-17 23:44:35 +0000298 if (script_interpreter->m_embedded_thread_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, error_str,
Enrico Granata79cc6f72012-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 Chen319e9272012-08-17 23:44:35 +0000303 script_interpreter->m_embedded_thread_pty.GetMasterFileDescriptor());
Enrico Granata79cc6f72012-06-07 00:17:18 +0000304 {
305 StreamString run_string;
306 char error_str[1024];
Johnny Chen319e9272012-08-17 23:44:35 +0000307 const char *pty_slave_name = script_interpreter->m_embedded_thread_pty.GetSlaveName (error_str, sizeof (error_str));
Enrico Granata008eaf82012-07-31 16:58:12 +0000308 if (pty_slave_name != NULL && PyThreadState_GetDict() != NULL)
Enrico Granata79cc6f72012-06-07 00:17:18 +0000309 {
Johnny Chen2c90e992012-08-18 04:14:54 +0000310 ScriptInterpreterPython::Locker locker(script_interpreter,
Jim Ingham6a510852012-12-07 17:43:38 +0000311 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession | ScriptInterpreterPython::Locker::InitGlobals,
Johnny Chen2c90e992012-08-18 04:14:54 +0000312 ScriptInterpreterPython::Locker::FreeAcquiredLock);
Enrico Granata79cc6f72012-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 Malead01b2952012-11-29 21:49:15 +0000337 log->Printf ("ScriptInterpreterPython::NonInteractiveInputReaderCallback, Activate, succeeded in creating thread (thread_t = %p)", (void *)embedded_interpreter_thread);
Enrico Granata79cc6f72012-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 Clayton4c054102012-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 Granata79cc6f72012-06-07 00:17:18 +0000368 break;
369
370 case eInputReaderAsynchronousOutputWritten:
371 break;
372
373 case eInputReaderInterrupt:
Enrico Granata557fd002012-12-19 23:42:07 +0000374 {
375 PyThreadState* state = _PyThreadState_Current;
376 if (!state)
377 state = script_interpreter->m_command_thread_state;
378 if (state)
379 {
380 long tid = state->thread_id;
381 _PyThreadState_Current = state;
382 int num_threads = PyThreadState_SetAsyncExc(tid, PyExc_KeyboardInterrupt);
383 if (log)
384 log->Printf("ScriptInterpreterPython::NonInteractiveInputReaderCallback, eInputReaderInterrupt, tid = %ld, num_threads = %d, state = %p",
385 tid,num_threads,state);
386 }
387 else if (log)
388 log->Printf("ScriptInterpreterPython::NonInteractiveInputReaderCallback, eInputReaderInterrupt, state = NULL");
389 }
Enrico Granata79cc6f72012-06-07 00:17:18 +0000390 break;
391
392 case eInputReaderEndOfFile:
393 reader.SetIsDone(true);
394 break;
395
396 case eInputReaderGotToken:
Johnny Chen319e9272012-08-17 23:44:35 +0000397 if (script_interpreter->m_embedded_thread_pty.GetMasterFileDescriptor() != -1)
Enrico Granata79cc6f72012-06-07 00:17:18 +0000398 {
399 if (log)
400 log->Printf ("ScriptInterpreterPython::NonInteractiveInputReaderCallback, GotToken, bytes='%s', byte_len = %lu", bytes,
401 bytes_len);
402 if (bytes && bytes_len)
Johnny Chen319e9272012-08-17 23:44:35 +0000403 ::write (script_interpreter->m_embedded_thread_pty.GetMasterFileDescriptor(), bytes, bytes_len);
404 ::write (script_interpreter->m_embedded_thread_pty.GetMasterFileDescriptor(), "\n", 1);
Enrico Granata79cc6f72012-06-07 00:17:18 +0000405 }
406 else
407 {
408 if (log)
409 log->Printf ("ScriptInterpreterPython::NonInteractiveInputReaderCallback, GotToken, bytes='%s', byte_len = %lu, Master File Descriptor is bad.",
410 bytes,
411 bytes_len);
412 reader.SetIsDone (true);
413 }
414
415 break;
416
417 case eInputReaderDone:
418 {
419 StreamString run_string;
420 char error_str[1024];
Johnny Chen319e9272012-08-17 23:44:35 +0000421 const char *pty_slave_name = script_interpreter->m_embedded_thread_pty.GetSlaveName (error_str, sizeof (error_str));
Enrico Granata008eaf82012-07-31 16:58:12 +0000422 if (pty_slave_name != NULL && PyThreadState_GetDict() != NULL)
Enrico Granata79cc6f72012-06-07 00:17:18 +0000423 {
Johnny Chen2c90e992012-08-18 04:14:54 +0000424 ScriptInterpreterPython::Locker locker(script_interpreter,
425 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
426 ScriptInterpreterPython::Locker::FreeAcquiredLock);
Enrico Granata79cc6f72012-06-07 00:17:18 +0000427 run_string.Printf ("run_one_line (%s, 'sys.stdin = save_stdin')", script_interpreter->m_dictionary_name.c_str());
428 PyRun_SimpleString (run_string.GetData());
429 run_string.Clear();
430
431 run_string.Printf ("run_one_line (%s, 'sys.stderr = save_stderr')", script_interpreter->m_dictionary_name.c_str());
432 PyRun_SimpleString (run_string.GetData());
433 run_string.Clear();
434 }
435 }
436
437 // Restore terminal settings if they were validly saved
438 if (log)
439 log->Printf ("ScriptInterpreterPython::NonInteractiveInputReaderCallback, Done, closing down input reader.");
440
441 script_interpreter->RestoreTerminalState ();
442
Johnny Chen319e9272012-08-17 23:44:35 +0000443 script_interpreter->m_embedded_thread_pty.CloseMasterFileDescriptor();
Enrico Granata79cc6f72012-06-07 00:17:18 +0000444 break;
445 }
446
447 return bytes_len;
448}
449
Greg Clayton66111032010-06-23 01:19:29 +0000450ScriptInterpreterPython::ScriptInterpreterPython (CommandInterpreter &interpreter) :
Greg Claytona7015092010-09-18 01:14:36 +0000451 ScriptInterpreter (interpreter, eScriptLanguagePython),
Johnny Chen319e9272012-08-17 23:44:35 +0000452 m_embedded_thread_pty (),
Caroline Tice2f88aad2011-01-14 00:29:16 +0000453 m_embedded_python_pty (),
454 m_embedded_thread_input_reader_sp (),
Johnny Chen319e9272012-08-17 23:44:35 +0000455 m_embedded_python_input_reader_sp (),
Greg Clayton51b1e2d2011-02-09 01:08:52 +0000456 m_dbg_stdout (interpreter.GetDebugger().GetOutputFile().GetStream()),
Caroline Tice2f88aad2011-01-14 00:29:16 +0000457 m_new_sysout (NULL),
Johnny Chen5d346292012-03-08 20:53:04 +0000458 m_old_sysout (NULL),
459 m_old_syserr (NULL),
Enrico Granataa73b7df2012-03-06 23:42:15 +0000460 m_run_one_line (NULL),
Caroline Tice2f88aad2011-01-14 00:29:16 +0000461 m_dictionary_name (interpreter.GetDebugger().GetInstanceName().AsCString()),
Greg Claytona3406612011-02-07 23:24:47 +0000462 m_terminal_state (),
Caroline Tice2f88aad2011-01-14 00:29:16 +0000463 m_session_is_active (false),
Enrico Granata557fd002012-12-19 23:42:07 +0000464 m_valid_session (true),
465 m_command_thread_state (NULL)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000466{
467
Greg Clayton645bf542011-01-27 01:01:10 +0000468 static int g_initialized = false;
469
470 if (!g_initialized)
471 {
472 g_initialized = true;
Greg Claytonfc36f7912011-03-22 01:14:58 +0000473 ScriptInterpreterPython::InitializePrivate ();
Greg Clayton645bf542011-01-27 01:01:10 +0000474 }
475
Caroline Tice2f88aad2011-01-14 00:29:16 +0000476 m_dictionary_name.append("_dict");
477 StreamString run_string;
478 run_string.Printf ("%s = dict()", m_dictionary_name.c_str());
Johnny Chen2c90e992012-08-18 04:14:54 +0000479
480 Locker locker(this,
481 ScriptInterpreterPython::Locker::AcquireLock,
482 ScriptInterpreterPython::Locker::FreeAcquiredLock);
Caroline Tice2f88aad2011-01-14 00:29:16 +0000483 PyRun_SimpleString (run_string.GetData());
Caroline Ticedc8f7772010-10-18 18:24:17 +0000484
Caroline Tice2f88aad2011-01-14 00:29:16 +0000485 run_string.Clear();
Caroline Tice2f88aad2011-01-14 00:29:16 +0000486
487 // Importing 'lldb' module calls SBDebugger::Initialize, which calls Debugger::Initialize, which increments a
488 // global debugger ref-count; therefore we need to check the ref-count before and after importing lldb, and if the
489 // ref-count increased we need to call Debugger::Terminate here to decrement the ref-count so that when the final
490 // call to Debugger::Terminate is made, the ref-count has the correct value.
491 //
492 // Bonus question: Why doesn't the ref-count always increase? Because sometimes lldb has already been imported, in
493 // which case the code inside it, including the call to SBDebugger::Initialize(), does not get executed.
Caroline Ticedc8f7772010-10-18 18:24:17 +0000494
Caroline Tice2f88aad2011-01-14 00:29:16 +0000495 int old_count = Debugger::TestDebuggerRefCount();
Greg Clayton6b2bd932012-02-01 08:09:32 +0000496
Greg Clayton6d98f562012-04-25 00:58:03 +0000497 run_string.Printf ("run_one_line (%s, 'import copy, os, re, sys, uuid, lldb')", m_dictionary_name.c_str());
Caroline Tice2f88aad2011-01-14 00:29:16 +0000498 PyRun_SimpleString (run_string.GetData());
Greg Claytondd36def2010-10-17 22:03:32 +0000499
Enrico Granatad3d444f2012-02-23 23:10:03 +0000500 // WARNING: temporary code that loads Cocoa formatters - this should be done on a per-platform basis rather than loading the whole set
501 // and letting the individual formatter classes exploit APIs to check whether they can/cannot do their task
502 run_string.Clear();
Enrico Granataf71a8392012-10-22 19:09:28 +0000503 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 Granatad3d444f2012-02-23 23:10:03 +0000504 PyRun_SimpleString (run_string.GetData());
Greg Clayton6b2bd932012-02-01 08:09:32 +0000505
Caroline Tice2f88aad2011-01-14 00:29:16 +0000506 int new_count = Debugger::TestDebuggerRefCount();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000507
Caroline Tice2f88aad2011-01-14 00:29:16 +0000508 if (new_count > old_count)
509 Debugger::Terminate();
Caroline Ticedc8f7772010-10-18 18:24:17 +0000510
Caroline Tice2f88aad2011-01-14 00:29:16 +0000511 run_string.Clear();
Daniel Malead01b2952012-11-29 21:49:15 +0000512 run_string.Printf ("run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64 "; pydoc.pager = pydoc.plainpager')", m_dictionary_name.c_str(),
Caroline Tice2f88aad2011-01-14 00:29:16 +0000513 interpreter.GetDebugger().GetID());
514 PyRun_SimpleString (run_string.GetData());
515
516 if (m_dbg_stdout != NULL)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000517 {
Caroline Tice2f88aad2011-01-14 00:29:16 +0000518 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
Caroline Ticedc8f7772010-10-18 18:24:17 +0000519 }
Enrico Granatab5887262012-10-29 21:18:03 +0000520
521 // get the output file handle from the debugger (if any)
522 File& out_file = interpreter.GetDebugger().GetOutputFile();
523 if (out_file.IsValid())
524 ResetOutputFileHandle(out_file.GetStream());
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000525}
526
527ScriptInterpreterPython::~ScriptInterpreterPython ()
528{
Caroline Tice2f88aad2011-01-14 00:29:16 +0000529 Debugger &debugger = GetCommandInterpreter().GetDebugger();
530
531 if (m_embedded_thread_input_reader_sp.get() != NULL)
532 {
533 m_embedded_thread_input_reader_sp->SetIsDone (true);
Johnny Chen319e9272012-08-17 23:44:35 +0000534 m_embedded_thread_pty.CloseSlaveFileDescriptor();
Caroline Tice2f88aad2011-01-14 00:29:16 +0000535 const InputReaderSP reader_sp = m_embedded_thread_input_reader_sp;
Caroline Tice2f88aad2011-01-14 00:29:16 +0000536 debugger.PopInputReader (reader_sp);
Johnny Chen319e9272012-08-17 23:44:35 +0000537 m_embedded_thread_input_reader_sp.reset();
538 }
539
540 if (m_embedded_python_input_reader_sp.get() != NULL)
541 {
542 m_embedded_python_input_reader_sp->SetIsDone (true);
543 m_embedded_python_pty.CloseSlaveFileDescriptor();
544 const InputReaderSP reader_sp = m_embedded_python_input_reader_sp;
545 debugger.PopInputReader (reader_sp);
546 m_embedded_python_input_reader_sp.reset();
Caroline Tice2f88aad2011-01-14 00:29:16 +0000547 }
548
549 if (m_new_sysout)
550 {
Enrico Granata47c6f6d2011-10-24 17:22:21 +0000551 Locker locker(this,
552 ScriptInterpreterPython::Locker::AcquireLock,
553 ScriptInterpreterPython::Locker::FreeLock);
554 Py_DECREF ((PyObject*)m_new_sysout);
Caroline Tice2f88aad2011-01-14 00:29:16 +0000555 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000556}
557
Caroline Tice2f88aad2011-01-14 00:29:16 +0000558void
559ScriptInterpreterPython::ResetOutputFileHandle (FILE *fh)
560{
561 if (fh == NULL)
562 return;
563
564 m_dbg_stdout = fh;
Caroline Tice2f88aad2011-01-14 00:29:16 +0000565
Johnny Chen5d346292012-03-08 20:53:04 +0000566 Locker locker(this,
567 ScriptInterpreterPython::Locker::AcquireLock,
568 ScriptInterpreterPython::Locker::FreeAcquiredLock);
569
Enrico Granata9128ee22011-09-06 19:20:51 +0000570 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
Caroline Tice2f88aad2011-01-14 00:29:16 +0000571}
572
573void
Greg Claytona3406612011-02-07 23:24:47 +0000574ScriptInterpreterPython::SaveTerminalState (int fd)
575{
576 // Python mucks with the terminal state of STDIN. If we can possibly avoid
577 // this by setting the file handles up correctly prior to entering the
578 // interpreter we should. For now we save and restore the terminal state
579 // on the input file handle.
580 m_terminal_state.Save (fd, false);
581}
582
583void
584ScriptInterpreterPython::RestoreTerminalState ()
585{
586 // Python mucks with the terminal state of STDIN. If we can possibly avoid
587 // this by setting the file handles up correctly prior to entering the
588 // interpreter we should. For now we save and restore the terminal state
589 // on the input file handle.
590 m_terminal_state.Restore();
591}
592
Greg Claytona3406612011-02-07 23:24:47 +0000593void
Caroline Tice2f88aad2011-01-14 00:29:16 +0000594ScriptInterpreterPython::LeaveSession ()
595{
Enrico Granata0249fba2012-04-04 17:31:29 +0000596 // checking that we have a valid thread state - since we use our own threading and locking
597 // in some (rare) cases during cleanup Python may end up believing we have no thread state
598 // and PyImport_AddModule will crash if that is the case - since that seems to only happen
599 // when destroying the SBDebugger, we can make do without clearing up stdout and stderr
Johnny Chen30e422d2012-05-04 20:37:11 +0000600
601 // rdar://problem/11292882
602 // When the current thread state is NULL, PyThreadState_Get() issues a fatal error.
603 if (PyThreadState_GetDict())
Johnny Chen1cf107c2012-02-29 01:52:13 +0000604 {
Enrico Granata0249fba2012-04-04 17:31:29 +0000605 PyObject *sysmod = PyImport_AddModule ("sys");
606 PyObject *sysdict = PyModule_GetDict (sysmod);
607
608 if (m_new_sysout && sysmod && sysdict)
609 {
610 if (m_old_sysout)
611 PyDict_SetItemString (sysdict, "stdout", (PyObject*)m_old_sysout);
612 if (m_old_syserr)
613 PyDict_SetItemString (sysdict, "stderr", (PyObject*)m_old_syserr);
614 }
Johnny Chen1cf107c2012-02-29 01:52:13 +0000615 }
616
Caroline Tice2f88aad2011-01-14 00:29:16 +0000617 m_session_is_active = false;
618}
619
620void
Jim Ingham6a510852012-12-07 17:43:38 +0000621ScriptInterpreterPython::EnterSession (bool init_lldb_globals)
Caroline Tice2f88aad2011-01-14 00:29:16 +0000622{
623 // If we have already entered the session, without having officially 'left' it, then there is no need to
624 // 'enter' it again.
625
626 if (m_session_is_active)
627 return;
628
629 m_session_is_active = true;
630
Caroline Tice6760a512011-01-17 21:55:19 +0000631 StreamString run_string;
632
Jim Ingham6a510852012-12-07 17:43:38 +0000633 if (init_lldb_globals)
634 {
635 run_string.Printf ( "run_one_line (%s, 'lldb.debugger_unique_id = %" PRIu64, m_dictionary_name.c_str(), GetCommandInterpreter().GetDebugger().GetID());
636 run_string.Printf ( "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64 ")", GetCommandInterpreter().GetDebugger().GetID());
637 run_string.PutCString ("; lldb.target = lldb.debugger.GetSelectedTarget()");
638 run_string.PutCString ("; lldb.process = lldb.target.GetProcess()");
639 run_string.PutCString ("; lldb.thread = lldb.process.GetSelectedThread ()");
640 run_string.PutCString ("; lldb.frame = lldb.thread.GetSelectedFrame ()");
641 run_string.PutCString ("')");
642 }
Jim Ingham53206242012-12-08 02:02:04 +0000643 else
644 {
645 // If we aren't initing the globals, we should still always set the debugger (since that is always unique.)
646 run_string.Printf ( "run_one_line (%s, \"lldb.debugger_unique_id = %" PRIu64, m_dictionary_name.c_str(), GetCommandInterpreter().GetDebugger().GetID());
647 run_string.Printf ( "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%" PRIu64 ")", GetCommandInterpreter().GetDebugger().GetID());
648 run_string.PutCString ("\")");
649 }
Caroline Tice2f88aad2011-01-14 00:29:16 +0000650
Caroline Ticee67afe12011-05-03 21:21:50 +0000651 PyRun_SimpleString (run_string.GetData());
652 run_string.Clear();
Johnny Chen1cf107c2012-02-29 01:52:13 +0000653
Caroline Tice2f88aad2011-01-14 00:29:16 +0000654 PyObject *sysmod = PyImport_AddModule ("sys");
655 PyObject *sysdict = PyModule_GetDict (sysmod);
Johnny Chen1cf107c2012-02-29 01:52:13 +0000656
Greg Clayton037f9fd2012-01-28 02:11:02 +0000657 if (m_new_sysout && sysmod && sysdict)
658 {
Johnny Chen1cf107c2012-02-29 01:52:13 +0000659 m_old_sysout = PyDict_GetItemString(sysdict, "stdout");
660 m_old_syserr = PyDict_GetItemString(sysdict, "stderr");
Johnny Chen5d346292012-03-08 20:53:04 +0000661 if (m_new_sysout)
662 {
663 PyDict_SetItemString (sysdict, "stdout", (PyObject*)m_new_sysout);
664 PyDict_SetItemString (sysdict, "stderr", (PyObject*)m_new_sysout);
665 }
Greg Clayton037f9fd2012-01-28 02:11:02 +0000666 }
Johnny Chen1cf107c2012-02-29 01:52:13 +0000667
Caroline Tice2f88aad2011-01-14 00:29:16 +0000668 if (PyErr_Occurred())
669 PyErr_Clear ();
Greg Clayton037f9fd2012-01-28 02:11:02 +0000670}
Caroline Tice2f88aad2011-01-14 00:29:16 +0000671
Enrico Granataa73b7df2012-03-06 23:42:15 +0000672static PyObject*
673FindSessionDictionary (const char* dict_name)
674{
675 static std::map<ConstString,PyObject*> g_dict_map;
676
677 ConstString dict(dict_name);
678
679 std::map<ConstString,PyObject*>::iterator iter = g_dict_map.find(dict);
680
681 if (iter != g_dict_map.end())
682 return iter->second;
683
684 PyObject *main_mod = PyImport_AddModule ("__main__");
685 if (main_mod != NULL)
686 {
687 PyObject *main_dict = PyModule_GetDict (main_mod);
688 if ((main_dict != NULL)
689 && PyDict_Check (main_dict))
690 {
691 // Go through the main dictionary looking for the correct python script interpreter dictionary
692 PyObject *key, *value;
693 Py_ssize_t pos = 0;
694
695 while (PyDict_Next (main_dict, &pos, &key, &value))
696 {
697 // We have stolen references to the key and value objects in the dictionary; we need to increment
698 // them now so that Python's garbage collector doesn't collect them out from under us.
699 Py_INCREF (key);
700 Py_INCREF (value);
701 if (strcmp (PyString_AsString (key), dict_name) == 0)
702 {
703 g_dict_map[dict] = value;
704 return value;
705 }
706 }
707 }
708 }
709 return NULL;
710}
711
712static std::string
713GenerateUniqueName (const char* base_name_wanted,
714 uint32_t& functions_counter,
715 void* name_token = NULL)
716{
717 StreamString sstr;
718
719 if (!base_name_wanted)
720 return std::string();
721
722 if (!name_token)
723 sstr.Printf ("%s_%d", base_name_wanted, functions_counter++);
724 else
725 sstr.Printf ("%s_%p", base_name_wanted, name_token);
726
727 return sstr.GetString();
728}
729
Johnny Chen7dc2e472010-07-30 22:33:14 +0000730bool
Enrico Granata085577f2012-10-31 00:01:26 +0000731ScriptInterpreterPython::ExecuteOneLine (const char *command, CommandReturnObject *result, const ExecuteScriptOptions &options)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000732{
Caroline Tice2f88aad2011-01-14 00:29:16 +0000733 if (!m_valid_session)
734 return false;
735
Caroline Tice8f5b2eb2011-01-14 21:09:29 +0000736 // We want to call run_one_line, passing in the dictionary and the command string. We cannot do this through
737 // PyRun_SimpleString here because the command string may contain escaped characters, and putting it inside
738 // another string to pass to PyRun_SimpleString messes up the escaping. So we use the following more complicated
739 // method to pass the command string directly down to Python.
740
Enrico Granata47c6f6d2011-10-24 17:22:21 +0000741 Locker locker(this,
Jim Ingham6a510852012-12-07 17:43:38 +0000742 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession | (options.GetSetLLDBGlobals() ? ScriptInterpreterPython::Locker::InitGlobals : 0),
Enrico Granata085577f2012-10-31 00:01:26 +0000743 ScriptInterpreterPython::Locker::FreeAcquiredLock | (options.GetSetLLDBGlobals() ? ScriptInterpreterPython::Locker::TearDownSession : 0));
Caroline Tice8f5b2eb2011-01-14 21:09:29 +0000744
745 bool success = false;
746
Greg Clayton66111032010-06-23 01:19:29 +0000747 if (command)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000748 {
Caroline Tice8f5b2eb2011-01-14 21:09:29 +0000749 // Find the correct script interpreter dictionary in the main module.
Enrico Granataa73b7df2012-03-06 23:42:15 +0000750 PyObject *script_interpreter_dict = FindSessionDictionary(m_dictionary_name.c_str());
751 if (script_interpreter_dict != NULL)
Caroline Tice8f5b2eb2011-01-14 21:09:29 +0000752 {
Enrico Granataa73b7df2012-03-06 23:42:15 +0000753 PyObject *pfunc = (PyObject*)m_run_one_line;
Greg Claytoned3eee62012-04-25 01:49:50 +0000754 PyObject *pmod = PyImport_AddModule ("lldb.embedded_interpreter");
Enrico Granataa73b7df2012-03-06 23:42:15 +0000755 if (pmod != NULL)
Caroline Tice8f5b2eb2011-01-14 21:09:29 +0000756 {
Enrico Granataa73b7df2012-03-06 23:42:15 +0000757 PyObject *pmod_dict = PyModule_GetDict (pmod);
758 if ((pmod_dict != NULL)
759 && PyDict_Check (pmod_dict))
Caroline Tice8f5b2eb2011-01-14 21:09:29 +0000760 {
Enrico Granataa73b7df2012-03-06 23:42:15 +0000761 if (!pfunc)
Caroline Tice8f5b2eb2011-01-14 21:09:29 +0000762 {
763 PyObject *key, *value;
764 Py_ssize_t pos = 0;
765
766 while (PyDict_Next (pmod_dict, &pos, &key, &value))
767 {
768 Py_INCREF (key);
769 Py_INCREF (value);
770 if (strcmp (PyString_AsString (key), "run_one_line") == 0)
771 {
772 pfunc = value;
773 break;
774 }
775 }
Enrico Granataa73b7df2012-03-06 23:42:15 +0000776 m_run_one_line = pfunc;
777 }
778
779 if (pfunc && PyCallable_Check (pfunc))
780 {
781 PyObject *pargs = Py_BuildValue("(Os)",script_interpreter_dict,command);
782 if (pargs != NULL)
Caroline Tice8f5b2eb2011-01-14 21:09:29 +0000783 {
Enrico Granata79cc6f72012-06-07 00:17:18 +0000784 PyObject *pvalue = NULL;
785 { // scope for PythonInputReaderManager
Enrico Granata085577f2012-10-31 00:01:26 +0000786 PythonInputReaderManager py_input(options.GetEnableIO() ? this : NULL);
Enrico Granata79cc6f72012-06-07 00:17:18 +0000787 pvalue = PyObject_CallObject (pfunc, pargs);
788 }
Enrico Granataa73b7df2012-03-06 23:42:15 +0000789 Py_DECREF (pargs);
790 if (pvalue != NULL)
Caroline Tice8f5b2eb2011-01-14 21:09:29 +0000791 {
Enrico Granataa73b7df2012-03-06 23:42:15 +0000792 Py_DECREF (pvalue);
793 success = true;
794 }
Enrico Granata085577f2012-10-31 00:01:26 +0000795 else if (options.GetMaskoutErrors() && PyErr_Occurred ())
Enrico Granataa73b7df2012-03-06 23:42:15 +0000796 {
797 PyErr_Print();
798 PyErr_Clear();
Caroline Tice8f5b2eb2011-01-14 21:09:29 +0000799 }
800 }
801 }
802 }
Caroline Tice8f5b2eb2011-01-14 21:09:29 +0000803 }
Enrico Granataa73b7df2012-03-06 23:42:15 +0000804 Py_INCREF (script_interpreter_dict);
Caroline Tice8f5b2eb2011-01-14 21:09:29 +0000805 }
Greg Clayton66111032010-06-23 01:19:29 +0000806
Caroline Tice8f5b2eb2011-01-14 21:09:29 +0000807 if (success)
Johnny Chen7dc2e472010-07-30 22:33:14 +0000808 return true;
809
810 // The one-liner failed. Append the error message.
811 if (result)
812 result->AppendErrorWithFormat ("python failed attempting to evaluate '%s'\n", command);
813 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000814 }
Johnny Chen7dc2e472010-07-30 22:33:14 +0000815
816 if (result)
817 result->AppendError ("empty command passed to python\n");
818 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000819}
820
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000821size_t
822ScriptInterpreterPython::InputReaderCallback
823(
824 void *baton,
Greg Clayton66111032010-06-23 01:19:29 +0000825 InputReader &reader,
Greg Claytonc6ed5422010-10-07 17:14:24 +0000826 InputReaderAction notification,
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000827 const char *bytes,
828 size_t bytes_len
829)
830{
Caroline Tice5c2816d2010-11-10 19:18:14 +0000831 lldb::thread_t embedded_interpreter_thread;
832 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
833
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000834 if (baton == NULL)
835 return 0;
Caroline Tice2f88aad2011-01-14 00:29:16 +0000836
837 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
Enrico Granata47c6f6d2011-10-24 17:22:21 +0000838
Caroline Tice2f88aad2011-01-14 00:29:16 +0000839 if (script_interpreter->m_script_lang != eScriptLanguagePython)
840 return 0;
841
Caroline Ticed61c10b2011-06-16 16:27:19 +0000842 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
843 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
844
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000845 switch (notification)
846 {
847 case eInputReaderActivate:
848 {
Caroline Ticed61c10b2011-06-16 16:27:19 +0000849 if (!batch_mode)
850 {
851 out_stream->Printf ("Python Interactive Interpreter. To exit, type 'quit()', 'exit()' or Ctrl-D.\n");
852 out_stream->Flush();
853 }
Greg Clayton51b1e2d2011-02-09 01:08:52 +0000854
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000855 // Save terminal settings if we can
Greg Clayton51b1e2d2011-02-09 01:08:52 +0000856 int input_fd = reader.GetDebugger().GetInputFile().GetDescriptor();
857 if (input_fd == File::kInvalidDescriptor)
Greg Claytondd36def2010-10-17 22:03:32 +0000858 input_fd = STDIN_FILENO;
Caroline Ticee7e92b72010-09-14 22:49:06 +0000859
Greg Claytona3406612011-02-07 23:24:47 +0000860 script_interpreter->SaveTerminalState(input_fd);
Greg Claytoncdd074f2011-02-07 19:04:58 +0000861
Caroline Tice6760a512011-01-17 21:55:19 +0000862 {
Enrico Granata47c6f6d2011-10-24 17:22:21 +0000863 ScriptInterpreterPython::Locker locker(script_interpreter,
Jim Ingham6a510852012-12-07 17:43:38 +0000864 ScriptInterpreterPython::Locker::AcquireLock
865 | ScriptInterpreterPython::Locker::InitSession
866 | ScriptInterpreterPython::Locker::InitGlobals,
Enrico Granata47c6f6d2011-10-24 17:22:21 +0000867 ScriptInterpreterPython::Locker::FreeAcquiredLock);
Caroline Tice6760a512011-01-17 21:55:19 +0000868 }
Caroline Tice6760a512011-01-17 21:55:19 +0000869
Caroline Tice5c2816d2010-11-10 19:18:14 +0000870 char error_str[1024];
871 if (script_interpreter->m_embedded_python_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, error_str,
872 sizeof(error_str)))
873 {
874 if (log)
875 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in opening master pty (fd = %d).",
876 script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor());
877 embedded_interpreter_thread = Host::ThreadCreate ("<lldb.script-interpreter.embedded-python-loop>",
878 ScriptInterpreterPython::RunEmbeddedPythonInterpreter,
879 script_interpreter, NULL);
Greg Clayton2da6d492011-02-08 01:34:25 +0000880 if (IS_VALID_LLDB_HOST_THREAD(embedded_interpreter_thread))
Caroline Tice5c2816d2010-11-10 19:18:14 +0000881 {
882 if (log)
Daniel Malead01b2952012-11-29 21:49:15 +0000883 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in creating thread (thread_t = %p)", (void *)embedded_interpreter_thread);
Caroline Tice5c2816d2010-11-10 19:18:14 +0000884 Error detach_error;
885 Host::ThreadDetach (embedded_interpreter_thread, &detach_error);
886 }
887 else
888 {
889 if (log)
890 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed in creating thread");
891 reader.SetIsDone (true);
892 }
893 }
894 else
895 {
896 if (log)
897 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed to open master pty ");
898 reader.SetIsDone (true);
899 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000900 }
901 break;
902
903 case eInputReaderDeactivate:
Greg Clayton1a0be3b2012-01-06 00:47:38 +0000904 // When another input reader is pushed, don't leave the session...
905 //script_interpreter->LeaveSession ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000906 break;
907
908 case eInputReaderReactivate:
Caroline Tice6760a512011-01-17 21:55:19 +0000909 {
Johnny Chen2c90e992012-08-18 04:14:54 +0000910 ScriptInterpreterPython::Locker locker(script_interpreter,
Jim Ingham6a510852012-12-07 17:43:38 +0000911 ScriptInterpreterPython::Locker::AcquireLock
912 | ScriptInterpreterPython::Locker::InitSession
913 | ScriptInterpreterPython::Locker::InitGlobals,
Johnny Chen2c90e992012-08-18 04:14:54 +0000914 ScriptInterpreterPython::Locker::FreeAcquiredLock);
Caroline Tice6760a512011-01-17 21:55:19 +0000915 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000916 break;
Caroline Ticeefed6132010-11-19 20:47:54 +0000917
Caroline Tice969ed3d2011-05-02 20:41:46 +0000918 case eInputReaderAsynchronousOutputWritten:
919 break;
920
Caroline Ticeefed6132010-11-19 20:47:54 +0000921 case eInputReaderInterrupt:
922 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "raise KeyboardInterrupt\n", 24);
923 break;
924
925 case eInputReaderEndOfFile:
926 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()\n", 7);
927 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000928
929 case eInputReaderGotToken:
Caroline Tice5c2816d2010-11-10 19:18:14 +0000930 if (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor() != -1)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000931 {
Caroline Tice5c2816d2010-11-10 19:18:14 +0000932 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +0000933 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %lu", bytes,
Caroline Tice5c2816d2010-11-10 19:18:14 +0000934 bytes_len);
935 if (bytes && bytes_len)
936 {
937 if ((int) bytes[0] == 4)
938 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()", 6);
939 else
940 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), bytes, bytes_len);
941 }
942 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "\n", 1);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000943 }
Caroline Tice5c2816d2010-11-10 19:18:14 +0000944 else
945 {
946 if (log)
Jason Molendafd54b362011-09-20 21:44:10 +0000947 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %lu, Master File Descriptor is bad.",
Caroline Tice5c2816d2010-11-10 19:18:14 +0000948 bytes,
949 bytes_len);
950 reader.SetIsDone (true);
951 }
952
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000953 break;
954
955 case eInputReaderDone:
Johnny Chen2c90e992012-08-18 04:14:54 +0000956 {
957 Locker locker(script_interpreter,
958 ScriptInterpreterPython::Locker::AcquireLock,
959 ScriptInterpreterPython::Locker::FreeAcquiredLock);
960 script_interpreter->LeaveSession ();
961 }
Caroline Tice2f88aad2011-01-14 00:29:16 +0000962
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000963 // Restore terminal settings if they were validly saved
Caroline Tice5c2816d2010-11-10 19:18:14 +0000964 if (log)
965 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Done, closing down input reader.");
Caroline Ticee7e92b72010-09-14 22:49:06 +0000966
Greg Claytona3406612011-02-07 23:24:47 +0000967 script_interpreter->RestoreTerminalState ();
968
Caroline Tice5c2816d2010-11-10 19:18:14 +0000969 script_interpreter->m_embedded_python_pty.CloseMasterFileDescriptor();
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000970 break;
971 }
972
973 return bytes_len;
974}
975
976
977void
Greg Claytona7015092010-09-18 01:14:36 +0000978ScriptInterpreterPython::ExecuteInterpreterLoop ()
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000979{
980 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
981
Caroline Tice2f88aad2011-01-14 00:29:16 +0000982 Debugger &debugger = GetCommandInterpreter().GetDebugger();
Caroline Ticee7e92b72010-09-14 22:49:06 +0000983
984 // At the moment, the only time the debugger does not have an input file handle is when this is called
985 // directly from Python, in which case it is both dangerous and unnecessary (not to mention confusing) to
986 // try to embed a running interpreter loop inside the already running Python interpreter loop, so we won't
987 // do it.
988
Greg Clayton51b1e2d2011-02-09 01:08:52 +0000989 if (!debugger.GetInputFile().IsValid())
Caroline Ticee7e92b72010-09-14 22:49:06 +0000990 return;
991
Greg Clayton66111032010-06-23 01:19:29 +0000992 InputReaderSP reader_sp (new InputReader(debugger));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000993 if (reader_sp)
994 {
995 Error error (reader_sp->Initialize (ScriptInterpreterPython::InputReaderCallback,
996 this, // baton
997 eInputReaderGranularityLine, // token size, to pass to callback function
998 NULL, // end token
999 NULL, // prompt
1000 true)); // echo input
1001
1002 if (error.Success())
1003 {
Greg Clayton66111032010-06-23 01:19:29 +00001004 debugger.PushInputReader (reader_sp);
Johnny Chen319e9272012-08-17 23:44:35 +00001005 m_embedded_python_input_reader_sp = reader_sp;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001006 }
1007 }
1008}
1009
1010bool
1011ScriptInterpreterPython::ExecuteOneLineWithReturn (const char *in_string,
Enrico Granataa9dbf432011-10-17 21:45:27 +00001012 ScriptInterpreter::ScriptReturnType return_type,
Enrico Granata79cc6f72012-06-07 00:17:18 +00001013 void *ret_value,
Enrico Granata085577f2012-10-31 00:01:26 +00001014 const ExecuteScriptOptions &options)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001015{
Caroline Tice2f88aad2011-01-14 00:29:16 +00001016
Enrico Granata47c6f6d2011-10-24 17:22:21 +00001017 Locker locker(this,
Jim Ingham6a510852012-12-07 17:43:38 +00001018 ScriptInterpreterPython::Locker::AcquireLock
1019 | ScriptInterpreterPython::Locker::InitSession
1020 | (options.GetSetLLDBGlobals() ? ScriptInterpreterPython::Locker::InitGlobals : 0),
Enrico Granata085577f2012-10-31 00:01:26 +00001021 ScriptInterpreterPython::Locker::FreeAcquiredLock | (options.GetSetLLDBGlobals() ? ScriptInterpreterPython::Locker::TearDownSession : 0));
Caroline Tice2f88aad2011-01-14 00:29:16 +00001022
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001023 PyObject *py_return = NULL;
1024 PyObject *mainmod = PyImport_AddModule ("__main__");
1025 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice2f88aad2011-01-14 00:29:16 +00001026 PyObject *locals = NULL;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001027 PyObject *py_error = NULL;
Johnny Chen0a76c282011-08-11 19:17:45 +00001028 bool ret_success = false;
Caroline Tice2f88aad2011-01-14 00:29:16 +00001029 bool should_decrement_locals = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001030 int success;
Caroline Tice2f88aad2011-01-14 00:29:16 +00001031
Enrico Granataa73b7df2012-03-06 23:42:15 +00001032 locals = FindSessionDictionary(m_dictionary_name.c_str());
1033
Caroline Tice2f88aad2011-01-14 00:29:16 +00001034 if (locals == NULL)
1035 {
1036 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
1037 should_decrement_locals = true;
1038 }
1039
1040 if (locals == NULL)
1041 {
1042 locals = globals;
1043 should_decrement_locals = false;
1044 }
1045
1046 py_error = PyErr_Occurred();
1047 if (py_error != NULL)
1048 PyErr_Clear();
1049
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001050 if (in_string != NULL)
1051 {
Enrico Granata79cc6f72012-06-07 00:17:18 +00001052 { // scope for PythonInputReaderManager
Enrico Granata085577f2012-10-31 00:01:26 +00001053 PythonInputReaderManager py_input(options.GetEnableIO() ? this : NULL);
Enrico Granata79cc6f72012-06-07 00:17:18 +00001054 py_return = PyRun_String (in_string, Py_eval_input, globals, locals);
1055 if (py_return == NULL)
1056 {
1057 py_error = PyErr_Occurred ();
1058 if (py_error != NULL)
1059 PyErr_Clear ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001060
Enrico Granata79cc6f72012-06-07 00:17:18 +00001061 py_return = PyRun_String (in_string, Py_single_input, globals, locals);
1062 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001063 }
1064
Caroline Tice2f88aad2011-01-14 00:29:16 +00001065 if (locals != NULL
1066 && should_decrement_locals)
1067 Py_DECREF (locals);
1068
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001069 if (py_return != NULL)
1070 {
1071 switch (return_type)
1072 {
Enrico Granataa9dbf432011-10-17 21:45:27 +00001073 case eScriptReturnTypeCharPtr: // "char *"
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001074 {
1075 const char format[3] = "s#";
Enrico Granata99f0b8f2011-08-17 01:30:04 +00001076 success = PyArg_Parse (py_return, format, (char **) ret_value);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001077 break;
1078 }
Enrico Granataa9dbf432011-10-17 21:45:27 +00001079 case eScriptReturnTypeCharStrOrNone: // char* or NULL if py_return == Py_None
Enrico Granatabe93a352011-08-16 16:49:25 +00001080 {
1081 const char format[3] = "z";
Enrico Granata99f0b8f2011-08-17 01:30:04 +00001082 success = PyArg_Parse (py_return, format, (char **) ret_value);
Enrico Granatabe93a352011-08-16 16:49:25 +00001083 break;
1084 }
Enrico Granataa9dbf432011-10-17 21:45:27 +00001085 case eScriptReturnTypeBool:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001086 {
1087 const char format[2] = "b";
1088 success = PyArg_Parse (py_return, format, (bool *) ret_value);
1089 break;
1090 }
Enrico Granataa9dbf432011-10-17 21:45:27 +00001091 case eScriptReturnTypeShortInt:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001092 {
1093 const char format[2] = "h";
1094 success = PyArg_Parse (py_return, format, (short *) ret_value);
1095 break;
1096 }
Enrico Granataa9dbf432011-10-17 21:45:27 +00001097 case eScriptReturnTypeShortIntUnsigned:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001098 {
1099 const char format[2] = "H";
1100 success = PyArg_Parse (py_return, format, (unsigned short *) ret_value);
1101 break;
1102 }
Enrico Granataa9dbf432011-10-17 21:45:27 +00001103 case eScriptReturnTypeInt:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001104 {
1105 const char format[2] = "i";
1106 success = PyArg_Parse (py_return, format, (int *) ret_value);
1107 break;
1108 }
Enrico Granataa9dbf432011-10-17 21:45:27 +00001109 case eScriptReturnTypeIntUnsigned:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001110 {
1111 const char format[2] = "I";
1112 success = PyArg_Parse (py_return, format, (unsigned int *) ret_value);
1113 break;
1114 }
Enrico Granataa9dbf432011-10-17 21:45:27 +00001115 case eScriptReturnTypeLongInt:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001116 {
1117 const char format[2] = "l";
1118 success = PyArg_Parse (py_return, format, (long *) ret_value);
1119 break;
1120 }
Enrico Granataa9dbf432011-10-17 21:45:27 +00001121 case eScriptReturnTypeLongIntUnsigned:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001122 {
1123 const char format[2] = "k";
1124 success = PyArg_Parse (py_return, format, (unsigned long *) ret_value);
1125 break;
1126 }
Enrico Granataa9dbf432011-10-17 21:45:27 +00001127 case eScriptReturnTypeLongLong:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001128 {
1129 const char format[2] = "L";
1130 success = PyArg_Parse (py_return, format, (long long *) ret_value);
1131 break;
1132 }
Enrico Granataa9dbf432011-10-17 21:45:27 +00001133 case eScriptReturnTypeLongLongUnsigned:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001134 {
1135 const char format[2] = "K";
1136 success = PyArg_Parse (py_return, format, (unsigned long long *) ret_value);
1137 break;
1138 }
Enrico Granataa9dbf432011-10-17 21:45:27 +00001139 case eScriptReturnTypeFloat:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001140 {
1141 const char format[2] = "f";
1142 success = PyArg_Parse (py_return, format, (float *) ret_value);
1143 break;
1144 }
Enrico Granataa9dbf432011-10-17 21:45:27 +00001145 case eScriptReturnTypeDouble:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001146 {
1147 const char format[2] = "d";
1148 success = PyArg_Parse (py_return, format, (double *) ret_value);
1149 break;
1150 }
Enrico Granataa9dbf432011-10-17 21:45:27 +00001151 case eScriptReturnTypeChar:
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001152 {
1153 const char format[2] = "c";
1154 success = PyArg_Parse (py_return, format, (char *) ret_value);
1155 break;
1156 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001157 }
1158 Py_DECREF (py_return);
1159 if (success)
1160 ret_success = true;
1161 else
1162 ret_success = false;
1163 }
1164 }
1165
1166 py_error = PyErr_Occurred();
1167 if (py_error != NULL)
1168 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001169 ret_success = false;
Enrico Granata085577f2012-10-31 00:01:26 +00001170 if (options.GetMaskoutErrors())
1171 {
1172 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
1173 PyErr_Print ();
1174 PyErr_Clear();
1175 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001176 }
Caroline Tice6760a512011-01-17 21:55:19 +00001177
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001178 return ret_success;
1179}
1180
1181bool
Enrico Granata085577f2012-10-31 00:01:26 +00001182ScriptInterpreterPython::ExecuteMultipleLines (const char *in_string, const ExecuteScriptOptions &options)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001183{
Enrico Granata47c6f6d2011-10-24 17:22:21 +00001184
1185
1186 Locker locker(this,
Jim Ingham6a510852012-12-07 17:43:38 +00001187 ScriptInterpreterPython::Locker::AcquireLock
1188 | ScriptInterpreterPython::Locker::InitSession
1189 | (options.GetSetLLDBGlobals() ? ScriptInterpreterPython::Locker::InitGlobals : 0),
Enrico Granata085577f2012-10-31 00:01:26 +00001190 ScriptInterpreterPython::Locker::FreeAcquiredLock | (options.GetSetLLDBGlobals() ? ScriptInterpreterPython::Locker::TearDownSession : 0));
Caroline Tice2f88aad2011-01-14 00:29:16 +00001191
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001192 bool success = false;
1193 PyObject *py_return = NULL;
1194 PyObject *mainmod = PyImport_AddModule ("__main__");
1195 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice2f88aad2011-01-14 00:29:16 +00001196 PyObject *locals = NULL;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001197 PyObject *py_error = NULL;
Caroline Tice2f88aad2011-01-14 00:29:16 +00001198 bool should_decrement_locals = false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001199
Enrico Granataa73b7df2012-03-06 23:42:15 +00001200 locals = FindSessionDictionary(m_dictionary_name.c_str());
1201
Caroline Tice2f88aad2011-01-14 00:29:16 +00001202 if (locals == NULL)
1203 {
1204 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
1205 should_decrement_locals = true;
1206 }
1207
1208 if (locals == NULL)
1209 {
1210 locals = globals;
1211 should_decrement_locals = false;
1212 }
1213
1214 py_error = PyErr_Occurred();
1215 if (py_error != NULL)
1216 PyErr_Clear();
1217
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001218 if (in_string != NULL)
1219 {
1220 struct _node *compiled_node = PyParser_SimpleParseString (in_string, Py_file_input);
1221 if (compiled_node)
1222 {
1223 PyCodeObject *compiled_code = PyNode_Compile (compiled_node, "temp.py");
1224 if (compiled_code)
1225 {
Enrico Granata79cc6f72012-06-07 00:17:18 +00001226 { // scope for PythonInputReaderManager
Enrico Granata085577f2012-10-31 00:01:26 +00001227 PythonInputReaderManager py_input(options.GetEnableIO() ? this : NULL);
Enrico Granata79cc6f72012-06-07 00:17:18 +00001228 py_return = PyEval_EvalCode (compiled_code, globals, locals);
1229 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001230 if (py_return != NULL)
1231 {
1232 success = true;
1233 Py_DECREF (py_return);
1234 }
Caroline Tice2f88aad2011-01-14 00:29:16 +00001235 if (locals && should_decrement_locals)
1236 Py_DECREF (locals);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001237 }
1238 }
1239 }
1240
1241 py_error = PyErr_Occurred ();
1242 if (py_error != NULL)
1243 {
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001244 success = false;
Enrico Granata085577f2012-10-31 00:01:26 +00001245 if (options.GetMaskoutErrors())
1246 {
1247 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
1248 PyErr_Print ();
1249 PyErr_Clear();
1250 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001251 }
1252
1253 return success;
1254}
1255
1256static const char *g_reader_instructions = "Enter your Python command(s). Type 'DONE' to end.";
1257
1258size_t
1259ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback
1260(
1261 void *baton,
Greg Clayton66111032010-06-23 01:19:29 +00001262 InputReader &reader,
Greg Claytonc6ed5422010-10-07 17:14:24 +00001263 InputReaderAction notification,
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001264 const char *bytes,
1265 size_t bytes_len
1266)
1267{
Caroline Ticed61c10b2011-06-16 16:27:19 +00001268 static StringList commands_in_progress;
1269
1270 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
1271 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
1272
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001273 switch (notification)
1274 {
1275 case eInputReaderActivate:
1276 {
1277 commands_in_progress.Clear();
Caroline Ticed61c10b2011-06-16 16:27:19 +00001278 if (!batch_mode)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001279 {
Caroline Ticed61c10b2011-06-16 16:27:19 +00001280 out_stream->Printf ("%s\n", g_reader_instructions);
Greg Clayton66111032010-06-23 01:19:29 +00001281 if (reader.GetPrompt())
Caroline Ticed61c10b2011-06-16 16:27:19 +00001282 out_stream->Printf ("%s", reader.GetPrompt());
1283 out_stream->Flush ();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001284 }
1285 }
1286 break;
1287
1288 case eInputReaderDeactivate:
1289 break;
1290
1291 case eInputReaderReactivate:
Caroline Ticed61c10b2011-06-16 16:27:19 +00001292 if (reader.GetPrompt() && !batch_mode)
Caroline Tice04a339a2010-10-27 18:34:42 +00001293 {
Caroline Ticed61c10b2011-06-16 16:27:19 +00001294 out_stream->Printf ("%s", reader.GetPrompt());
1295 out_stream->Flush ();
Caroline Tice04a339a2010-10-27 18:34:42 +00001296 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001297 break;
1298
Caroline Tice969ed3d2011-05-02 20:41:46 +00001299 case eInputReaderAsynchronousOutputWritten:
1300 break;
1301
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001302 case eInputReaderGotToken:
1303 {
1304 std::string temp_string (bytes, bytes_len);
1305 commands_in_progress.AppendString (temp_string.c_str());
Caroline Ticed61c10b2011-06-16 16:27:19 +00001306 if (!reader.IsDone() && reader.GetPrompt() && !batch_mode)
Caroline Tice04a339a2010-10-27 18:34:42 +00001307 {
Caroline Ticed61c10b2011-06-16 16:27:19 +00001308 out_stream->Printf ("%s", reader.GetPrompt());
1309 out_stream->Flush ();
Caroline Tice04a339a2010-10-27 18:34:42 +00001310 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001311 }
1312 break;
1313
Caroline Ticeefed6132010-11-19 20:47:54 +00001314 case eInputReaderEndOfFile:
1315 case eInputReaderInterrupt:
1316 // Control-c (SIGINT) & control-d both mean finish & exit.
1317 reader.SetIsDone(true);
1318
1319 // Control-c (SIGINT) ALSO means cancel; do NOT create a breakpoint command.
1320 if (notification == eInputReaderInterrupt)
1321 commands_in_progress.Clear();
1322
1323 // Fall through here...
1324
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001325 case eInputReaderDone:
1326 {
1327 BreakpointOptions *bp_options = (BreakpointOptions *)baton;
1328 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1329 data_ap->user_source.AppendList (commands_in_progress);
1330 if (data_ap.get())
1331 {
Greg Clayton66111032010-06-23 01:19:29 +00001332 ScriptInterpreter *interpreter = reader.GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001333 if (interpreter)
1334 {
1335 if (interpreter->GenerateBreakpointCommandCallbackData (data_ap->user_source,
1336 data_ap->script_source))
1337 {
Enrico Granataa73b7df2012-03-06 23:42:15 +00001338 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1339 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001340 }
Caroline Ticed61c10b2011-06-16 16:27:19 +00001341 else if (!batch_mode)
1342 {
1343 out_stream->Printf ("Warning: No command attached to breakpoint.\n");
1344 out_stream->Flush();
1345 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001346 }
1347 else
1348 {
Caroline Ticed61c10b2011-06-16 16:27:19 +00001349 if (!batch_mode)
1350 {
1351 out_stream->Printf ("Warning: Unable to find script intepreter; no command attached to breakpoint.\n");
1352 out_stream->Flush();
1353 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001354 }
1355 }
1356 }
1357 break;
1358
1359 }
1360
1361 return bytes_len;
1362}
1363
Johnny Chene9a56272012-08-09 23:09:42 +00001364size_t
1365ScriptInterpreterPython::GenerateWatchpointOptionsCommandCallback
1366(
1367 void *baton,
1368 InputReader &reader,
1369 InputReaderAction notification,
1370 const char *bytes,
1371 size_t bytes_len
1372)
1373{
1374 static StringList commands_in_progress;
1375
1376 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
1377 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
1378
1379 switch (notification)
1380 {
1381 case eInputReaderActivate:
1382 {
1383 commands_in_progress.Clear();
1384 if (!batch_mode)
1385 {
1386 out_stream->Printf ("%s\n", g_reader_instructions);
1387 if (reader.GetPrompt())
1388 out_stream->Printf ("%s", reader.GetPrompt());
1389 out_stream->Flush ();
1390 }
1391 }
1392 break;
1393
1394 case eInputReaderDeactivate:
1395 break;
1396
1397 case eInputReaderReactivate:
1398 if (reader.GetPrompt() && !batch_mode)
1399 {
1400 out_stream->Printf ("%s", reader.GetPrompt());
1401 out_stream->Flush ();
1402 }
1403 break;
1404
1405 case eInputReaderAsynchronousOutputWritten:
1406 break;
1407
1408 case eInputReaderGotToken:
1409 {
1410 std::string temp_string (bytes, bytes_len);
1411 commands_in_progress.AppendString (temp_string.c_str());
1412 if (!reader.IsDone() && reader.GetPrompt() && !batch_mode)
1413 {
1414 out_stream->Printf ("%s", reader.GetPrompt());
1415 out_stream->Flush ();
1416 }
1417 }
1418 break;
1419
1420 case eInputReaderEndOfFile:
1421 case eInputReaderInterrupt:
1422 // Control-c (SIGINT) & control-d both mean finish & exit.
1423 reader.SetIsDone(true);
1424
1425 // Control-c (SIGINT) ALSO means cancel; do NOT create a breakpoint command.
1426 if (notification == eInputReaderInterrupt)
1427 commands_in_progress.Clear();
1428
1429 // Fall through here...
1430
1431 case eInputReaderDone:
1432 {
1433 WatchpointOptions *wp_options = (WatchpointOptions *)baton;
1434 std::auto_ptr<WatchpointOptions::CommandData> data_ap(new WatchpointOptions::CommandData());
1435 data_ap->user_source.AppendList (commands_in_progress);
1436 if (data_ap.get())
1437 {
1438 ScriptInterpreter *interpreter = reader.GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
1439 if (interpreter)
1440 {
1441 if (interpreter->GenerateWatchpointCommandCallbackData (data_ap->user_source,
1442 data_ap->script_source))
1443 {
1444 BatonSP baton_sp (new WatchpointOptions::CommandBaton (data_ap.release()));
1445 wp_options->SetCallback (ScriptInterpreterPython::WatchpointCallbackFunction, baton_sp);
1446 }
1447 else if (!batch_mode)
1448 {
1449 out_stream->Printf ("Warning: No command attached to breakpoint.\n");
1450 out_stream->Flush();
1451 }
1452 }
1453 else
1454 {
1455 if (!batch_mode)
1456 {
1457 out_stream->Printf ("Warning: Unable to find script intepreter; no command attached to breakpoint.\n");
1458 out_stream->Flush();
1459 }
1460 }
1461 }
1462 }
1463 break;
1464
1465 }
1466
1467 return bytes_len;
1468}
1469
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001470void
Greg Claytona7015092010-09-18 01:14:36 +00001471ScriptInterpreterPython::CollectDataForBreakpointCommandCallback (BreakpointOptions *bp_options,
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001472 CommandReturnObject &result)
1473{
Caroline Tice2f88aad2011-01-14 00:29:16 +00001474 Debugger &debugger = GetCommandInterpreter().GetDebugger();
1475
Greg Clayton66111032010-06-23 01:19:29 +00001476 InputReaderSP reader_sp (new InputReader (debugger));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001477
1478 if (reader_sp)
1479 {
1480 Error err = reader_sp->Initialize (
1481 ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback,
1482 bp_options, // baton
1483 eInputReaderGranularityLine, // token size, for feeding data to callback function
1484 "DONE", // end token
1485 "> ", // prompt
1486 true); // echo input
1487
1488 if (err.Success())
Greg Clayton66111032010-06-23 01:19:29 +00001489 debugger.PushInputReader (reader_sp);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001490 else
1491 {
1492 result.AppendError (err.AsCString());
1493 result.SetStatus (eReturnStatusFailed);
1494 }
1495 }
1496 else
1497 {
1498 result.AppendError("out of memory");
1499 result.SetStatus (eReturnStatusFailed);
1500 }
1501}
1502
Johnny Chene9a56272012-08-09 23:09:42 +00001503void
1504ScriptInterpreterPython::CollectDataForWatchpointCommandCallback (WatchpointOptions *wp_options,
1505 CommandReturnObject &result)
1506{
1507 Debugger &debugger = GetCommandInterpreter().GetDebugger();
1508
1509 InputReaderSP reader_sp (new InputReader (debugger));
1510
1511 if (reader_sp)
1512 {
1513 Error err = reader_sp->Initialize (
1514 ScriptInterpreterPython::GenerateWatchpointOptionsCommandCallback,
1515 wp_options, // baton
1516 eInputReaderGranularityLine, // token size, for feeding data to callback function
1517 "DONE", // end token
1518 "> ", // prompt
1519 true); // echo input
1520
1521 if (err.Success())
1522 debugger.PushInputReader (reader_sp);
1523 else
1524 {
1525 result.AppendError (err.AsCString());
1526 result.SetStatus (eReturnStatusFailed);
1527 }
1528 }
1529 else
1530 {
1531 result.AppendError("out of memory");
1532 result.SetStatus (eReturnStatusFailed);
1533 }
1534}
1535
Johnny Chen45501542010-09-11 00:23:59 +00001536// Set a Python one-liner as the callback for the breakpoint.
Johnny Chen94de55d2010-09-10 18:21:10 +00001537void
Greg Claytona7015092010-09-18 01:14:36 +00001538ScriptInterpreterPython::SetBreakpointCommandCallback (BreakpointOptions *bp_options,
Johnny Chen94de55d2010-09-10 18:21:10 +00001539 const char *oneliner)
1540{
1541 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1542
1543 // It's necessary to set both user_source and script_source to the oneliner.
1544 // The former is used to generate callback description (as in breakpoint command list)
1545 // while the latter is used for Python to interpret during the actual callback.
Caroline Tice988efc12010-09-27 21:35:15 +00001546
Johnny Chen94de55d2010-09-10 18:21:10 +00001547 data_ap->user_source.AppendString (oneliner);
Johnny Chene9a56272012-08-09 23:09:42 +00001548 data_ap->script_source.assign (oneliner);
Johnny Chen94de55d2010-09-10 18:21:10 +00001549
Caroline Tice988efc12010-09-27 21:35:15 +00001550 if (GenerateBreakpointCommandCallbackData (data_ap->user_source, data_ap->script_source))
1551 {
Enrico Granataa73b7df2012-03-06 23:42:15 +00001552 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1553 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
Caroline Tice988efc12010-09-27 21:35:15 +00001554 }
1555
Johnny Chen94de55d2010-09-10 18:21:10 +00001556 return;
1557}
1558
Johnny Chene9a56272012-08-09 23:09:42 +00001559// Set a Python one-liner as the callback for the watchpoint.
1560void
1561ScriptInterpreterPython::SetWatchpointCommandCallback (WatchpointOptions *wp_options,
1562 const char *oneliner)
1563{
1564 std::auto_ptr<WatchpointOptions::CommandData> data_ap(new WatchpointOptions::CommandData());
1565
1566 // It's necessary to set both user_source and script_source to the oneliner.
1567 // The former is used to generate callback description (as in watchpoint command list)
1568 // while the latter is used for Python to interpret during the actual callback.
1569
1570 data_ap->user_source.AppendString (oneliner);
1571 data_ap->script_source.assign (oneliner);
1572
1573 if (GenerateWatchpointCommandCallbackData (data_ap->user_source, data_ap->script_source))
1574 {
1575 BatonSP baton_sp (new WatchpointOptions::CommandBaton (data_ap.release()));
1576 wp_options->SetCallback (ScriptInterpreterPython::WatchpointCallbackFunction, baton_sp);
1577 }
1578
1579 return;
1580}
1581
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001582bool
1583ScriptInterpreterPython::ExportFunctionDefinitionToInterpreter (StringList &function_def)
1584{
1585 // Convert StringList to one long, newline delimited, const char *.
Enrico Granataa73b7df2012-03-06 23:42:15 +00001586 std::string function_def_string(function_def.CopyList());
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001587
Enrico Granata085577f2012-10-31 00:01:26 +00001588 return ExecuteMultipleLines (function_def_string.c_str(), ScriptInterpreter::ExecuteScriptOptions().SetEnableIO(false));
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001589}
1590
Enrico Granataf2bbf712011-07-15 02:26:42 +00001591bool
Enrico Granataa73b7df2012-03-06 23:42:15 +00001592ScriptInterpreterPython::GenerateFunction(const char *signature, const StringList &input)
Enrico Granataf2bbf712011-07-15 02:26:42 +00001593{
1594 int num_lines = input.GetSize ();
1595 if (num_lines == 0)
1596 return false;
Enrico Granataa73b7df2012-03-06 23:42:15 +00001597
1598 if (!signature || *signature == 0)
1599 return false;
1600
Enrico Granataf2bbf712011-07-15 02:26:42 +00001601 StreamString sstr;
1602 StringList auto_generated_function;
Enrico Granataa73b7df2012-03-06 23:42:15 +00001603 auto_generated_function.AppendString (signature);
Enrico Granataf2bbf712011-07-15 02:26:42 +00001604 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
Enrico Granata40d55712012-08-08 02:06:30 +00001605 auto_generated_function.AppendString (" new_keys = internal_dict.keys()"); // Make a list of keys in the session dict
Enrico Granataf2bbf712011-07-15 02:26:42 +00001606 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
Enrico Granata40d55712012-08-08 02:06:30 +00001607 auto_generated_function.AppendString (" global_dict.update (internal_dict)"); // Add the session dictionary to the
Enrico Granataf2bbf712011-07-15 02:26:42 +00001608 // global dictionary.
1609
1610 // Wrap everything up inside the function, increasing the indentation.
1611
Enrico Granata070db182013-01-07 23:09:58 +00001612 auto_generated_function.AppendString(" if True:");
Enrico Granataf2bbf712011-07-15 02:26:42 +00001613 for (int i = 0; i < num_lines; ++i)
1614 {
1615 sstr.Clear ();
Enrico Granata070db182013-01-07 23:09:58 +00001616 sstr.Printf (" %s", input.GetStringAtIndex (i));
Enrico Granataf2bbf712011-07-15 02:26:42 +00001617 auto_generated_function.AppendString (sstr.GetData());
1618 }
1619 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
Enrico Granata40d55712012-08-08 02:06:30 +00001620 auto_generated_function.AppendString (" internal_dict[key] = global_dict[key]"); // Update session dict values
Enrico Granataf2bbf712011-07-15 02:26:42 +00001621 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1622 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1623
1624 // Verify that the results are valid Python.
1625
1626 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1627 return false;
1628
1629 return true;
1630
1631}
1632
Enrico Granataf2bbf712011-07-15 02:26:42 +00001633bool
Enrico Granataa73b7df2012-03-06 23:42:15 +00001634ScriptInterpreterPython::GenerateTypeScriptFunction (StringList &user_input, std::string& output, void* name_token)
Enrico Granataf2bbf712011-07-15 02:26:42 +00001635{
Enrico Granataa73b7df2012-03-06 23:42:15 +00001636 static uint32_t num_created_functions = 0;
Enrico Granataf2bbf712011-07-15 02:26:42 +00001637 user_input.RemoveBlankLines ();
Enrico Granataf2bbf712011-07-15 02:26:42 +00001638 StreamString sstr;
1639
1640 // Check to see if we have any data; if not, just return.
1641 if (user_input.GetSize() == 0)
1642 return false;
1643
1644 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1645 // ValueObject as parameter to the function.
1646
Enrico Granataa73b7df2012-03-06 23:42:15 +00001647 std::string auto_generated_function_name(GenerateUniqueName("lldb_autogen_python_type_print_func", num_created_functions, name_token));
Enrico Granata40d55712012-08-08 02:06:30 +00001648 sstr.Printf ("def %s (valobj, internal_dict):", auto_generated_function_name.c_str());
Enrico Granataf2bbf712011-07-15 02:26:42 +00001649
Enrico Granataa73b7df2012-03-06 23:42:15 +00001650 if (!GenerateFunction(sstr.GetData(), user_input))
Enrico Granataf2bbf712011-07-15 02:26:42 +00001651 return false;
Enrico Granataa73b7df2012-03-06 23:42:15 +00001652
Enrico Granataf2bbf712011-07-15 02:26:42 +00001653 // Store the name of the auto-generated function to be called.
Enrico Granataa73b7df2012-03-06 23:42:15 +00001654 output.assign(auto_generated_function_name);
Enrico Granataf2bbf712011-07-15 02:26:42 +00001655 return true;
1656}
1657
Enrico Granatac53114e2011-07-25 16:59:05 +00001658bool
Enrico Granataa73b7df2012-03-06 23:42:15 +00001659ScriptInterpreterPython::GenerateScriptAliasFunction (StringList &user_input, std::string &output)
Enrico Granatabe93a352011-08-16 16:49:25 +00001660{
Enrico Granataa73b7df2012-03-06 23:42:15 +00001661 static uint32_t num_created_functions = 0;
Enrico Granatabe93a352011-08-16 16:49:25 +00001662 user_input.RemoveBlankLines ();
Enrico Granatabe93a352011-08-16 16:49:25 +00001663 StreamString sstr;
1664
1665 // Check to see if we have any data; if not, just return.
1666 if (user_input.GetSize() == 0)
1667 return false;
1668
Enrico Granataa73b7df2012-03-06 23:42:15 +00001669 std::string auto_generated_function_name(GenerateUniqueName("lldb_autogen_python_cmd_alias_func", num_created_functions));
1670
Enrico Granata40d55712012-08-08 02:06:30 +00001671 sstr.Printf ("def %s (debugger, args, result, internal_dict):", auto_generated_function_name.c_str());
Enrico Granatabe93a352011-08-16 16:49:25 +00001672
Enrico Granataa73b7df2012-03-06 23:42:15 +00001673 if (!GenerateFunction(sstr.GetData(),user_input))
Enrico Granatabe93a352011-08-16 16:49:25 +00001674 return false;
1675
1676 // Store the name of the auto-generated function to be called.
Enrico Granataa73b7df2012-03-06 23:42:15 +00001677 output.assign(auto_generated_function_name);
Enrico Granatabe93a352011-08-16 16:49:25 +00001678 return true;
1679}
1680
1681
1682bool
Enrico Granataa73b7df2012-03-06 23:42:15 +00001683ScriptInterpreterPython::GenerateTypeSynthClass (StringList &user_input, std::string &output, void* name_token)
Enrico Granatac53114e2011-07-25 16:59:05 +00001684{
Enrico Granataa73b7df2012-03-06 23:42:15 +00001685 static uint32_t num_created_classes = 0;
Enrico Granatac53114e2011-07-25 16:59:05 +00001686 user_input.RemoveBlankLines ();
1687 int num_lines = user_input.GetSize ();
1688 StreamString sstr;
1689
1690 // Check to see if we have any data; if not, just return.
1691 if (user_input.GetSize() == 0)
1692 return false;
1693
1694 // Wrap all user input into a Python class
1695
Enrico Granataa73b7df2012-03-06 23:42:15 +00001696 std::string auto_generated_class_name(GenerateUniqueName("lldb_autogen_python_type_synth_class",num_created_classes,name_token));
Enrico Granatac53114e2011-07-25 16:59:05 +00001697
Enrico Granatac53114e2011-07-25 16:59:05 +00001698 StringList auto_generated_class;
1699
1700 // Create the function name & definition string.
1701
1702 sstr.Printf ("class %s:", auto_generated_class_name.c_str());
1703 auto_generated_class.AppendString (sstr.GetData());
1704
1705 // Wrap everything up inside the class, increasing the indentation.
Enrico Granata070db182013-01-07 23:09:58 +00001706 // we don't need to play any fancy indentation tricks here because there is no
1707 // surrounding code whose indentation we need to honor
Enrico Granatac53114e2011-07-25 16:59:05 +00001708 for (int i = 0; i < num_lines; ++i)
1709 {
1710 sstr.Clear ();
1711 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1712 auto_generated_class.AppendString (sstr.GetData());
1713 }
1714
1715
1716 // Verify that the results are valid Python.
1717 // (even though the method is ExportFunctionDefinitionToInterpreter, a class will actually be exported)
1718 // (TODO: rename that method to ExportDefinitionToInterpreter)
1719 if (!ExportFunctionDefinitionToInterpreter (auto_generated_class))
1720 return false;
1721
1722 // Store the name of the auto-generated class
1723
Enrico Granataa73b7df2012-03-06 23:42:15 +00001724 output.assign(auto_generated_class_name);
Enrico Granatac53114e2011-07-25 16:59:05 +00001725 return true;
1726}
1727
Enrico Granataa73b7df2012-03-06 23:42:15 +00001728lldb::ScriptInterpreterObjectSP
Enrico Granata57907592012-08-24 00:30:47 +00001729ScriptInterpreterPython::CreateOSPlugin (std::string class_name,
1730 lldb::ProcessSP process_sp)
1731{
1732 if (class_name.empty())
1733 return lldb::ScriptInterpreterObjectSP();
1734
1735 if (!process_sp)
1736 return lldb::ScriptInterpreterObjectSP();
1737
1738 void* ret_val;
1739
1740 {
Enrico Granata4300fab2012-08-24 01:34:39 +00001741 Locker py_lock(this,Locker::AcquireLock,Locker::FreeLock);
Enrico Granata57907592012-08-24 00:30:47 +00001742 ret_val = g_swig_create_os_plugin (class_name,
1743 m_dictionary_name.c_str(),
1744 process_sp);
1745 }
1746
1747 return MakeScriptObject(ret_val);
1748}
1749
1750lldb::ScriptInterpreterObjectSP
1751ScriptInterpreterPython::OSPlugin_QueryForRegisterInfo (lldb::ScriptInterpreterObjectSP object)
1752{
Enrico Granata4300fab2012-08-24 01:34:39 +00001753 Locker py_lock(this,Locker::AcquireLock,Locker::FreeLock);
1754
Enrico Granata57907592012-08-24 00:30:47 +00001755 static char callee_name[] = "get_register_info";
1756
1757 if (!object)
1758 return lldb::ScriptInterpreterObjectSP();
1759
1760 PyObject* implementor = (PyObject*)object->GetObject();
1761
1762 if (implementor == NULL || implementor == Py_None)
1763 return lldb::ScriptInterpreterObjectSP();
1764
1765 PyObject* pmeth = PyObject_GetAttrString(implementor, callee_name);
1766
1767 if (PyErr_Occurred())
1768 {
1769 PyErr_Clear();
1770 }
1771
1772 if (pmeth == NULL || pmeth == Py_None)
1773 {
1774 Py_XDECREF(pmeth);
1775 return lldb::ScriptInterpreterObjectSP();
1776 }
1777
1778 if (PyCallable_Check(pmeth) == 0)
1779 {
1780 if (PyErr_Occurred())
1781 {
1782 PyErr_Clear();
1783 }
1784
1785 Py_XDECREF(pmeth);
1786 return lldb::ScriptInterpreterObjectSP();
1787 }
1788
1789 if (PyErr_Occurred())
1790 {
1791 PyErr_Clear();
1792 }
1793
1794 Py_XDECREF(pmeth);
1795
1796 // right now we know this function exists and is callable..
1797 PyObject* py_return = PyObject_CallMethod(implementor, callee_name, NULL);
1798
1799 // if it fails, print the error but otherwise go on
1800 if (PyErr_Occurred())
1801 {
1802 PyErr_Print();
1803 PyErr_Clear();
1804 }
1805
1806 return MakeScriptObject(py_return);
1807}
1808
1809lldb::ScriptInterpreterObjectSP
Enrico Granata6167ab22012-08-24 00:51:29 +00001810ScriptInterpreterPython::OSPlugin_QueryForThreadsInfo (lldb::ScriptInterpreterObjectSP object)
1811{
Enrico Granata4300fab2012-08-24 01:34:39 +00001812 Locker py_lock(this,Locker::AcquireLock,Locker::FreeLock);
1813
Enrico Granata6167ab22012-08-24 00:51:29 +00001814 static char callee_name[] = "get_thread_info";
1815
1816 if (!object)
1817 return lldb::ScriptInterpreterObjectSP();
1818
1819 PyObject* implementor = (PyObject*)object->GetObject();
1820
1821 if (implementor == NULL || implementor == Py_None)
1822 return lldb::ScriptInterpreterObjectSP();
1823
1824 PyObject* pmeth = PyObject_GetAttrString(implementor, callee_name);
1825
1826 if (PyErr_Occurred())
1827 {
1828 PyErr_Clear();
1829 }
1830
1831 if (pmeth == NULL || pmeth == Py_None)
1832 {
1833 Py_XDECREF(pmeth);
1834 return lldb::ScriptInterpreterObjectSP();
1835 }
1836
1837 if (PyCallable_Check(pmeth) == 0)
1838 {
1839 if (PyErr_Occurred())
1840 {
1841 PyErr_Clear();
1842 }
1843
1844 Py_XDECREF(pmeth);
1845 return lldb::ScriptInterpreterObjectSP();
1846 }
1847
1848 if (PyErr_Occurred())
1849 {
1850 PyErr_Clear();
1851 }
1852
1853 Py_XDECREF(pmeth);
1854
1855 // right now we know this function exists and is callable..
1856 PyObject* py_return = PyObject_CallMethod(implementor, callee_name, NULL);
1857
1858 // if it fails, print the error but otherwise go on
1859 if (PyErr_Occurred())
1860 {
1861 PyErr_Print();
1862 PyErr_Clear();
1863 }
1864
1865 return MakeScriptObject(py_return);
1866}
1867
1868lldb::ScriptInterpreterObjectSP
Greg Clayton435ce132012-08-24 05:45:15 +00001869ScriptInterpreterPython::OSPlugin_QueryForRegisterContextData (lldb::ScriptInterpreterObjectSP object,
1870 lldb::tid_t thread_id)
Enrico Granata6167ab22012-08-24 00:51:29 +00001871{
Enrico Granata4300fab2012-08-24 01:34:39 +00001872 Locker py_lock(this,Locker::AcquireLock,Locker::FreeLock);
1873
Enrico Granata6167ab22012-08-24 00:51:29 +00001874 static char callee_name[] = "get_register_data";
1875 static char param_format[] = "l";
1876
1877 if (!object)
1878 return lldb::ScriptInterpreterObjectSP();
1879
1880 PyObject* implementor = (PyObject*)object->GetObject();
1881
1882 if (implementor == NULL || implementor == Py_None)
1883 return lldb::ScriptInterpreterObjectSP();
1884
1885 PyObject* pmeth = PyObject_GetAttrString(implementor, callee_name);
1886
1887 if (PyErr_Occurred())
1888 {
1889 PyErr_Clear();
1890 }
1891
1892 if (pmeth == NULL || pmeth == Py_None)
1893 {
1894 Py_XDECREF(pmeth);
1895 return lldb::ScriptInterpreterObjectSP();
1896 }
1897
1898 if (PyCallable_Check(pmeth) == 0)
1899 {
1900 if (PyErr_Occurred())
1901 {
1902 PyErr_Clear();
1903 }
1904
1905 Py_XDECREF(pmeth);
1906 return lldb::ScriptInterpreterObjectSP();
1907 }
1908
1909 if (PyErr_Occurred())
1910 {
1911 PyErr_Clear();
1912 }
1913
1914 Py_XDECREF(pmeth);
1915
1916 // right now we know this function exists and is callable..
1917 PyObject* py_return = PyObject_CallMethod(implementor, callee_name, param_format, thread_id);
1918
1919 // if it fails, print the error but otherwise go on
1920 if (PyErr_Occurred())
1921 {
1922 PyErr_Print();
1923 PyErr_Clear();
1924 }
1925
1926 return MakeScriptObject(py_return);
1927}
1928
1929lldb::ScriptInterpreterObjectSP
Enrico Granataa37a0652011-07-24 00:14:56 +00001930ScriptInterpreterPython::CreateSyntheticScriptedProvider (std::string class_name,
1931 lldb::ValueObjectSP valobj)
1932{
1933 if (class_name.empty())
Enrico Granataa73b7df2012-03-06 23:42:15 +00001934 return lldb::ScriptInterpreterObjectSP();
Enrico Granataa37a0652011-07-24 00:14:56 +00001935
1936 if (!valobj.get())
Enrico Granataa73b7df2012-03-06 23:42:15 +00001937 return lldb::ScriptInterpreterObjectSP();
Enrico Granataa37a0652011-07-24 00:14:56 +00001938
Greg Claytoncc4d0142012-02-17 07:49:44 +00001939 ExecutionContext exe_ctx (valobj->GetExecutionContextRef());
1940 Target *target = exe_ctx.GetTargetPtr();
Enrico Granataa37a0652011-07-24 00:14:56 +00001941
1942 if (!target)
Enrico Granataa73b7df2012-03-06 23:42:15 +00001943 return lldb::ScriptInterpreterObjectSP();
Enrico Granataa37a0652011-07-24 00:14:56 +00001944
1945 Debugger &debugger = target->GetDebugger();
1946 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1947 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1948
1949 if (!script_interpreter)
Enrico Granataa73b7df2012-03-06 23:42:15 +00001950 return lldb::ScriptInterpreterObjectSP();
Enrico Granataa37a0652011-07-24 00:14:56 +00001951
1952 void* ret_val;
Enrico Granata47c6f6d2011-10-24 17:22:21 +00001953
Enrico Granataa37a0652011-07-24 00:14:56 +00001954 {
Enrico Granata47c6f6d2011-10-24 17:22:21 +00001955 Locker py_lock(this);
Enrico Granatae3e91512012-10-22 18:18:36 +00001956 ret_val = g_swig_synthetic_script (class_name,
1957 python_interpreter->m_dictionary_name.c_str(),
1958 valobj);
Enrico Granataa37a0652011-07-24 00:14:56 +00001959 }
1960
Enrico Granataa73b7df2012-03-06 23:42:15 +00001961 return MakeScriptObject(ret_val);
Enrico Granataa37a0652011-07-24 00:14:56 +00001962}
1963
Enrico Granataf2bbf712011-07-15 02:26:42 +00001964bool
Enrico Granataa73b7df2012-03-06 23:42:15 +00001965ScriptInterpreterPython::GenerateTypeScriptFunction (const char* oneliner, std::string& output, void* name_token)
Enrico Granataf2bbf712011-07-15 02:26:42 +00001966{
Enrico Granata061858c2012-02-15 02:34:21 +00001967 StringList input;
1968 input.SplitIntoLines(oneliner, strlen(oneliner));
1969 return GenerateTypeScriptFunction(input, output, name_token);
Enrico Granataf2bbf712011-07-15 02:26:42 +00001970}
1971
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001972bool
Enrico Granataa73b7df2012-03-06 23:42:15 +00001973ScriptInterpreterPython::GenerateTypeSynthClass (const char* oneliner, std::string& output, void* name_token)
Enrico Granata061858c2012-02-15 02:34:21 +00001974{
1975 StringList input;
1976 input.SplitIntoLines(oneliner, strlen(oneliner));
1977 return GenerateTypeSynthClass(input, output, name_token);
1978}
1979
1980
1981bool
Enrico Granataa73b7df2012-03-06 23:42:15 +00001982ScriptInterpreterPython::GenerateBreakpointCommandCallbackData (StringList &user_input, std::string& output)
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001983{
Enrico Granataa73b7df2012-03-06 23:42:15 +00001984 static uint32_t num_created_functions = 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001985 user_input.RemoveBlankLines ();
Caroline Tice18474c92010-09-27 18:00:20 +00001986 StreamString sstr;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001987
Caroline Ticeefed6132010-11-19 20:47:54 +00001988 if (user_input.GetSize() == 0)
1989 return false;
1990
Enrico Granataa73b7df2012-03-06 23:42:15 +00001991 std::string auto_generated_function_name(GenerateUniqueName("lldb_autogen_python_bp_callback_func_",num_created_functions));
Enrico Granata40d55712012-08-08 02:06:30 +00001992 sstr.Printf ("def %s (frame, bp_loc, internal_dict):", auto_generated_function_name.c_str());
Caroline Tice2f88aad2011-01-14 00:29:16 +00001993
Enrico Granataa73b7df2012-03-06 23:42:15 +00001994 if (!GenerateFunction(sstr.GetData(), user_input))
Caroline Tice650b9262010-09-21 19:25:28 +00001995 return false;
Enrico Granataa73b7df2012-03-06 23:42:15 +00001996
Caroline Tice18474c92010-09-27 18:00:20 +00001997 // Store the name of the auto-generated function to be called.
Enrico Granataa73b7df2012-03-06 23:42:15 +00001998 output.assign(auto_generated_function_name);
Caroline Tice18474c92010-09-27 18:00:20 +00001999 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002000}
2001
Enrico Granata7bc0ec32012-02-29 03:28:49 +00002002bool
Johnny Chene9a56272012-08-09 23:09:42 +00002003ScriptInterpreterPython::GenerateWatchpointCommandCallbackData (StringList &user_input, std::string& output)
2004{
2005 static uint32_t num_created_functions = 0;
2006 user_input.RemoveBlankLines ();
2007 StreamString sstr;
2008
2009 if (user_input.GetSize() == 0)
2010 return false;
2011
2012 std::string auto_generated_function_name(GenerateUniqueName("lldb_autogen_python_wp_callback_func_",num_created_functions));
2013 sstr.Printf ("def %s (frame, wp, internal_dict):", auto_generated_function_name.c_str());
2014
2015 if (!GenerateFunction(sstr.GetData(), user_input))
2016 return false;
2017
2018 // Store the name of the auto-generated function to be called.
2019 output.assign(auto_generated_function_name);
2020 return true;
2021}
2022
2023bool
Enrico Granata7bc0ec32012-02-29 03:28:49 +00002024ScriptInterpreterPython::GetScriptedSummary (const char *python_function_name,
2025 lldb::ValueObjectSP valobj,
2026 lldb::ScriptInterpreterObjectSP& callee_wrapper_sp,
2027 std::string& retval)
Enrico Granataf2bbf712011-07-15 02:26:42 +00002028{
2029
Enrico Granata7bc0ec32012-02-29 03:28:49 +00002030 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
Enrico Granataf2bbf712011-07-15 02:26:42 +00002031
2032 if (!valobj.get())
Enrico Granata7bc0ec32012-02-29 03:28:49 +00002033 {
2034 retval.assign("<no object>");
2035 return false;
2036 }
Enrico Granataf2bbf712011-07-15 02:26:42 +00002037
Enrico Granata7bc0ec32012-02-29 03:28:49 +00002038 void* old_callee = (callee_wrapper_sp ? callee_wrapper_sp->GetObject() : NULL);
2039 void* new_callee = old_callee;
Enrico Granataf2bbf712011-07-15 02:26:42 +00002040
Enrico Granata7bc0ec32012-02-29 03:28:49 +00002041 bool ret_val;
Enrico Granataf2bbf712011-07-15 02:26:42 +00002042 if (python_function_name
2043 && *python_function_name)
2044 {
Enrico Granataf2bbf712011-07-15 02:26:42 +00002045 {
Enrico Granata7bc0ec32012-02-29 03:28:49 +00002046 Locker py_lock(this);
2047 {
2048 Timer scoped_timer ("g_swig_typescript_callback","g_swig_typescript_callback");
2049 ret_val = g_swig_typescript_callback (python_function_name,
2050 FindSessionDictionary(m_dictionary_name.c_str()),
2051 valobj,
2052 &new_callee,
2053 retval);
2054 }
Enrico Granataf2bbf712011-07-15 02:26:42 +00002055 }
2056 }
2057 else
Enrico Granata7bc0ec32012-02-29 03:28:49 +00002058 {
2059 retval.assign("<no function name>");
2060 return false;
2061 }
2062
2063 if (new_callee && old_callee != new_callee)
2064 callee_wrapper_sp = MakeScriptObject(new_callee);
Enrico Granataf2bbf712011-07-15 02:26:42 +00002065
2066 return ret_val;
2067
2068}
2069
Greg Claytonc6ed5422010-10-07 17:14:24 +00002070bool
2071ScriptInterpreterPython::BreakpointCallbackFunction
2072(
2073 void *baton,
2074 StoppointCallbackContext *context,
2075 user_id_t break_id,
2076 user_id_t break_loc_id
2077)
2078{
2079 BreakpointOptions::CommandData *bp_option_data = (BreakpointOptions::CommandData *) baton;
Enrico Granataa73b7df2012-03-06 23:42:15 +00002080 const char *python_function_name = bp_option_data->script_source.c_str();
Caroline Tice2f88aad2011-01-14 00:29:16 +00002081
2082 if (!context)
2083 return true;
2084
Greg Clayton1ac04c32012-02-21 00:09:25 +00002085 ExecutionContext exe_ctx (context->exe_ctx_ref);
2086 Target *target = exe_ctx.GetTargetPtr();
Caroline Tice2f88aad2011-01-14 00:29:16 +00002087
2088 if (!target)
2089 return true;
2090
2091 Debugger &debugger = target->GetDebugger();
2092 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
2093 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
2094
2095 if (!script_interpreter)
2096 return true;
Greg Claytonc6ed5422010-10-07 17:14:24 +00002097
2098 if (python_function_name != NULL
2099 && python_function_name[0] != '\0')
2100 {
Greg Clayton1ac04c32012-02-21 00:09:25 +00002101 const StackFrameSP stop_frame_sp (exe_ctx.GetFrameSP());
Greg Claytonc6ed5422010-10-07 17:14:24 +00002102 BreakpointSP breakpoint_sp = target->GetBreakpointByID (break_id);
Greg Claytonfc36f7912011-03-22 01:14:58 +00002103 if (breakpoint_sp)
Caroline Tice2f88aad2011-01-14 00:29:16 +00002104 {
Greg Claytonfc36f7912011-03-22 01:14:58 +00002105 const BreakpointLocationSP bp_loc_sp (breakpoint_sp->FindLocationByID (break_loc_id));
2106
2107 if (stop_frame_sp && bp_loc_sp)
Caroline Tice6760a512011-01-17 21:55:19 +00002108 {
Greg Claytonfc36f7912011-03-22 01:14:58 +00002109 bool ret_val = true;
Greg Claytonfc36f7912011-03-22 01:14:58 +00002110 {
Enrico Granata47c6f6d2011-10-24 17:22:21 +00002111 Locker py_lock(python_interpreter);
Greg Claytonfc36f7912011-03-22 01:14:58 +00002112 ret_val = g_swig_breakpoint_callback (python_function_name,
2113 python_interpreter->m_dictionary_name.c_str(),
2114 stop_frame_sp,
2115 bp_loc_sp);
Greg Claytonfc36f7912011-03-22 01:14:58 +00002116 }
2117 return ret_val;
Caroline Tice6760a512011-01-17 21:55:19 +00002118 }
Caroline Tice2f88aad2011-01-14 00:29:16 +00002119 }
Greg Claytonc6ed5422010-10-07 17:14:24 +00002120 }
2121 // We currently always true so we stop in case anything goes wrong when
2122 // trying to call the script function
2123 return true;
2124}
Caroline Tice5c2816d2010-11-10 19:18:14 +00002125
Johnny Chene9a56272012-08-09 23:09:42 +00002126bool
2127ScriptInterpreterPython::WatchpointCallbackFunction
2128(
2129 void *baton,
2130 StoppointCallbackContext *context,
2131 user_id_t watch_id
2132)
2133{
2134 WatchpointOptions::CommandData *wp_option_data = (WatchpointOptions::CommandData *) baton;
2135 const char *python_function_name = wp_option_data->script_source.c_str();
2136
2137 if (!context)
2138 return true;
2139
2140 ExecutionContext exe_ctx (context->exe_ctx_ref);
2141 Target *target = exe_ctx.GetTargetPtr();
2142
2143 if (!target)
2144 return true;
2145
2146 Debugger &debugger = target->GetDebugger();
2147 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
2148 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
2149
2150 if (!script_interpreter)
2151 return true;
2152
2153 if (python_function_name != NULL
2154 && python_function_name[0] != '\0')
2155 {
2156 const StackFrameSP stop_frame_sp (exe_ctx.GetFrameSP());
2157 WatchpointSP wp_sp = target->GetWatchpointList().FindByID (watch_id);
2158 if (wp_sp)
2159 {
2160 if (stop_frame_sp && wp_sp)
2161 {
2162 bool ret_val = true;
2163 {
2164 Locker py_lock(python_interpreter);
2165 ret_val = g_swig_watchpoint_callback (python_function_name,
2166 python_interpreter->m_dictionary_name.c_str(),
2167 stop_frame_sp,
2168 wp_sp);
2169 }
2170 return ret_val;
2171 }
2172 }
2173 }
2174 // We currently always true so we stop in case anything goes wrong when
2175 // trying to call the script function
2176 return true;
2177}
2178
Caroline Tice5c2816d2010-11-10 19:18:14 +00002179lldb::thread_result_t
2180ScriptInterpreterPython::RunEmbeddedPythonInterpreter (lldb::thread_arg_t baton)
2181{
2182 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
2183
2184 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
2185
2186 if (log)
2187 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread starting...", baton);
2188
2189 char error_str[1024];
2190 const char *pty_slave_name = script_interpreter->m_embedded_python_pty.GetSlaveName (error_str, sizeof (error_str));
Caroline Tice2f88aad2011-01-14 00:29:16 +00002191
Enrico Granata47c6f6d2011-10-24 17:22:21 +00002192 if (pty_slave_name != NULL)
Caroline Tice6760a512011-01-17 21:55:19 +00002193 {
Caroline Tice5c2816d2010-11-10 19:18:14 +00002194 StreamString run_string;
Johnny Chen2c90e992012-08-18 04:14:54 +00002195
2196 // Ensure we have the GIL before running any Python code.
2197 // Since we're only running a few one-liners and then dropping to the interpreter (which will release the GIL when needed),
2198 // we can just release the GIL after finishing our work.
2199 // If finer-grained locking is desirable, we can lock and unlock the GIL only when calling a python function.
2200 Locker locker(script_interpreter,
Jim Ingham6a510852012-12-07 17:43:38 +00002201 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession | ScriptInterpreterPython::Locker::InitGlobals,
Johnny Chen2c90e992012-08-18 04:14:54 +00002202 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
2203
Caroline Tice2f88aad2011-01-14 00:29:16 +00002204 run_string.Printf ("run_one_line (%s, 'save_stderr = sys.stderr')", script_interpreter->m_dictionary_name.c_str());
2205 PyRun_SimpleString (run_string.GetData());
2206 run_string.Clear ();
2207
2208 run_string.Printf ("run_one_line (%s, 'sys.stderr = sys.stdout')", script_interpreter->m_dictionary_name.c_str());
2209 PyRun_SimpleString (run_string.GetData());
2210 run_string.Clear ();
2211
2212 run_string.Printf ("run_one_line (%s, 'save_stdin = sys.stdin')", script_interpreter->m_dictionary_name.c_str());
2213 PyRun_SimpleString (run_string.GetData());
2214 run_string.Clear ();
2215
2216 run_string.Printf ("run_one_line (%s, \"sys.stdin = open ('%s', 'r')\")", script_interpreter->m_dictionary_name.c_str(),
2217 pty_slave_name);
2218 PyRun_SimpleString (run_string.GetData());
2219 run_string.Clear ();
2220
Johnny Chen24e99aa2011-03-11 00:28:50 +00002221 // The following call drops into the embedded interpreter loop and stays there until the
2222 // user chooses to exit from the Python interpreter.
Johnny Chen2c90e992012-08-18 04:14:54 +00002223 // This embedded interpreter will, as any Python code that performs I/O, unlock the GIL before
2224 // a system call that can hang, and lock it when the syscall has returned.
Caroline Tice2f88aad2011-01-14 00:29:16 +00002225
Johnny Chen2c90e992012-08-18 04:14:54 +00002226 // We need to surround the call to the embedded interpreter with calls to PyGILState_Ensure and
2227 // PyGILState_Release (using the Locker above). This is because Python has a global lock which must be held whenever we want
2228 // to touch any Python objects. Otherwise, if the user calls Python code, the interpreter state will be off,
2229 // and things could hang (it's happened before).
Caroline Ticec288e8c2011-03-11 00:21:55 +00002230
Caroline Tice2f88aad2011-01-14 00:29:16 +00002231 run_string.Printf ("run_python_interpreter (%s)", script_interpreter->m_dictionary_name.c_str());
2232 PyRun_SimpleString (run_string.GetData());
2233 run_string.Clear ();
Johnny Chen2c90e992012-08-18 04:14:54 +00002234
Caroline Tice2f88aad2011-01-14 00:29:16 +00002235 run_string.Printf ("run_one_line (%s, 'sys.stdin = save_stdin')", script_interpreter->m_dictionary_name.c_str());
2236 PyRun_SimpleString (run_string.GetData());
2237 run_string.Clear();
Johnny Chen2c90e992012-08-18 04:14:54 +00002238
Caroline Tice2f88aad2011-01-14 00:29:16 +00002239 run_string.Printf ("run_one_line (%s, 'sys.stderr = save_stderr')", script_interpreter->m_dictionary_name.c_str());
2240 PyRun_SimpleString (run_string.GetData());
2241 run_string.Clear();
Caroline Tice5c2816d2010-11-10 19:18:14 +00002242 }
2243
Johnny Chen319e9272012-08-17 23:44:35 +00002244 if (script_interpreter->m_embedded_python_input_reader_sp)
2245 script_interpreter->m_embedded_python_input_reader_sp->SetIsDone (true);
Caroline Tice5c2816d2010-11-10 19:18:14 +00002246
2247 script_interpreter->m_embedded_python_pty.CloseSlaveFileDescriptor();
Caroline Tice2f88aad2011-01-14 00:29:16 +00002248
Caroline Tice5c2816d2010-11-10 19:18:14 +00002249 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT);
2250 if (log)
2251 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread exiting...", baton);
2252
2253
Johnny Chen24e99aa2011-03-11 00:28:50 +00002254 // Clean up the input reader and make the debugger pop it off the stack.
Caroline Tice2f88aad2011-01-14 00:29:16 +00002255 Debugger &debugger = script_interpreter->GetCommandInterpreter().GetDebugger();
Johnny Chen319e9272012-08-17 23:44:35 +00002256 const InputReaderSP reader_sp = script_interpreter->m_embedded_python_input_reader_sp;
2257 if (reader_sp)
2258 {
2259 debugger.PopInputReader (reader_sp);
2260 script_interpreter->m_embedded_python_input_reader_sp.reset();
2261 }
Caroline Tice2f88aad2011-01-14 00:29:16 +00002262
Caroline Tice5c2816d2010-11-10 19:18:14 +00002263 return NULL;
2264}
2265
Enrico Granata79cc6f72012-06-07 00:17:18 +00002266lldb::thread_result_t
2267ScriptInterpreterPython::PythonInputReaderManager::RunPythonInputReader (lldb::thread_arg_t baton)
2268{
2269 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
2270
2271 const InputReaderSP reader_sp = script_interpreter->m_embedded_thread_input_reader_sp;
2272
2273 if (reader_sp)
2274 reader_sp->WaitOnReaderIsDone();
2275
2276 return NULL;
2277}
2278
Enrico Granataa37a0652011-07-24 00:14:56 +00002279uint32_t
Enrico Granataa73b7df2012-03-06 23:42:15 +00002280ScriptInterpreterPython::CalculateNumChildren (const lldb::ScriptInterpreterObjectSP& implementor_sp)
Enrico Granataa37a0652011-07-24 00:14:56 +00002281{
Enrico Granataa73b7df2012-03-06 23:42:15 +00002282 if (!implementor_sp)
2283 return 0;
2284
2285 void* implementor = implementor_sp->GetObject();
2286
Enrico Granataa37a0652011-07-24 00:14:56 +00002287 if (!implementor)
2288 return 0;
2289
2290 if (!g_swig_calc_children)
2291 return 0;
Enrico Granata47c6f6d2011-10-24 17:22:21 +00002292
Enrico Granataa37a0652011-07-24 00:14:56 +00002293 uint32_t ret_val = 0;
2294
Enrico Granataa37a0652011-07-24 00:14:56 +00002295 {
Enrico Granata47c6f6d2011-10-24 17:22:21 +00002296 Locker py_lock(this);
Enrico Granatae3e91512012-10-22 18:18:36 +00002297 ret_val = g_swig_calc_children (implementor);
Enrico Granataa37a0652011-07-24 00:14:56 +00002298 }
2299
2300 return ret_val;
2301}
2302
Enrico Granata9128ee22011-09-06 19:20:51 +00002303lldb::ValueObjectSP
Enrico Granataa73b7df2012-03-06 23:42:15 +00002304ScriptInterpreterPython::GetChildAtIndex (const lldb::ScriptInterpreterObjectSP& implementor_sp, uint32_t idx)
Enrico Granataa37a0652011-07-24 00:14:56 +00002305{
Enrico Granataa73b7df2012-03-06 23:42:15 +00002306 if (!implementor_sp)
2307 return lldb::ValueObjectSP();
2308
2309 void* implementor = implementor_sp->GetObject();
2310
Enrico Granataa37a0652011-07-24 00:14:56 +00002311 if (!implementor)
Enrico Granata9128ee22011-09-06 19:20:51 +00002312 return lldb::ValueObjectSP();
Enrico Granataa37a0652011-07-24 00:14:56 +00002313
Enrico Granata9128ee22011-09-06 19:20:51 +00002314 if (!g_swig_get_child_index || !g_swig_cast_to_sbvalue)
2315 return lldb::ValueObjectSP();
Enrico Granataa37a0652011-07-24 00:14:56 +00002316
Enrico Granata9128ee22011-09-06 19:20:51 +00002317 void* child_ptr = NULL;
2318 lldb::SBValue* value_sb = NULL;
2319 lldb::ValueObjectSP ret_val;
Enrico Granataa37a0652011-07-24 00:14:56 +00002320
Enrico Granataa37a0652011-07-24 00:14:56 +00002321 {
Enrico Granata47c6f6d2011-10-24 17:22:21 +00002322 Locker py_lock(this);
Enrico Granatae3e91512012-10-22 18:18:36 +00002323 child_ptr = g_swig_get_child_index (implementor,idx);
Enrico Granata9128ee22011-09-06 19:20:51 +00002324 if (child_ptr != NULL && child_ptr != Py_None)
2325 {
2326 value_sb = (lldb::SBValue*)g_swig_cast_to_sbvalue(child_ptr);
2327 if (value_sb == NULL)
2328 Py_XDECREF(child_ptr);
2329 else
Greg Claytonaa0c70e2012-11-01 21:35:16 +00002330 ret_val = value_sb->GetSP();
Enrico Granata9128ee22011-09-06 19:20:51 +00002331 }
2332 else
2333 {
2334 Py_XDECREF(child_ptr);
2335 }
Enrico Granataa37a0652011-07-24 00:14:56 +00002336 }
2337
2338 return ret_val;
2339}
2340
2341int
Enrico Granataa73b7df2012-03-06 23:42:15 +00002342ScriptInterpreterPython::GetIndexOfChildWithName (const lldb::ScriptInterpreterObjectSP& implementor_sp, const char* child_name)
Enrico Granataa37a0652011-07-24 00:14:56 +00002343{
Enrico Granataa73b7df2012-03-06 23:42:15 +00002344 if (!implementor_sp)
2345 return UINT32_MAX;
2346
2347 void* implementor = implementor_sp->GetObject();
2348
Enrico Granataa37a0652011-07-24 00:14:56 +00002349 if (!implementor)
2350 return UINT32_MAX;
2351
2352 if (!g_swig_get_index_child)
2353 return UINT32_MAX;
2354
Enrico Granataa37a0652011-07-24 00:14:56 +00002355 int ret_val = UINT32_MAX;
2356
Enrico Granataa37a0652011-07-24 00:14:56 +00002357 {
Enrico Granata47c6f6d2011-10-24 17:22:21 +00002358 Locker py_lock(this);
Enrico Granatae3e91512012-10-22 18:18:36 +00002359 ret_val = g_swig_get_index_child (implementor, child_name);
Enrico Granataa37a0652011-07-24 00:14:56 +00002360 }
2361
2362 return ret_val;
2363}
2364
Enrico Granata86cc9822012-03-19 22:58:49 +00002365bool
Enrico Granataa73b7df2012-03-06 23:42:15 +00002366ScriptInterpreterPython::UpdateSynthProviderInstance (const lldb::ScriptInterpreterObjectSP& implementor_sp)
Enrico Granata6f3533f2011-07-29 19:53:35 +00002367{
Enrico Granata86cc9822012-03-19 22:58:49 +00002368 bool ret_val = false;
2369
Enrico Granataa73b7df2012-03-06 23:42:15 +00002370 if (!implementor_sp)
Enrico Granata86cc9822012-03-19 22:58:49 +00002371 return ret_val;
Enrico Granataa73b7df2012-03-06 23:42:15 +00002372
2373 void* implementor = implementor_sp->GetObject();
2374
Enrico Granata6f3533f2011-07-29 19:53:35 +00002375 if (!implementor)
Enrico Granata86cc9822012-03-19 22:58:49 +00002376 return ret_val;
Enrico Granata6f3533f2011-07-29 19:53:35 +00002377
2378 if (!g_swig_update_provider)
Enrico Granata86cc9822012-03-19 22:58:49 +00002379 return ret_val;
Enrico Granata6f3533f2011-07-29 19:53:35 +00002380
Enrico Granata6f3533f2011-07-29 19:53:35 +00002381 {
Enrico Granata47c6f6d2011-10-24 17:22:21 +00002382 Locker py_lock(this);
Enrico Granatae3e91512012-10-22 18:18:36 +00002383 ret_val = g_swig_update_provider (implementor);
Enrico Granata6f3533f2011-07-29 19:53:35 +00002384 }
2385
Enrico Granata86cc9822012-03-19 22:58:49 +00002386 return ret_val;
Enrico Granata6f3533f2011-07-29 19:53:35 +00002387}
2388
Enrico Granatabe93a352011-08-16 16:49:25 +00002389bool
Enrico Granataadaf2822012-10-23 19:54:09 +00002390ScriptInterpreterPython::MightHaveChildrenSynthProviderInstance (const lldb::ScriptInterpreterObjectSP& implementor_sp)
2391{
2392 bool ret_val = false;
2393
2394 if (!implementor_sp)
2395 return ret_val;
2396
2397 void* implementor = implementor_sp->GetObject();
2398
2399 if (!implementor)
2400 return ret_val;
2401
2402 if (!g_swig_mighthavechildren_provider)
2403 return ret_val;
2404
2405 {
2406 Locker py_lock(this);
2407 ret_val = g_swig_mighthavechildren_provider (implementor);
2408 }
2409
2410 return ret_val;
2411}
2412
Enrico Granata69ea91b2012-11-30 20:15:16 +00002413static std::string
2414ReadPythonBacktrace (PyObject* py_backtrace)
2415{
2416 PyObject* traceback_module = NULL,
2417 *stringIO_module = NULL,
2418 *stringIO_builder = NULL,
2419 *stringIO_buffer = NULL,
2420 *printTB = NULL,
2421 *printTB_args = NULL,
2422 *printTB_result = NULL,
2423 *stringIO_getvalue = NULL,
2424 *printTB_string = NULL;
2425
2426 std::string retval("backtrace unavailable");
2427
2428 if (py_backtrace && py_backtrace != Py_None)
2429 {
2430 traceback_module = PyImport_ImportModule("traceback");
2431 stringIO_module = PyImport_ImportModule("StringIO");
2432
2433 if (traceback_module && traceback_module != Py_None && stringIO_module && stringIO_module != Py_None)
2434 {
2435 stringIO_builder = PyObject_GetAttrString(stringIO_module, "StringIO");
2436 if (stringIO_builder && stringIO_builder != Py_None)
2437 {
2438 stringIO_buffer = PyObject_CallObject(stringIO_builder, NULL);
2439 if (stringIO_buffer && stringIO_buffer != Py_None)
2440 {
2441 printTB = PyObject_GetAttrString(traceback_module, "print_tb");
2442 if (printTB && printTB != Py_None)
2443 {
2444 printTB_args = Py_BuildValue("OOO",py_backtrace,Py_None,stringIO_buffer);
2445 printTB_result = PyObject_CallObject(printTB, printTB_args);
2446 stringIO_getvalue = PyObject_GetAttrString(stringIO_buffer, "getvalue");
2447 if (stringIO_getvalue && stringIO_getvalue != Py_None)
2448 {
2449 printTB_string = PyObject_CallObject (stringIO_getvalue,NULL);
2450 if (printTB_string && printTB_string != Py_None && PyString_Check(printTB_string))
2451 retval.assign(PyString_AsString(printTB_string));
2452 }
2453 }
2454 }
2455 }
2456 }
2457 }
2458 Py_XDECREF(traceback_module);
2459 Py_XDECREF(stringIO_module);
2460 Py_XDECREF(stringIO_builder);
2461 Py_XDECREF(stringIO_buffer);
2462 Py_XDECREF(printTB);
2463 Py_XDECREF(printTB_args);
2464 Py_XDECREF(printTB_result);
2465 Py_XDECREF(stringIO_getvalue);
2466 Py_XDECREF(printTB_string);
2467 return retval;
2468}
2469
Enrico Granataadaf2822012-10-23 19:54:09 +00002470bool
Enrico Granataa9dbf432011-10-17 21:45:27 +00002471ScriptInterpreterPython::LoadScriptingModule (const char* pathname,
Enrico Granata0a305db2011-11-07 22:57:04 +00002472 bool can_reload,
Jim Ingham6a510852012-12-07 17:43:38 +00002473 bool init_session,
Enrico Granataa9dbf432011-10-17 21:45:27 +00002474 lldb_private::Error& error)
2475{
2476 if (!pathname || !pathname[0])
2477 {
2478 error.SetErrorString("invalid pathname");
2479 return false;
2480 }
2481
2482 if (!g_swig_call_module_init)
2483 {
2484 error.SetErrorString("internal helper function missing");
2485 return false;
2486 }
2487
Greg Claytone1cd1be2012-01-29 20:56:30 +00002488 lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().shared_from_this();
Enrico Granata47c6f6d2011-10-24 17:22:21 +00002489
Enrico Granataa9dbf432011-10-17 21:45:27 +00002490 {
Enrico Granataa9dbf432011-10-17 21:45:27 +00002491 FileSpec target_file(pathname, true);
2492
2493 // TODO: would we want to reject any other value?
2494 if (target_file.GetFileType() == FileSpec::eFileTypeInvalid ||
2495 target_file.GetFileType() == FileSpec::eFileTypeUnknown)
2496 {
2497 error.SetErrorString("invalid pathname");
2498 return false;
2499 }
2500
2501 const char* directory = target_file.GetDirectory().GetCString();
2502 std::string basename(target_file.GetFilename().GetCString());
Johnny Chen2c90e992012-08-18 04:14:54 +00002503
2504 // Before executing Pyton code, lock the GIL.
Greg Claytonc9d645d2012-10-18 22:40:37 +00002505 Locker py_lock (this,
Jim Ingham6a510852012-12-07 17:43:38 +00002506 Locker::AcquireLock | (init_session ? Locker::InitSession : 0),
2507 Locker::FreeAcquiredLock | (init_session ? Locker::TearDownSession : 0));
Enrico Granataa9dbf432011-10-17 21:45:27 +00002508
2509 // now make sure that Python has "directory" in the search path
2510 StreamString command_stream;
Enrico Granata2ffcf432012-11-08 02:44:10 +00002511 command_stream.Printf("if not (sys.path.__contains__('%s')):\n sys.path.insert(1,'%s');\n\n",
Enrico Granataa9dbf432011-10-17 21:45:27 +00002512 directory,
2513 directory);
Enrico Granata085577f2012-10-31 00:01:26 +00002514 bool syspath_retval = ExecuteMultipleLines(command_stream.GetData(), ScriptInterpreter::ExecuteScriptOptions().SetEnableIO(false).SetSetLLDBGlobals(false));
Enrico Granataa9dbf432011-10-17 21:45:27 +00002515 if (!syspath_retval)
2516 {
2517 error.SetErrorString("Python sys.path handling failed");
2518 return false;
2519 }
2520
2521 // strip .py or .pyc extension
2522 ConstString extension = target_file.GetFileNameExtension();
Sean Callanan811209b2012-12-03 21:28:37 +00002523 if (extension)
2524 {
2525 if (::strcmp(extension.GetCString(), "py") == 0)
2526 basename.resize(basename.length()-3);
2527 else if(::strcmp(extension.GetCString(), "pyc") == 0)
2528 basename.resize(basename.length()-4);
2529 }
Enrico Granataa9dbf432011-10-17 21:45:27 +00002530
2531 // check if the module is already import-ed
2532 command_stream.Clear();
2533 command_stream.Printf("sys.getrefcount(%s)",basename.c_str());
2534 int refcount = 0;
2535 // this call will fail if the module does not exist (because the parameter to it is not a string
2536 // but an actual Python module object, which is non-existant if the module was not imported before)
Enrico Granata0a305db2011-11-07 22:57:04 +00002537 bool was_imported = (ExecuteOneLineWithReturn(command_stream.GetData(),
Greg Claytonc9d645d2012-10-18 22:40:37 +00002538 ScriptInterpreterPython::eScriptReturnTypeInt,
2539 &refcount,
Enrico Granata085577f2012-10-31 00:01:26 +00002540 ScriptInterpreter::ExecuteScriptOptions().SetEnableIO(false).SetSetLLDBGlobals(false)) && refcount > 0);
Enrico Granata0a305db2011-11-07 22:57:04 +00002541 if (was_imported == true && can_reload == false)
Enrico Granataa9dbf432011-10-17 21:45:27 +00002542 {
2543 error.SetErrorString("module already imported");
2544 return false;
2545 }
2546
2547 // now actually do the import
2548 command_stream.Clear();
2549 command_stream.Printf("import %s",basename.c_str());
Enrico Granata085577f2012-10-31 00:01:26 +00002550 bool import_retval = ExecuteMultipleLines(command_stream.GetData(), ScriptInterpreter::ExecuteScriptOptions().SetEnableIO(false).SetSetLLDBGlobals(false).SetMaskoutErrors(false));
2551 PyObject* py_error = PyErr_Occurred(); // per Python docs: "you do not need to Py_DECREF()" the return of this function
2552
2553 if (py_error || !import_retval) // check for failure of the import
Enrico Granataa9dbf432011-10-17 21:45:27 +00002554 {
Enrico Granata085577f2012-10-31 00:01:26 +00002555 if (py_error) // if we have a Python error..
2556 {
Enrico Granata69ea91b2012-11-30 20:15:16 +00002557 PyObject *type = NULL,*value = NULL,*traceback = NULL;
2558 PyErr_Fetch (&type,&value,&traceback);
2559
Enrico Granata085577f2012-10-31 00:01:26 +00002560 if (PyErr_GivenExceptionMatches (py_error, PyExc_ImportError)) // and it is an ImportError
2561 {
Enrico Granata085577f2012-10-31 00:01:26 +00002562 if (value && value != Py_None)
2563 error.SetErrorString(PyString_AsString(PyObject_Str(value)));
2564 else
2565 error.SetErrorString("ImportError raised by imported module");
Enrico Granata085577f2012-10-31 00:01:26 +00002566 }
2567 else // any other error
2568 {
Enrico Granata69ea91b2012-11-30 20:15:16 +00002569 // get the backtrace
2570 std::string bt = ReadPythonBacktrace(traceback);
Enrico Granata5ce1d012012-11-13 02:57:43 +00002571
2572 if (value && value != Py_None)
Enrico Granata69ea91b2012-11-30 20:15:16 +00002573 error.SetErrorStringWithFormat("Python error raised while importing module: %s - traceback: %s", PyString_AsString(PyObject_Str(value)),bt.c_str());
Enrico Granata5ce1d012012-11-13 02:57:43 +00002574 else
Enrico Granata69ea91b2012-11-30 20:15:16 +00002575 error.SetErrorStringWithFormat("Python raised an error while importing module - traceback: %s",bt.c_str());
Enrico Granata085577f2012-10-31 00:01:26 +00002576 }
Enrico Granata69ea91b2012-11-30 20:15:16 +00002577
2578 Py_XDECREF(type);
2579 Py_XDECREF(value);
2580 Py_XDECREF(traceback);
Enrico Granata085577f2012-10-31 00:01:26 +00002581 }
2582 else // we failed but have no error to explain why
2583 {
2584 error.SetErrorString("unknown error while importing module");
2585 }
2586
2587 // anyway, clear the error indicator and return false
2588 PyErr_Clear();
Enrico Granataa9dbf432011-10-17 21:45:27 +00002589 return false;
2590 }
2591
Enrico Granata085577f2012-10-31 00:01:26 +00002592 // if we are here, everything worked
Enrico Granata061858c2012-02-15 02:34:21 +00002593 // call __lldb_init_module(debugger,dict)
Enrico Granataa9dbf432011-10-17 21:45:27 +00002594 if (!g_swig_call_module_init (basename,
Enrico Granata47c6f6d2011-10-24 17:22:21 +00002595 m_dictionary_name.c_str(),
Enrico Granataa9dbf432011-10-17 21:45:27 +00002596 debugger_sp))
2597 {
Enrico Granata061858c2012-02-15 02:34:21 +00002598 error.SetErrorString("calling __lldb_init_module failed");
Enrico Granataa9dbf432011-10-17 21:45:27 +00002599 return false;
2600 }
2601 return true;
2602 }
2603}
2604
Enrico Granata7bc0ec32012-02-29 03:28:49 +00002605lldb::ScriptInterpreterObjectSP
2606ScriptInterpreterPython::MakeScriptObject (void* object)
2607{
2608 return lldb::ScriptInterpreterObjectSP(new ScriptInterpreterPythonObject(object));
2609}
2610
Enrico Granata0a305db2011-11-07 22:57:04 +00002611ScriptInterpreterPython::SynchronicityHandler::SynchronicityHandler (lldb::DebuggerSP debugger_sp,
2612 ScriptedCommandSynchronicity synchro) :
2613 m_debugger_sp(debugger_sp),
2614 m_synch_wanted(synchro),
2615 m_old_asynch(debugger_sp->GetAsyncExecution())
2616{
2617 if (m_synch_wanted == eScriptedCommandSynchronicitySynchronous)
2618 m_debugger_sp->SetAsyncExecution(false);
2619 else if (m_synch_wanted == eScriptedCommandSynchronicityAsynchronous)
2620 m_debugger_sp->SetAsyncExecution(true);
2621}
2622
2623ScriptInterpreterPython::SynchronicityHandler::~SynchronicityHandler()
2624{
2625 if (m_synch_wanted != eScriptedCommandSynchronicityCurrentValue)
2626 m_debugger_sp->SetAsyncExecution(m_old_asynch);
2627}
2628
Enrico Granataa9dbf432011-10-17 21:45:27 +00002629bool
Enrico Granatabe93a352011-08-16 16:49:25 +00002630ScriptInterpreterPython::RunScriptBasedCommand(const char* impl_function,
2631 const char* args,
Enrico Granata0a305db2011-11-07 22:57:04 +00002632 ScriptedCommandSynchronicity synchronicity,
Enrico Granata223383e2011-08-16 23:24:13 +00002633 lldb_private::CommandReturnObject& cmd_retobj,
Enrico Granatabe93a352011-08-16 16:49:25 +00002634 Error& error)
2635{
2636 if (!impl_function)
2637 {
2638 error.SetErrorString("no function to execute");
2639 return false;
2640 }
2641
2642 if (!g_swig_call_command)
2643 {
2644 error.SetErrorString("no helper function to run scripted commands");
2645 return false;
2646 }
2647
Greg Claytone1cd1be2012-01-29 20:56:30 +00002648 lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().shared_from_this();
Enrico Granata0a305db2011-11-07 22:57:04 +00002649
2650 if (!debugger_sp.get())
2651 {
2652 error.SetErrorString("invalid Debugger pointer");
2653 return false;
2654 }
Enrico Granatabe93a352011-08-16 16:49:25 +00002655
2656 bool ret_val;
2657
2658 std::string err_msg;
Enrico Granata0a305db2011-11-07 22:57:04 +00002659
Enrico Granatabe93a352011-08-16 16:49:25 +00002660 {
Jim Ingham6a510852012-12-07 17:43:38 +00002661 Locker py_lock(this,
2662 Locker::AcquireLock | Locker::InitSession | Locker::InitGlobals,
2663 Locker::FreeLock | Locker::TearDownSession);
Enrico Granata557fd002012-12-19 23:42:07 +00002664
Enrico Granata0a305db2011-11-07 22:57:04 +00002665 SynchronicityHandler synch_handler(debugger_sp,
2666 synchronicity);
Enrico Granata557fd002012-12-19 23:42:07 +00002667
2668 // we need to save the thread state when we first start the command
2669 // because we might decide to interrupt it while some action is taking
2670 // place outside of Python (e.g. printing to screen, waiting for the network, ...)
2671 // in that case, _PyThreadState_Current will be NULL - and we would be unable
2672 // to set the asynchronous exception - not a desirable situation
2673 m_command_thread_state = _PyThreadState_Current;
Enrico Granata0a305db2011-11-07 22:57:04 +00002674
Enrico Granata79cc6f72012-06-07 00:17:18 +00002675 PythonInputReaderManager py_input(this);
2676
Enrico Granatabe93a352011-08-16 16:49:25 +00002677 ret_val = g_swig_call_command (impl_function,
Enrico Granata47c6f6d2011-10-24 17:22:21 +00002678 m_dictionary_name.c_str(),
Enrico Granatabe93a352011-08-16 16:49:25 +00002679 debugger_sp,
2680 args,
2681 err_msg,
Enrico Granata274fd6e2011-08-19 23:56:34 +00002682 cmd_retobj);
Enrico Granatabe93a352011-08-16 16:49:25 +00002683 }
Enrico Granata0a305db2011-11-07 22:57:04 +00002684
Enrico Granatabe93a352011-08-16 16:49:25 +00002685 if (!ret_val)
2686 error.SetErrorString(err_msg.c_str());
2687 else
2688 error.Clear();
Enrico Granata0a305db2011-11-07 22:57:04 +00002689
Enrico Granatabe93a352011-08-16 16:49:25 +00002690 return ret_val;
Enrico Granatabe93a352011-08-16 16:49:25 +00002691}
2692
Enrico Granata99f0b8f2011-08-17 01:30:04 +00002693// in Python, a special attribute __doc__ contains the docstring
2694// for an object (function, method, class, ...) if any is defined
2695// Otherwise, the attribute's value is None
Enrico Granatafac939e2012-09-18 21:53:02 +00002696bool
2697ScriptInterpreterPython::GetDocumentationForItem(const char* item, std::string& dest)
Enrico Granata99f0b8f2011-08-17 01:30:04 +00002698{
Enrico Granatafac939e2012-09-18 21:53:02 +00002699 dest.clear();
2700 if (!item || !*item)
2701 return false;
Enrico Granata99f0b8f2011-08-17 01:30:04 +00002702 std::string command(item);
2703 command += ".__doc__";
2704
2705 char* result_ptr = NULL; // Python is going to point this to valid data if ExecuteOneLineWithReturn returns successfully
2706
2707 if (ExecuteOneLineWithReturn (command.c_str(),
Enrico Granataa9dbf432011-10-17 21:45:27 +00002708 ScriptInterpreter::eScriptReturnTypeCharStrOrNone,
Enrico Granata085577f2012-10-31 00:01:26 +00002709 &result_ptr, ScriptInterpreter::ExecuteScriptOptions().SetEnableIO(false) /*.SetSetLLDBGlobals(false)*/))
Enrico Granata99f0b8f2011-08-17 01:30:04 +00002710 {
Enrico Granataeacb4912012-09-20 23:23:55 +00002711 if (result_ptr)
2712 dest.assign(result_ptr);
Enrico Granatafac939e2012-09-18 21:53:02 +00002713 return true;
Enrico Granata99f0b8f2011-08-17 01:30:04 +00002714 }
2715 else
Enrico Granatafac939e2012-09-18 21:53:02 +00002716 {
2717 StreamString str_stream;
2718 str_stream.Printf("Function %s was not found. Containing module might be missing.",item);
2719 dest.assign(str_stream.GetData());
2720 return false;
2721 }
Enrico Granata99f0b8f2011-08-17 01:30:04 +00002722}
Caroline Tice5c2816d2010-11-10 19:18:14 +00002723
Caroline Tice2f88aad2011-01-14 00:29:16 +00002724void
Enrico Granata7bc0ec32012-02-29 03:28:49 +00002725ScriptInterpreterPython::InitializeInterpreter (SWIGInitCallback python_swig_init_callback)
Greg Claytonfc36f7912011-03-22 01:14:58 +00002726{
2727 g_swig_init_callback = python_swig_init_callback;
Enrico Granata7bc0ec32012-02-29 03:28:49 +00002728 g_swig_breakpoint_callback = LLDBSwigPythonBreakpointCallbackFunction;
Johnny Chene9a56272012-08-09 23:09:42 +00002729 g_swig_watchpoint_callback = LLDBSwigPythonWatchpointCallbackFunction;
Enrico Granata7bc0ec32012-02-29 03:28:49 +00002730 g_swig_typescript_callback = LLDBSwigPythonCallTypeScript;
2731 g_swig_synthetic_script = LLDBSwigPythonCreateSyntheticProvider;
2732 g_swig_calc_children = LLDBSwigPython_CalculateNumChildren;
2733 g_swig_get_child_index = LLDBSwigPython_GetChildAtIndex;
2734 g_swig_get_index_child = LLDBSwigPython_GetIndexOfChildWithName;
2735 g_swig_cast_to_sbvalue = LLDBSWIGPython_CastPyObjectToSBValue;
2736 g_swig_update_provider = LLDBSwigPython_UpdateSynthProviderInstance;
Enrico Granataadaf2822012-10-23 19:54:09 +00002737 g_swig_mighthavechildren_provider = LLDBSwigPython_MightHaveChildrenSynthProviderInstance;
Enrico Granata7bc0ec32012-02-29 03:28:49 +00002738 g_swig_call_command = LLDBSwigPythonCallCommand;
2739 g_swig_call_module_init = LLDBSwigPythonCallModuleInit;
Enrico Granata57907592012-08-24 00:30:47 +00002740 g_swig_create_os_plugin = LLDBSWIGPythonCreateOSPlugin;
Greg Claytonfc36f7912011-03-22 01:14:58 +00002741}
2742
2743void
2744ScriptInterpreterPython::InitializePrivate ()
Caroline Tice2f88aad2011-01-14 00:29:16 +00002745{
Caroline Tice2f88aad2011-01-14 00:29:16 +00002746 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
2747
Greg Claytona3406612011-02-07 23:24:47 +00002748 // Python will muck with STDIN terminal state, so save off any current TTY
2749 // settings so we can restore them.
2750 TerminalState stdin_tty_state;
2751 stdin_tty_state.Save(STDIN_FILENO, false);
Caroline Tice2f88aad2011-01-14 00:29:16 +00002752
Johnny Chen2c90e992012-08-18 04:14:54 +00002753 PyGILState_STATE gstate;
2754 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT | LIBLLDB_LOG_VERBOSE));
2755 bool threads_already_initialized = false;
2756 if (PyEval_ThreadsInitialized ()) {
2757 gstate = PyGILState_Ensure ();
2758 if (log)
2759 log->Printf("Ensured PyGILState. Previous state = %slocked\n", gstate == PyGILState_UNLOCKED ? "un" : "");
2760 threads_already_initialized = true;
2761 } else {
2762 // InitThreads acquires the GIL if it hasn't been called before.
2763 PyEval_InitThreads ();
2764 }
Caroline Ticec928f592011-06-02 22:09:43 +00002765 Py_InitializeEx (0);
Caroline Tice2f88aad2011-01-14 00:29:16 +00002766
Greg Claytonfc36f7912011-03-22 01:14:58 +00002767 // Initialize SWIG after setting up python
2768 assert (g_swig_init_callback != NULL);
2769 g_swig_init_callback ();
Caroline Tice2f88aad2011-01-14 00:29:16 +00002770
2771 // Update the path python uses to search for modules to include the current directory.
2772
Caroline Tice1f499bc2011-06-13 21:33:00 +00002773 PyRun_SimpleString ("import sys");
2774 PyRun_SimpleString ("sys.path.append ('.')");
Jim Inghama6c422b2011-08-27 01:24:08 +00002775
2776 // Find the module that owns this code and use that path we get to
2777 // set the sys.path appropriately.
2778
2779 FileSpec file_spec;
2780 char python_dir_path[PATH_MAX];
2781 if (Host::GetLLDBPath (ePathTypePythonDir, file_spec))
2782 {
2783 std::string python_path("sys.path.insert(0,\"");
2784 size_t orig_len = python_path.length();
2785 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
2786 {
2787 python_path.append (python_dir_path);
2788 python_path.append ("\")");
2789 PyRun_SimpleString (python_path.c_str());
2790 python_path.resize (orig_len);
2791 }
2792
2793 if (Host::GetLLDBPath (ePathTypeLLDBShlibDir, file_spec))
2794 {
2795 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
2796 {
2797 python_path.append (python_dir_path);
2798 python_path.append ("\")");
2799 PyRun_SimpleString (python_path.c_str());
2800 python_path.resize (orig_len);
2801 }
2802 }
2803 }
2804
Greg Clayton6d98f562012-04-25 00:58:03 +00002805 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 Claytoncdd074f2011-02-07 19:04:58 +00002806
Johnny Chen2c90e992012-08-18 04:14:54 +00002807 if (threads_already_initialized) {
2808 if (log)
2809 log->Printf("Releasing PyGILState. Returning to state = %slocked\n", gstate == PyGILState_UNLOCKED ? "un" : "");
2810 PyGILState_Release (gstate);
2811 } else {
2812 // We initialized the threads in this function, just unlock the GIL.
2813 PyEval_SaveThread();
2814 }
2815
Greg Claytona3406612011-02-07 23:24:47 +00002816 stdin_tty_state.Restore();
Caroline Tice2f88aad2011-01-14 00:29:16 +00002817}
2818
Greg Claytonfc36f7912011-03-22 01:14:58 +00002819//void
2820//ScriptInterpreterPython::Terminate ()
2821//{
2822// // We are intentionally NOT calling Py_Finalize here (this would be the logical place to call it). Calling
2823// // Py_Finalize here causes test suite runs to seg fault: The test suite runs in Python. It registers
2824// // SBDebugger::Terminate to be called 'at_exit'. When the test suite Python harness finishes up, it calls
2825// // Py_Finalize, which calls all the 'at_exit' registered functions. SBDebugger::Terminate calls Debugger::Terminate,
2826// // which calls lldb::Terminate, which calls ScriptInterpreter::Terminate, which calls
2827// // ScriptInterpreterPython::Terminate. So if we call Py_Finalize here, we end up with Py_Finalize being called from
2828// // within Py_Finalize, which results in a seg fault.
2829// //
2830// // Since this function only gets called when lldb is shutting down and going away anyway, the fact that we don't
2831// // actually call Py_Finalize should not cause any problems (everything should shut down/go away anyway when the
2832// // process exits).
2833// //
2834//// Py_Finalize ();
2835//}
Greg Claytondce502e2011-11-04 03:34:56 +00002836
2837#endif // #ifdef LLDB_DISABLE_PYTHON