blob: 97cf7f866d61a94bc844dc44da7c83ebda67a182 [file] [log] [blame]
Chris Lattner24943d22010-06-08 16:52:24 +00001//===-- ScriptInterpreterPython.cpp -----------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10// In order to guarantee correct working with Python, Python.h *MUST* be
Benjamin Kramerc28bbdb2011-10-23 16:49:03 +000011// the *FIRST* header file included here.
Greg Clayton3e4238d2011-11-04 03:34:56 +000012#ifdef LLDB_DISABLE_PYTHON
13
14// Python is disabled in this build
15
16#else
Benjamin Kramerc28bbdb2011-10-23 16:49:03 +000017
18#if defined (__APPLE__)
19#include <Python/Python.h>
20#else
21#include <Python.h>
22#endif
Chris Lattner24943d22010-06-08 16:52:24 +000023
24#include "lldb/Interpreter/ScriptInterpreterPython.h"
25
Chris Lattner24943d22010-06-08 16:52:24 +000026#include <stdlib.h>
27#include <stdio.h>
28
29#include <string>
30
Enrico Granata91544802011-09-06 19:20:51 +000031#include "lldb/API/SBValue.h"
Greg Clayton987c7eb2011-09-17 08:33:22 +000032#include "lldb/Breakpoint/BreakpointLocation.h"
Greg Clayton63094e02010-06-23 01:19:29 +000033#include "lldb/Breakpoint/StoppointCallbackContext.h"
Johnny Chenf3ec4612012-08-09 23:09:42 +000034#include "lldb/Breakpoint/WatchpointOptions.h"
Chris Lattner24943d22010-06-08 16:52:24 +000035#include "lldb/Core/Debugger.h"
Chris Lattner24943d22010-06-08 16:52:24 +000036#include "lldb/Core/Timer.h"
37#include "lldb/Host/Host.h"
38#include "lldb/Interpreter/CommandInterpreter.h"
39#include "lldb/Interpreter/CommandReturnObject.h"
Greg Clayton5144f382010-10-07 17:14:24 +000040#include "lldb/Target/Thread.h"
Chris Lattner24943d22010-06-08 16:52:24 +000041
Chris Lattner24943d22010-06-08 16:52:24 +000042using namespace lldb;
43using namespace lldb_private;
44
Greg Claytone86cbb92011-03-22 01:14:58 +000045
46static ScriptInterpreter::SWIGInitCallback g_swig_init_callback = NULL;
47static ScriptInterpreter::SWIGBreakpointCallbackFunction g_swig_breakpoint_callback = NULL;
Johnny Chenf3ec4612012-08-09 23:09:42 +000048static ScriptInterpreter::SWIGWatchpointCallbackFunction g_swig_watchpoint_callback = NULL;
Enrico Granataf7a9b142011-07-15 02:26:42 +000049static ScriptInterpreter::SWIGPythonTypeScriptCallbackFunction g_swig_typescript_callback = NULL;
Enrico Granata9ae7cef2011-07-24 00:14:56 +000050static ScriptInterpreter::SWIGPythonCreateSyntheticProvider g_swig_synthetic_script = NULL;
51static ScriptInterpreter::SWIGPythonCalculateNumChildren g_swig_calc_children = NULL;
52static ScriptInterpreter::SWIGPythonGetChildAtIndex g_swig_get_child_index = NULL;
53static ScriptInterpreter::SWIGPythonGetIndexOfChildWithName g_swig_get_index_child = NULL;
54static ScriptInterpreter::SWIGPythonCastPyObjectToSBValue g_swig_cast_to_sbvalue = NULL;
Enrico Granata979e20d2011-07-29 19:53:35 +000055static ScriptInterpreter::SWIGPythonUpdateSynthProviderInstance g_swig_update_provider = NULL;
Enrico Granatac2a28252011-08-16 16:49:25 +000056static ScriptInterpreter::SWIGPythonCallCommand g_swig_call_command = NULL;
Enrico Granata59df36f2011-10-17 21:45:27 +000057static ScriptInterpreter::SWIGPythonCallModuleInit g_swig_call_module_init = NULL;
Enrico Granata155ee912012-08-24 00:30:47 +000058static ScriptInterpreter::SWIGPythonCreateOSPlugin g_swig_create_os_plugin = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +000059
Enrico Granata1328b142012-02-29 03:28:49 +000060// these are the Pythonic implementations of the required callbacks
61// these are scripting-language specific, which is why they belong here
62// we still need to use function pointers to them instead of relying
63// on linkage-time resolution because the SWIG stuff and this file
64// get built at different times
65extern "C" bool
66LLDBSwigPythonBreakpointCallbackFunction
67(
68 const char *python_function_name,
69 const char *session_dictionary_name,
70 const lldb::StackFrameSP& sb_frame,
71 const lldb::BreakpointLocationSP& sb_bp_loc
72 );
73
74extern "C" bool
Johnny Chenf3ec4612012-08-09 23:09:42 +000075LLDBSwigPythonWatchpointCallbackFunction
76(
77 const char *python_function_name,
78 const char *session_dictionary_name,
79 const lldb::StackFrameSP& sb_frame,
80 const lldb::WatchpointSP& sb_wp
81 );
82
83extern "C" bool
Enrico Granata1328b142012-02-29 03:28:49 +000084LLDBSwigPythonCallTypeScript
85(
86 const char *python_function_name,
87 void *session_dictionary,
88 const lldb::ValueObjectSP& valobj_sp,
89 void** pyfunct_wrapper,
90 std::string& retval
91 );
92
93extern "C" void*
94LLDBSwigPythonCreateSyntheticProvider
95(
96 const std::string python_class_name,
97 const char *session_dictionary_name,
98 const lldb::ValueObjectSP& valobj_sp
99 );
100
101
102extern "C" uint32_t LLDBSwigPython_CalculateNumChildren (void *implementor);
103extern "C" void* LLDBSwigPython_GetChildAtIndex (void *implementor, uint32_t idx);
104extern "C" int LLDBSwigPython_GetIndexOfChildWithName (void *implementor, const char* child_name);
105extern "C" void* LLDBSWIGPython_CastPyObjectToSBValue (void* data);
Enrico Granatacf09f882012-03-19 22:58:49 +0000106extern "C" bool LLDBSwigPython_UpdateSynthProviderInstance (void* implementor);
Enrico Granata1328b142012-02-29 03:28:49 +0000107
108extern "C" bool LLDBSwigPythonCallCommand
109(
110 const char *python_function_name,
111 const char *session_dictionary_name,
112 lldb::DebuggerSP& debugger,
113 const char* args,
114 std::string& err_msg,
115 lldb_private::CommandReturnObject& cmd_retobj
116 );
117
118extern "C" bool LLDBSwigPythonCallModuleInit
119(
120 const std::string python_module_name,
121 const char *session_dictionary_name,
122 lldb::DebuggerSP& debugger
123 );
124
Enrico Granata155ee912012-08-24 00:30:47 +0000125extern "C" void* LLDBSWIGPythonCreateOSPlugin
126(
127 const std::string python_class_name,
128 const char *session_dictionary_name,
129 const lldb::ProcessSP& process_sp
130);
131
Chris Lattner24943d22010-06-08 16:52:24 +0000132static int
133_check_and_flush (FILE *stream)
134{
135 int prev_fail = ferror (stream);
136 return fflush (stream) || prev_fail ? EOF : 0;
137}
138
Enrico Granatafa1f6172011-10-24 17:22:21 +0000139ScriptInterpreterPython::Locker::Locker (ScriptInterpreterPython *py_interpreter,
140 uint16_t on_entry,
141 uint16_t on_leave,
142 FILE* wait_msg_handle) :
143 m_need_session( (on_leave & TearDownSession) == TearDownSession ),
Enrico Granatafa1f6172011-10-24 17:22:21 +0000144 m_python_interpreter(py_interpreter),
145 m_tmp_fh(wait_msg_handle)
Enrico Granata91544802011-09-06 19:20:51 +0000146{
Enrico Granatafa1f6172011-10-24 17:22:21 +0000147 if (m_python_interpreter && !m_tmp_fh)
148 m_tmp_fh = (m_python_interpreter->m_dbg_stdout ? m_python_interpreter->m_dbg_stdout : stdout);
Johnny Chen8165d432012-08-18 04:14:54 +0000149
150 DoAcquireLock();
Enrico Granatafa1f6172011-10-24 17:22:21 +0000151 if ( (on_entry & InitSession) == InitSession )
152 DoInitSession();
153}
154
155bool
156ScriptInterpreterPython::Locker::DoAcquireLock()
157{
Johnny Chen8165d432012-08-18 04:14:54 +0000158 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT | LIBLLDB_LOG_VERBOSE));
159 m_GILState = PyGILState_Ensure();
160 if (log)
161 log->Printf("Ensured PyGILState. Previous state = %slocked\n", m_GILState == PyGILState_UNLOCKED ? "un" : "");
Enrico Granatafa1f6172011-10-24 17:22:21 +0000162 return true;
163}
164
165bool
166ScriptInterpreterPython::Locker::DoInitSession()
167{
168 if (!m_python_interpreter)
169 return false;
170 m_python_interpreter->EnterSession ();
171 return true;
172}
173
174bool
175ScriptInterpreterPython::Locker::DoFreeLock()
176{
Johnny Chen8165d432012-08-18 04:14:54 +0000177 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT | LIBLLDB_LOG_VERBOSE));
178 if (log)
179 log->Printf("Releasing PyGILState. Returning to state = %slocked\n", m_GILState == PyGILState_UNLOCKED ? "un" : "");
180 PyGILState_Release(m_GILState);
Enrico Granatafa1f6172011-10-24 17:22:21 +0000181 return true;
182}
183
184bool
185ScriptInterpreterPython::Locker::DoTearDownSession()
186{
187 if (!m_python_interpreter)
188 return false;
189 m_python_interpreter->LeaveSession ();
190 return true;
Enrico Granata91544802011-09-06 19:20:51 +0000191}
192
193ScriptInterpreterPython::Locker::~Locker()
194{
195 if (m_need_session)
Enrico Granatafa1f6172011-10-24 17:22:21 +0000196 DoTearDownSession();
Johnny Chen8165d432012-08-18 04:14:54 +0000197 DoFreeLock();
Enrico Granata91544802011-09-06 19:20:51 +0000198}
199
Enrico Granatadba1de82012-03-27 02:35:13 +0000200class ForceDisableSyntheticChildren
201{
202public:
203 ForceDisableSyntheticChildren (Target* target) :
204 m_target(target)
205 {
206 m_old_value = target->GetSuppressSyntheticValue();
207 target->SetSuppressSyntheticValue(true);
208 }
209 ~ForceDisableSyntheticChildren ()
210 {
211 m_target->SetSuppressSyntheticValue(m_old_value);
212 }
213private:
214 Target* m_target;
215 bool m_old_value;
216};
217
Enrico Granataa1ba3142012-06-07 00:17:18 +0000218ScriptInterpreterPython::PythonInputReaderManager::PythonInputReaderManager (ScriptInterpreterPython *interpreter) :
219m_interpreter(interpreter),
220m_debugger_sp(),
221m_reader_sp(),
222m_error(false)
223{
224 if (m_interpreter == NULL)
225 {
226 m_error = true;
227 return;
228 }
229
230 m_debugger_sp = m_interpreter->GetCommandInterpreter().GetDebugger().shared_from_this();
231
232 if (!m_debugger_sp)
233 {
234 m_error = true;
235 return;
236 }
237
238 m_reader_sp = InputReaderSP(new InputReader(*m_debugger_sp.get()));
239
240 if (!m_reader_sp)
241 {
242 m_error = true;
243 return;
244 }
245
246 Error error (m_reader_sp->Initialize (ScriptInterpreterPython::PythonInputReaderManager::InputReaderCallback,
247 m_interpreter, // baton
248 eInputReaderGranularityLine, // token size, to pass to callback function
249 NULL, // end token
250 NULL, // prompt
251 true)); // echo input
252 if (error.Fail())
253 m_error = true;
254 else
255 {
256 m_debugger_sp->PushInputReader (m_reader_sp);
257 m_interpreter->m_embedded_thread_input_reader_sp = m_reader_sp;
258 }
259}
260
261ScriptInterpreterPython::PythonInputReaderManager::~PythonInputReaderManager()
262{
Johnny Chen8121d7a2012-08-17 23:44:35 +0000263 // Nothing to do if either m_interpreter or m_reader_sp is invalid.
264 if (!m_interpreter || !m_reader_sp)
265 return;
266
267 m_reader_sp->SetIsDone (true);
268 if (m_debugger_sp)
269 m_debugger_sp->PopInputReader(m_reader_sp);
270
271 // Only mess with m_interpreter's counterpart if, indeed, they are the same object.
272 if (m_reader_sp.get() == m_interpreter->m_embedded_thread_input_reader_sp.get())
Enrico Granataa1ba3142012-06-07 00:17:18 +0000273 {
Johnny Chen8121d7a2012-08-17 23:44:35 +0000274 m_interpreter->m_embedded_thread_pty.CloseSlaveFileDescriptor();
Enrico Granataa1ba3142012-06-07 00:17:18 +0000275 m_interpreter->m_embedded_thread_input_reader_sp.reset();
Johnny Chen8121d7a2012-08-17 23:44:35 +0000276 }
Enrico Granataa1ba3142012-06-07 00:17:18 +0000277}
278
279size_t
280ScriptInterpreterPython::PythonInputReaderManager::InputReaderCallback
281(
282 void *baton,
283 InputReader &reader,
284 InputReaderAction notification,
285 const char *bytes,
286 size_t bytes_len
287 )
288{
289 lldb::thread_t embedded_interpreter_thread;
290 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
291
292 if (baton == NULL)
293 return 0;
294
295 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
296
297 if (script_interpreter->m_script_lang != eScriptLanguagePython)
298 return 0;
299
300 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
301
302 switch (notification)
303 {
304 case eInputReaderActivate:
305 {
306 // Save terminal settings if we can
307 int input_fd = reader.GetDebugger().GetInputFile().GetDescriptor();
308 if (input_fd == File::kInvalidDescriptor)
309 input_fd = STDIN_FILENO;
310
311 script_interpreter->SaveTerminalState(input_fd);
Johnny Chen8165d432012-08-18 04:14:54 +0000312
Enrico Granataa1ba3142012-06-07 00:17:18 +0000313 char error_str[1024];
Johnny Chen8121d7a2012-08-17 23:44:35 +0000314 if (script_interpreter->m_embedded_thread_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, error_str,
Enrico Granataa1ba3142012-06-07 00:17:18 +0000315 sizeof(error_str)))
316 {
317 if (log)
318 log->Printf ("ScriptInterpreterPython::NonInteractiveInputReaderCallback, Activate, succeeded in opening master pty (fd = %d).",
Johnny Chen8121d7a2012-08-17 23:44:35 +0000319 script_interpreter->m_embedded_thread_pty.GetMasterFileDescriptor());
Enrico Granataa1ba3142012-06-07 00:17:18 +0000320 {
321 StreamString run_string;
322 char error_str[1024];
Johnny Chen8121d7a2012-08-17 23:44:35 +0000323 const char *pty_slave_name = script_interpreter->m_embedded_thread_pty.GetSlaveName (error_str, sizeof (error_str));
Enrico Granataca2c7072012-07-31 16:58:12 +0000324 if (pty_slave_name != NULL && PyThreadState_GetDict() != NULL)
Enrico Granataa1ba3142012-06-07 00:17:18 +0000325 {
Johnny Chen8165d432012-08-18 04:14:54 +0000326 ScriptInterpreterPython::Locker locker(script_interpreter,
327 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
328 ScriptInterpreterPython::Locker::FreeAcquiredLock);
Enrico Granataa1ba3142012-06-07 00:17:18 +0000329 run_string.Printf ("run_one_line (%s, 'save_stderr = sys.stderr')", script_interpreter->m_dictionary_name.c_str());
330 PyRun_SimpleString (run_string.GetData());
331 run_string.Clear ();
332
333 run_string.Printf ("run_one_line (%s, 'sys.stderr = sys.stdout')", script_interpreter->m_dictionary_name.c_str());
334 PyRun_SimpleString (run_string.GetData());
335 run_string.Clear ();
336
337 run_string.Printf ("run_one_line (%s, 'save_stdin = sys.stdin')", script_interpreter->m_dictionary_name.c_str());
338 PyRun_SimpleString (run_string.GetData());
339 run_string.Clear ();
340
341 run_string.Printf ("run_one_line (%s, \"sys.stdin = open ('%s', 'r')\")", script_interpreter->m_dictionary_name.c_str(),
342 pty_slave_name);
343 PyRun_SimpleString (run_string.GetData());
344 run_string.Clear ();
345 }
346 }
347 embedded_interpreter_thread = Host::ThreadCreate ("<lldb.script-interpreter.noninteractive-python>",
348 ScriptInterpreterPython::PythonInputReaderManager::RunPythonInputReader,
349 script_interpreter, NULL);
350 if (IS_VALID_LLDB_HOST_THREAD(embedded_interpreter_thread))
351 {
352 if (log)
353 log->Printf ("ScriptInterpreterPython::NonInteractiveInputReaderCallback, Activate, succeeded in creating thread (thread_t = %p)", embedded_interpreter_thread);
354 Error detach_error;
355 Host::ThreadDetach (embedded_interpreter_thread, &detach_error);
356 }
357 else
358 {
359 if (log)
360 log->Printf ("ScriptInterpreterPython::NonInteractiveInputReaderCallback, Activate, failed in creating thread");
361 reader.SetIsDone (true);
362 }
363 }
364 else
365 {
366 if (log)
367 log->Printf ("ScriptInterpreterPython::NonInteractiveInputReaderCallback, Activate, failed to open master pty ");
368 reader.SetIsDone (true);
369 }
370 }
371 break;
372
373 case eInputReaderDeactivate:
374 // When another input reader is pushed, don't leave the session...
375 //script_interpreter->LeaveSession ();
376 break;
377
378 case eInputReaderReactivate:
379 {
Johnny Chen8165d432012-08-18 04:14:54 +0000380 ScriptInterpreterPython::Locker locker(script_interpreter,
381 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
382 ScriptInterpreterPython::Locker::FreeAcquiredLock);
Enrico Granataa1ba3142012-06-07 00:17:18 +0000383 }
384 break;
385
386 case eInputReaderAsynchronousOutputWritten:
387 break;
388
389 case eInputReaderInterrupt:
390 reader.SetIsDone(true);
391 break;
392
393 case eInputReaderEndOfFile:
394 reader.SetIsDone(true);
395 break;
396
397 case eInputReaderGotToken:
Johnny Chen8121d7a2012-08-17 23:44:35 +0000398 if (script_interpreter->m_embedded_thread_pty.GetMasterFileDescriptor() != -1)
Enrico Granataa1ba3142012-06-07 00:17:18 +0000399 {
400 if (log)
401 log->Printf ("ScriptInterpreterPython::NonInteractiveInputReaderCallback, GotToken, bytes='%s', byte_len = %lu", bytes,
402 bytes_len);
403 if (bytes && bytes_len)
Johnny Chen8121d7a2012-08-17 23:44:35 +0000404 ::write (script_interpreter->m_embedded_thread_pty.GetMasterFileDescriptor(), bytes, bytes_len);
405 ::write (script_interpreter->m_embedded_thread_pty.GetMasterFileDescriptor(), "\n", 1);
Enrico Granataa1ba3142012-06-07 00:17:18 +0000406 }
407 else
408 {
409 if (log)
410 log->Printf ("ScriptInterpreterPython::NonInteractiveInputReaderCallback, GotToken, bytes='%s', byte_len = %lu, Master File Descriptor is bad.",
411 bytes,
412 bytes_len);
413 reader.SetIsDone (true);
414 }
415
416 break;
417
418 case eInputReaderDone:
419 {
420 StreamString run_string;
421 char error_str[1024];
Johnny Chen8121d7a2012-08-17 23:44:35 +0000422 const char *pty_slave_name = script_interpreter->m_embedded_thread_pty.GetSlaveName (error_str, sizeof (error_str));
Enrico Granataca2c7072012-07-31 16:58:12 +0000423 if (pty_slave_name != NULL && PyThreadState_GetDict() != NULL)
Enrico Granataa1ba3142012-06-07 00:17:18 +0000424 {
Johnny Chen8165d432012-08-18 04:14:54 +0000425 ScriptInterpreterPython::Locker locker(script_interpreter,
426 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
427 ScriptInterpreterPython::Locker::FreeAcquiredLock);
Enrico Granataa1ba3142012-06-07 00:17:18 +0000428 run_string.Printf ("run_one_line (%s, 'sys.stdin = save_stdin')", script_interpreter->m_dictionary_name.c_str());
429 PyRun_SimpleString (run_string.GetData());
430 run_string.Clear();
431
432 run_string.Printf ("run_one_line (%s, 'sys.stderr = save_stderr')", script_interpreter->m_dictionary_name.c_str());
433 PyRun_SimpleString (run_string.GetData());
434 run_string.Clear();
435 }
436 }
437
438 // Restore terminal settings if they were validly saved
439 if (log)
440 log->Printf ("ScriptInterpreterPython::NonInteractiveInputReaderCallback, Done, closing down input reader.");
441
442 script_interpreter->RestoreTerminalState ();
443
Johnny Chen8121d7a2012-08-17 23:44:35 +0000444 script_interpreter->m_embedded_thread_pty.CloseMasterFileDescriptor();
Enrico Granataa1ba3142012-06-07 00:17:18 +0000445 break;
446 }
447
448 return bytes_len;
449}
450
Greg Clayton63094e02010-06-23 01:19:29 +0000451ScriptInterpreterPython::ScriptInterpreterPython (CommandInterpreter &interpreter) :
Greg Clayton238c0a12010-09-18 01:14:36 +0000452 ScriptInterpreter (interpreter, eScriptLanguagePython),
Johnny Chen8121d7a2012-08-17 23:44:35 +0000453 m_embedded_thread_pty (),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000454 m_embedded_python_pty (),
455 m_embedded_thread_input_reader_sp (),
Johnny Chen8121d7a2012-08-17 23:44:35 +0000456 m_embedded_python_input_reader_sp (),
Greg Clayton58928562011-02-09 01:08:52 +0000457 m_dbg_stdout (interpreter.GetDebugger().GetOutputFile().GetStream()),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000458 m_new_sysout (NULL),
Johnny Chenc65046d2012-03-08 20:53:04 +0000459 m_old_sysout (NULL),
460 m_old_syserr (NULL),
Enrico Granata400105d2012-03-06 23:42:15 +0000461 m_run_one_line (NULL),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000462 m_dictionary_name (interpreter.GetDebugger().GetInstanceName().AsCString()),
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000463 m_terminal_state (),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000464 m_session_is_active (false),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000465 m_valid_session (true)
Chris Lattner24943d22010-06-08 16:52:24 +0000466{
467
Greg Clayton7c330d62011-01-27 01:01:10 +0000468 static int g_initialized = false;
469
470 if (!g_initialized)
471 {
472 g_initialized = true;
Greg Claytone86cbb92011-03-22 01:14:58 +0000473 ScriptInterpreterPython::InitializePrivate ();
Greg Clayton7c330d62011-01-27 01:01:10 +0000474 }
475
Caroline Tice0aa2e552011-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 Chen8165d432012-08-18 04:14:54 +0000479
480 Locker locker(this,
481 ScriptInterpreterPython::Locker::AcquireLock,
482 ScriptInterpreterPython::Locker::FreeAcquiredLock);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000483 PyRun_SimpleString (run_string.GetData());
Caroline Tice5867f6b2010-10-18 18:24:17 +0000484
Caroline Tice0aa2e552011-01-14 00:29:16 +0000485 run_string.Clear();
Caroline Tice0aa2e552011-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 Tice5867f6b2010-10-18 18:24:17 +0000494
Caroline Tice0aa2e552011-01-14 00:29:16 +0000495 int old_count = Debugger::TestDebuggerRefCount();
Greg Claytonb302dff2012-02-01 08:09:32 +0000496
Greg Clayton4e651b12012-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 Tice0aa2e552011-01-14 00:29:16 +0000498 PyRun_SimpleString (run_string.GetData());
Greg Clayton24b48ff2010-10-17 22:03:32 +0000499
Enrico Granata8f84cfb2012-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();
Greg Clayton4e651b12012-04-25 00:58:03 +0000503 //run_string.Printf ("run_one_line (%s, 'from lldb.formatters import *; from lldb.formatters.objc import *; from lldb.formatters.cpp import *')", m_dictionary_name.c_str());
Enrico Granataa5c2ce02012-04-25 17:53:41 +0000504 run_string.Printf ("run_one_line (%s, 'import lldb.runtime.objc, lldb.formatters, lldb.formatters.objc, lldb.formatters.cpp')", m_dictionary_name.c_str());
Enrico Granata8f84cfb2012-02-23 23:10:03 +0000505 PyRun_SimpleString (run_string.GetData());
Greg Claytonb302dff2012-02-01 08:09:32 +0000506
Caroline Tice0aa2e552011-01-14 00:29:16 +0000507 int new_count = Debugger::TestDebuggerRefCount();
Chris Lattner24943d22010-06-08 16:52:24 +0000508
Caroline Tice0aa2e552011-01-14 00:29:16 +0000509 if (new_count > old_count)
510 Debugger::Terminate();
Caroline Tice5867f6b2010-10-18 18:24:17 +0000511
Caroline Tice0aa2e552011-01-14 00:29:16 +0000512 run_string.Clear();
Greg Clayton444e35b2011-10-19 18:09:39 +0000513 run_string.Printf ("run_one_line (%s, 'lldb.debugger_unique_id = %llu')", m_dictionary_name.c_str(),
Caroline Tice0aa2e552011-01-14 00:29:16 +0000514 interpreter.GetDebugger().GetID());
515 PyRun_SimpleString (run_string.GetData());
516
517 if (m_dbg_stdout != NULL)
Chris Lattner24943d22010-06-08 16:52:24 +0000518 {
Caroline Tice0aa2e552011-01-14 00:29:16 +0000519 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
Caroline Tice5867f6b2010-10-18 18:24:17 +0000520 }
Chris Lattner24943d22010-06-08 16:52:24 +0000521}
522
523ScriptInterpreterPython::~ScriptInterpreterPython ()
524{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000525 Debugger &debugger = GetCommandInterpreter().GetDebugger();
526
527 if (m_embedded_thread_input_reader_sp.get() != NULL)
528 {
529 m_embedded_thread_input_reader_sp->SetIsDone (true);
Johnny Chen8121d7a2012-08-17 23:44:35 +0000530 m_embedded_thread_pty.CloseSlaveFileDescriptor();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000531 const InputReaderSP reader_sp = m_embedded_thread_input_reader_sp;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000532 debugger.PopInputReader (reader_sp);
Johnny Chen8121d7a2012-08-17 23:44:35 +0000533 m_embedded_thread_input_reader_sp.reset();
534 }
535
536 if (m_embedded_python_input_reader_sp.get() != NULL)
537 {
538 m_embedded_python_input_reader_sp->SetIsDone (true);
539 m_embedded_python_pty.CloseSlaveFileDescriptor();
540 const InputReaderSP reader_sp = m_embedded_python_input_reader_sp;
541 debugger.PopInputReader (reader_sp);
542 m_embedded_python_input_reader_sp.reset();
Caroline Tice0aa2e552011-01-14 00:29:16 +0000543 }
544
545 if (m_new_sysout)
546 {
Enrico Granatafa1f6172011-10-24 17:22:21 +0000547 Locker locker(this,
548 ScriptInterpreterPython::Locker::AcquireLock,
549 ScriptInterpreterPython::Locker::FreeLock);
550 Py_DECREF ((PyObject*)m_new_sysout);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000551 }
Chris Lattner24943d22010-06-08 16:52:24 +0000552}
553
Caroline Tice0aa2e552011-01-14 00:29:16 +0000554void
555ScriptInterpreterPython::ResetOutputFileHandle (FILE *fh)
556{
557 if (fh == NULL)
558 return;
559
560 m_dbg_stdout = fh;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000561
Johnny Chenc65046d2012-03-08 20:53:04 +0000562 Locker locker(this,
563 ScriptInterpreterPython::Locker::AcquireLock,
564 ScriptInterpreterPython::Locker::FreeAcquiredLock);
565
Enrico Granata91544802011-09-06 19:20:51 +0000566 m_new_sysout = PyFile_FromFile (m_dbg_stdout, (char *) "", (char *) "w", _check_and_flush);
Caroline Tice0aa2e552011-01-14 00:29:16 +0000567}
568
569void
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000570ScriptInterpreterPython::SaveTerminalState (int fd)
571{
572 // Python mucks with the terminal state of STDIN. If we can possibly avoid
573 // this by setting the file handles up correctly prior to entering the
574 // interpreter we should. For now we save and restore the terminal state
575 // on the input file handle.
576 m_terminal_state.Save (fd, false);
577}
578
579void
580ScriptInterpreterPython::RestoreTerminalState ()
581{
582 // Python mucks with the terminal state of STDIN. If we can possibly avoid
583 // this by setting the file handles up correctly prior to entering the
584 // interpreter we should. For now we save and restore the terminal state
585 // on the input file handle.
586 m_terminal_state.Restore();
587}
588
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000589void
Caroline Tice0aa2e552011-01-14 00:29:16 +0000590ScriptInterpreterPython::LeaveSession ()
591{
Enrico Granata7aa754c2012-04-04 17:31:29 +0000592 // checking that we have a valid thread state - since we use our own threading and locking
593 // in some (rare) cases during cleanup Python may end up believing we have no thread state
594 // and PyImport_AddModule will crash if that is the case - since that seems to only happen
595 // when destroying the SBDebugger, we can make do without clearing up stdout and stderr
Johnny Chen2b536952012-05-04 20:37:11 +0000596
597 // rdar://problem/11292882
598 // When the current thread state is NULL, PyThreadState_Get() issues a fatal error.
599 if (PyThreadState_GetDict())
Johnny Chen41641f92012-02-29 01:52:13 +0000600 {
Enrico Granata7aa754c2012-04-04 17:31:29 +0000601 PyObject *sysmod = PyImport_AddModule ("sys");
602 PyObject *sysdict = PyModule_GetDict (sysmod);
603
604 if (m_new_sysout && sysmod && sysdict)
605 {
606 if (m_old_sysout)
607 PyDict_SetItemString (sysdict, "stdout", (PyObject*)m_old_sysout);
608 if (m_old_syserr)
609 PyDict_SetItemString (sysdict, "stderr", (PyObject*)m_old_syserr);
610 }
Johnny Chen41641f92012-02-29 01:52:13 +0000611 }
612
Caroline Tice0aa2e552011-01-14 00:29:16 +0000613 m_session_is_active = false;
614}
615
616void
617ScriptInterpreterPython::EnterSession ()
618{
619 // If we have already entered the session, without having officially 'left' it, then there is no need to
620 // 'enter' it again.
621
622 if (m_session_is_active)
623 return;
624
625 m_session_is_active = true;
626
Caroline Tice202f6b82011-01-17 21:55:19 +0000627 StreamString run_string;
628
Greg Clayton2fecc452012-01-28 02:11:02 +0000629 run_string.Printf ( "run_one_line (%s, 'lldb.debugger_unique_id = %llu", m_dictionary_name.c_str(), GetCommandInterpreter().GetDebugger().GetID());
630 run_string.Printf ( "; lldb.debugger = lldb.SBDebugger.FindDebuggerWithID (%llu)", GetCommandInterpreter().GetDebugger().GetID());
631 run_string.PutCString ("; lldb.target = lldb.debugger.GetSelectedTarget()");
632 run_string.PutCString ("; lldb.process = lldb.target.GetProcess()");
633 run_string.PutCString ("; lldb.thread = lldb.process.GetSelectedThread ()");
634 run_string.PutCString ("; lldb.frame = lldb.thread.GetSelectedFrame ()");
635 // Make sure STDIN is closed since when we run this as an embedded
636 // interpreter we don't want someone to call "line = sys.stdin.readline()"
637 // and lock up. We don't have multiple windows and when the interpreter is
638 // embedded we don't know we should be feeding input to the embedded
639 // interpreter or to the python sys.stdin. We also don't want to let python
640 // play with the real stdin from this process, so we need to close it...
Greg Clayton3eeaf6e2012-02-03 01:30:30 +0000641 //run_string.PutCString ("; sys.stdin.close()");
Greg Clayton2fecc452012-01-28 02:11:02 +0000642 run_string.PutCString ("')");
Caroline Tice0aa2e552011-01-14 00:29:16 +0000643
Caroline Tice6af65cb2011-05-03 21:21:50 +0000644 PyRun_SimpleString (run_string.GetData());
645 run_string.Clear();
Johnny Chen41641f92012-02-29 01:52:13 +0000646
Caroline Tice0aa2e552011-01-14 00:29:16 +0000647 PyObject *sysmod = PyImport_AddModule ("sys");
648 PyObject *sysdict = PyModule_GetDict (sysmod);
Johnny Chen41641f92012-02-29 01:52:13 +0000649
Greg Clayton2fecc452012-01-28 02:11:02 +0000650 if (m_new_sysout && sysmod && sysdict)
651 {
Johnny Chen41641f92012-02-29 01:52:13 +0000652 m_old_sysout = PyDict_GetItemString(sysdict, "stdout");
653 m_old_syserr = PyDict_GetItemString(sysdict, "stderr");
Johnny Chenc65046d2012-03-08 20:53:04 +0000654 if (m_new_sysout)
655 {
656 PyDict_SetItemString (sysdict, "stdout", (PyObject*)m_new_sysout);
657 PyDict_SetItemString (sysdict, "stderr", (PyObject*)m_new_sysout);
658 }
Greg Clayton2fecc452012-01-28 02:11:02 +0000659 }
Johnny Chen41641f92012-02-29 01:52:13 +0000660
Caroline Tice0aa2e552011-01-14 00:29:16 +0000661 if (PyErr_Occurred())
662 PyErr_Clear ();
Greg Clayton2fecc452012-01-28 02:11:02 +0000663}
Caroline Tice0aa2e552011-01-14 00:29:16 +0000664
Enrico Granata400105d2012-03-06 23:42:15 +0000665static PyObject*
666FindSessionDictionary (const char* dict_name)
667{
668 static std::map<ConstString,PyObject*> g_dict_map;
669
670 ConstString dict(dict_name);
671
672 std::map<ConstString,PyObject*>::iterator iter = g_dict_map.find(dict);
673
674 if (iter != g_dict_map.end())
675 return iter->second;
676
677 PyObject *main_mod = PyImport_AddModule ("__main__");
678 if (main_mod != NULL)
679 {
680 PyObject *main_dict = PyModule_GetDict (main_mod);
681 if ((main_dict != NULL)
682 && PyDict_Check (main_dict))
683 {
684 // Go through the main dictionary looking for the correct python script interpreter dictionary
685 PyObject *key, *value;
686 Py_ssize_t pos = 0;
687
688 while (PyDict_Next (main_dict, &pos, &key, &value))
689 {
690 // We have stolen references to the key and value objects in the dictionary; we need to increment
691 // them now so that Python's garbage collector doesn't collect them out from under us.
692 Py_INCREF (key);
693 Py_INCREF (value);
694 if (strcmp (PyString_AsString (key), dict_name) == 0)
695 {
696 g_dict_map[dict] = value;
697 return value;
698 }
699 }
700 }
701 }
702 return NULL;
703}
704
705static std::string
706GenerateUniqueName (const char* base_name_wanted,
707 uint32_t& functions_counter,
708 void* name_token = NULL)
709{
710 StreamString sstr;
711
712 if (!base_name_wanted)
713 return std::string();
714
715 if (!name_token)
716 sstr.Printf ("%s_%d", base_name_wanted, functions_counter++);
717 else
718 sstr.Printf ("%s_%p", base_name_wanted, name_token);
719
720 return sstr.GetString();
721}
722
Johnny Chen60dde642010-07-30 22:33:14 +0000723bool
Enrico Granataa1ba3142012-06-07 00:17:18 +0000724ScriptInterpreterPython::ExecuteOneLine (const char *command, CommandReturnObject *result, bool enable_io)
Chris Lattner24943d22010-06-08 16:52:24 +0000725{
Caroline Tice0aa2e552011-01-14 00:29:16 +0000726 if (!m_valid_session)
727 return false;
728
Caroline Tice4a461da2011-01-14 21:09:29 +0000729 // We want to call run_one_line, passing in the dictionary and the command string. We cannot do this through
730 // PyRun_SimpleString here because the command string may contain escaped characters, and putting it inside
731 // another string to pass to PyRun_SimpleString messes up the escaping. So we use the following more complicated
732 // method to pass the command string directly down to Python.
733
Enrico Granatafa1f6172011-10-24 17:22:21 +0000734 Locker locker(this,
735 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
736 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
Caroline Tice4a461da2011-01-14 21:09:29 +0000737
738 bool success = false;
739
Greg Clayton63094e02010-06-23 01:19:29 +0000740 if (command)
Chris Lattner24943d22010-06-08 16:52:24 +0000741 {
Caroline Tice4a461da2011-01-14 21:09:29 +0000742 // Find the correct script interpreter dictionary in the main module.
Enrico Granata400105d2012-03-06 23:42:15 +0000743 PyObject *script_interpreter_dict = FindSessionDictionary(m_dictionary_name.c_str());
744 if (script_interpreter_dict != NULL)
Caroline Tice4a461da2011-01-14 21:09:29 +0000745 {
Enrico Granata400105d2012-03-06 23:42:15 +0000746 PyObject *pfunc = (PyObject*)m_run_one_line;
Greg Clayton6f2f0ab2012-04-25 01:49:50 +0000747 PyObject *pmod = PyImport_AddModule ("lldb.embedded_interpreter");
Enrico Granata400105d2012-03-06 23:42:15 +0000748 if (pmod != NULL)
Caroline Tice4a461da2011-01-14 21:09:29 +0000749 {
Enrico Granata400105d2012-03-06 23:42:15 +0000750 PyObject *pmod_dict = PyModule_GetDict (pmod);
751 if ((pmod_dict != NULL)
752 && PyDict_Check (pmod_dict))
Caroline Tice4a461da2011-01-14 21:09:29 +0000753 {
Enrico Granata400105d2012-03-06 23:42:15 +0000754 if (!pfunc)
Caroline Tice4a461da2011-01-14 21:09:29 +0000755 {
756 PyObject *key, *value;
757 Py_ssize_t pos = 0;
758
759 while (PyDict_Next (pmod_dict, &pos, &key, &value))
760 {
761 Py_INCREF (key);
762 Py_INCREF (value);
763 if (strcmp (PyString_AsString (key), "run_one_line") == 0)
764 {
765 pfunc = value;
766 break;
767 }
768 }
Enrico Granata400105d2012-03-06 23:42:15 +0000769 m_run_one_line = pfunc;
770 }
771
772 if (pfunc && PyCallable_Check (pfunc))
773 {
774 PyObject *pargs = Py_BuildValue("(Os)",script_interpreter_dict,command);
775 if (pargs != NULL)
Caroline Tice4a461da2011-01-14 21:09:29 +0000776 {
Enrico Granataa1ba3142012-06-07 00:17:18 +0000777 PyObject *pvalue = NULL;
778 { // scope for PythonInputReaderManager
779 PythonInputReaderManager py_input(enable_io ? this : NULL);
780 pvalue = PyObject_CallObject (pfunc, pargs);
781 }
Enrico Granata400105d2012-03-06 23:42:15 +0000782 Py_DECREF (pargs);
783 if (pvalue != NULL)
Caroline Tice4a461da2011-01-14 21:09:29 +0000784 {
Enrico Granata400105d2012-03-06 23:42:15 +0000785 Py_DECREF (pvalue);
786 success = true;
787 }
788 else if (PyErr_Occurred ())
789 {
790 PyErr_Print();
791 PyErr_Clear();
Caroline Tice4a461da2011-01-14 21:09:29 +0000792 }
793 }
794 }
795 }
Caroline Tice4a461da2011-01-14 21:09:29 +0000796 }
Enrico Granata400105d2012-03-06 23:42:15 +0000797 Py_INCREF (script_interpreter_dict);
Caroline Tice4a461da2011-01-14 21:09:29 +0000798 }
Greg Clayton63094e02010-06-23 01:19:29 +0000799
Caroline Tice4a461da2011-01-14 21:09:29 +0000800 if (success)
Johnny Chen60dde642010-07-30 22:33:14 +0000801 return true;
802
803 // The one-liner failed. Append the error message.
804 if (result)
805 result->AppendErrorWithFormat ("python failed attempting to evaluate '%s'\n", command);
806 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000807 }
Johnny Chen60dde642010-07-30 22:33:14 +0000808
809 if (result)
810 result->AppendError ("empty command passed to python\n");
811 return false;
Chris Lattner24943d22010-06-08 16:52:24 +0000812}
813
Chris Lattner24943d22010-06-08 16:52:24 +0000814size_t
815ScriptInterpreterPython::InputReaderCallback
816(
817 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +0000818 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +0000819 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +0000820 const char *bytes,
821 size_t bytes_len
822)
823{
Caroline Tice2ade6112010-11-10 19:18:14 +0000824 lldb::thread_t embedded_interpreter_thread;
825 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
826
Chris Lattner24943d22010-06-08 16:52:24 +0000827 if (baton == NULL)
828 return 0;
Caroline Tice0aa2e552011-01-14 00:29:16 +0000829
830 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
Enrico Granatafa1f6172011-10-24 17:22:21 +0000831
Caroline Tice0aa2e552011-01-14 00:29:16 +0000832 if (script_interpreter->m_script_lang != eScriptLanguagePython)
833 return 0;
834
Caroline Tice892fadd2011-06-16 16:27:19 +0000835 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
836 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
837
Chris Lattner24943d22010-06-08 16:52:24 +0000838 switch (notification)
839 {
840 case eInputReaderActivate:
841 {
Caroline Tice892fadd2011-06-16 16:27:19 +0000842 if (!batch_mode)
843 {
844 out_stream->Printf ("Python Interactive Interpreter. To exit, type 'quit()', 'exit()' or Ctrl-D.\n");
845 out_stream->Flush();
846 }
Greg Clayton58928562011-02-09 01:08:52 +0000847
Chris Lattner24943d22010-06-08 16:52:24 +0000848 // Save terminal settings if we can
Greg Clayton58928562011-02-09 01:08:52 +0000849 int input_fd = reader.GetDebugger().GetInputFile().GetDescriptor();
850 if (input_fd == File::kInvalidDescriptor)
Greg Clayton24b48ff2010-10-17 22:03:32 +0000851 input_fd = STDIN_FILENO;
Caroline Ticec95c6d12010-09-14 22:49:06 +0000852
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000853 script_interpreter->SaveTerminalState(input_fd);
Greg Clayton99208582011-02-07 19:04:58 +0000854
Caroline Tice202f6b82011-01-17 21:55:19 +0000855 {
Enrico Granatafa1f6172011-10-24 17:22:21 +0000856 ScriptInterpreterPython::Locker locker(script_interpreter,
857 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
858 ScriptInterpreterPython::Locker::FreeAcquiredLock);
Caroline Tice202f6b82011-01-17 21:55:19 +0000859 }
Caroline Tice202f6b82011-01-17 21:55:19 +0000860
Caroline Tice2ade6112010-11-10 19:18:14 +0000861 char error_str[1024];
862 if (script_interpreter->m_embedded_python_pty.OpenFirstAvailableMaster (O_RDWR|O_NOCTTY, error_str,
863 sizeof(error_str)))
864 {
865 if (log)
866 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in opening master pty (fd = %d).",
867 script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor());
868 embedded_interpreter_thread = Host::ThreadCreate ("<lldb.script-interpreter.embedded-python-loop>",
869 ScriptInterpreterPython::RunEmbeddedPythonInterpreter,
870 script_interpreter, NULL);
Greg Clayton09c81ef2011-02-08 01:34:25 +0000871 if (IS_VALID_LLDB_HOST_THREAD(embedded_interpreter_thread))
Caroline Tice2ade6112010-11-10 19:18:14 +0000872 {
873 if (log)
Jason Molendae09e2542011-09-20 23:23:44 +0000874 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, succeeded in creating thread (thread_t = %p)", embedded_interpreter_thread);
Caroline Tice2ade6112010-11-10 19:18:14 +0000875 Error detach_error;
876 Host::ThreadDetach (embedded_interpreter_thread, &detach_error);
877 }
878 else
879 {
880 if (log)
881 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed in creating thread");
882 reader.SetIsDone (true);
883 }
884 }
885 else
886 {
887 if (log)
888 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Activate, failed to open master pty ");
889 reader.SetIsDone (true);
890 }
Chris Lattner24943d22010-06-08 16:52:24 +0000891 }
892 break;
893
894 case eInputReaderDeactivate:
Greg Claytona1cec242012-01-06 00:47:38 +0000895 // When another input reader is pushed, don't leave the session...
896 //script_interpreter->LeaveSession ();
Chris Lattner24943d22010-06-08 16:52:24 +0000897 break;
898
899 case eInputReaderReactivate:
Caroline Tice202f6b82011-01-17 21:55:19 +0000900 {
Johnny Chen8165d432012-08-18 04:14:54 +0000901 ScriptInterpreterPython::Locker locker(script_interpreter,
902 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
903 ScriptInterpreterPython::Locker::FreeAcquiredLock);
Caroline Tice202f6b82011-01-17 21:55:19 +0000904 }
Chris Lattner24943d22010-06-08 16:52:24 +0000905 break;
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000906
Caroline Tice4a348082011-05-02 20:41:46 +0000907 case eInputReaderAsynchronousOutputWritten:
908 break;
909
Caroline Ticec4f55fe2010-11-19 20:47:54 +0000910 case eInputReaderInterrupt:
911 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "raise KeyboardInterrupt\n", 24);
912 break;
913
914 case eInputReaderEndOfFile:
915 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()\n", 7);
916 break;
Chris Lattner24943d22010-06-08 16:52:24 +0000917
918 case eInputReaderGotToken:
Caroline Tice2ade6112010-11-10 19:18:14 +0000919 if (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor() != -1)
Chris Lattner24943d22010-06-08 16:52:24 +0000920 {
Caroline Tice2ade6112010-11-10 19:18:14 +0000921 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000922 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %lu", bytes,
Caroline Tice2ade6112010-11-10 19:18:14 +0000923 bytes_len);
924 if (bytes && bytes_len)
925 {
926 if ((int) bytes[0] == 4)
927 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "quit()", 6);
928 else
929 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), bytes, bytes_len);
930 }
931 ::write (script_interpreter->m_embedded_python_pty.GetMasterFileDescriptor(), "\n", 1);
Chris Lattner24943d22010-06-08 16:52:24 +0000932 }
Caroline Tice2ade6112010-11-10 19:18:14 +0000933 else
934 {
935 if (log)
Jason Molenda7e5fa7f2011-09-20 21:44:10 +0000936 log->Printf ("ScriptInterpreterPython::InputReaderCallback, GotToken, bytes='%s', byte_len = %lu, Master File Descriptor is bad.",
Caroline Tice2ade6112010-11-10 19:18:14 +0000937 bytes,
938 bytes_len);
939 reader.SetIsDone (true);
940 }
941
Chris Lattner24943d22010-06-08 16:52:24 +0000942 break;
943
944 case eInputReaderDone:
Johnny Chen8165d432012-08-18 04:14:54 +0000945 {
946 Locker locker(script_interpreter,
947 ScriptInterpreterPython::Locker::AcquireLock,
948 ScriptInterpreterPython::Locker::FreeAcquiredLock);
949 script_interpreter->LeaveSession ();
950 }
Caroline Tice0aa2e552011-01-14 00:29:16 +0000951
Chris Lattner24943d22010-06-08 16:52:24 +0000952 // Restore terminal settings if they were validly saved
Caroline Tice2ade6112010-11-10 19:18:14 +0000953 if (log)
954 log->Printf ("ScriptInterpreterPython::InputReaderCallback, Done, closing down input reader.");
Caroline Ticec95c6d12010-09-14 22:49:06 +0000955
Greg Clayton0fdd4a02011-02-07 23:24:47 +0000956 script_interpreter->RestoreTerminalState ();
957
Caroline Tice2ade6112010-11-10 19:18:14 +0000958 script_interpreter->m_embedded_python_pty.CloseMasterFileDescriptor();
Chris Lattner24943d22010-06-08 16:52:24 +0000959 break;
960 }
961
962 return bytes_len;
963}
964
965
966void
Greg Clayton238c0a12010-09-18 01:14:36 +0000967ScriptInterpreterPython::ExecuteInterpreterLoop ()
Chris Lattner24943d22010-06-08 16:52:24 +0000968{
969 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
970
Caroline Tice0aa2e552011-01-14 00:29:16 +0000971 Debugger &debugger = GetCommandInterpreter().GetDebugger();
Caroline Ticec95c6d12010-09-14 22:49:06 +0000972
973 // At the moment, the only time the debugger does not have an input file handle is when this is called
974 // directly from Python, in which case it is both dangerous and unnecessary (not to mention confusing) to
975 // try to embed a running interpreter loop inside the already running Python interpreter loop, so we won't
976 // do it.
977
Greg Clayton58928562011-02-09 01:08:52 +0000978 if (!debugger.GetInputFile().IsValid())
Caroline Ticec95c6d12010-09-14 22:49:06 +0000979 return;
980
Greg Clayton63094e02010-06-23 01:19:29 +0000981 InputReaderSP reader_sp (new InputReader(debugger));
Chris Lattner24943d22010-06-08 16:52:24 +0000982 if (reader_sp)
983 {
984 Error error (reader_sp->Initialize (ScriptInterpreterPython::InputReaderCallback,
985 this, // baton
986 eInputReaderGranularityLine, // token size, to pass to callback function
987 NULL, // end token
988 NULL, // prompt
989 true)); // echo input
990
991 if (error.Success())
992 {
Greg Clayton63094e02010-06-23 01:19:29 +0000993 debugger.PushInputReader (reader_sp);
Johnny Chen8121d7a2012-08-17 23:44:35 +0000994 m_embedded_python_input_reader_sp = reader_sp;
Chris Lattner24943d22010-06-08 16:52:24 +0000995 }
996 }
997}
998
999bool
1000ScriptInterpreterPython::ExecuteOneLineWithReturn (const char *in_string,
Enrico Granata59df36f2011-10-17 21:45:27 +00001001 ScriptInterpreter::ScriptReturnType return_type,
Enrico Granataa1ba3142012-06-07 00:17:18 +00001002 void *ret_value,
1003 bool enable_io)
Chris Lattner24943d22010-06-08 16:52:24 +00001004{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001005
Enrico Granatafa1f6172011-10-24 17:22:21 +00001006 Locker locker(this,
1007 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
1008 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001009
Chris Lattner24943d22010-06-08 16:52:24 +00001010 PyObject *py_return = NULL;
1011 PyObject *mainmod = PyImport_AddModule ("__main__");
1012 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001013 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +00001014 PyObject *py_error = NULL;
Johnny Chen60a7df52011-08-11 19:17:45 +00001015 bool ret_success = false;
Caroline Tice0aa2e552011-01-14 00:29:16 +00001016 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +00001017 int success;
Caroline Tice0aa2e552011-01-14 00:29:16 +00001018
Enrico Granata400105d2012-03-06 23:42:15 +00001019 locals = FindSessionDictionary(m_dictionary_name.c_str());
1020
Caroline Tice0aa2e552011-01-14 00:29:16 +00001021 if (locals == NULL)
1022 {
1023 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
1024 should_decrement_locals = true;
1025 }
1026
1027 if (locals == NULL)
1028 {
1029 locals = globals;
1030 should_decrement_locals = false;
1031 }
1032
1033 py_error = PyErr_Occurred();
1034 if (py_error != NULL)
1035 PyErr_Clear();
1036
Chris Lattner24943d22010-06-08 16:52:24 +00001037 if (in_string != NULL)
1038 {
Enrico Granataa1ba3142012-06-07 00:17:18 +00001039 { // scope for PythonInputReaderManager
1040 PythonInputReaderManager py_input(enable_io ? this : NULL);
1041 py_return = PyRun_String (in_string, Py_eval_input, globals, locals);
1042 if (py_return == NULL)
1043 {
1044 py_error = PyErr_Occurred ();
1045 if (py_error != NULL)
1046 PyErr_Clear ();
Chris Lattner24943d22010-06-08 16:52:24 +00001047
Enrico Granataa1ba3142012-06-07 00:17:18 +00001048 py_return = PyRun_String (in_string, Py_single_input, globals, locals);
1049 }
Chris Lattner24943d22010-06-08 16:52:24 +00001050 }
1051
Caroline Tice0aa2e552011-01-14 00:29:16 +00001052 if (locals != NULL
1053 && should_decrement_locals)
1054 Py_DECREF (locals);
1055
Chris Lattner24943d22010-06-08 16:52:24 +00001056 if (py_return != NULL)
1057 {
1058 switch (return_type)
1059 {
Enrico Granata59df36f2011-10-17 21:45:27 +00001060 case eScriptReturnTypeCharPtr: // "char *"
Chris Lattner24943d22010-06-08 16:52:24 +00001061 {
1062 const char format[3] = "s#";
Enrico Granatae5e34cb2011-08-17 01:30:04 +00001063 success = PyArg_Parse (py_return, format, (char **) ret_value);
Chris Lattner24943d22010-06-08 16:52:24 +00001064 break;
1065 }
Enrico Granata59df36f2011-10-17 21:45:27 +00001066 case eScriptReturnTypeCharStrOrNone: // char* or NULL if py_return == Py_None
Enrico Granatac2a28252011-08-16 16:49:25 +00001067 {
1068 const char format[3] = "z";
Enrico Granatae5e34cb2011-08-17 01:30:04 +00001069 success = PyArg_Parse (py_return, format, (char **) ret_value);
Enrico Granatac2a28252011-08-16 16:49:25 +00001070 break;
1071 }
Enrico Granata59df36f2011-10-17 21:45:27 +00001072 case eScriptReturnTypeBool:
Chris Lattner24943d22010-06-08 16:52:24 +00001073 {
1074 const char format[2] = "b";
1075 success = PyArg_Parse (py_return, format, (bool *) ret_value);
1076 break;
1077 }
Enrico Granata59df36f2011-10-17 21:45:27 +00001078 case eScriptReturnTypeShortInt:
Chris Lattner24943d22010-06-08 16:52:24 +00001079 {
1080 const char format[2] = "h";
1081 success = PyArg_Parse (py_return, format, (short *) ret_value);
1082 break;
1083 }
Enrico Granata59df36f2011-10-17 21:45:27 +00001084 case eScriptReturnTypeShortIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +00001085 {
1086 const char format[2] = "H";
1087 success = PyArg_Parse (py_return, format, (unsigned short *) ret_value);
1088 break;
1089 }
Enrico Granata59df36f2011-10-17 21:45:27 +00001090 case eScriptReturnTypeInt:
Chris Lattner24943d22010-06-08 16:52:24 +00001091 {
1092 const char format[2] = "i";
1093 success = PyArg_Parse (py_return, format, (int *) ret_value);
1094 break;
1095 }
Enrico Granata59df36f2011-10-17 21:45:27 +00001096 case eScriptReturnTypeIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +00001097 {
1098 const char format[2] = "I";
1099 success = PyArg_Parse (py_return, format, (unsigned int *) ret_value);
1100 break;
1101 }
Enrico Granata59df36f2011-10-17 21:45:27 +00001102 case eScriptReturnTypeLongInt:
Chris Lattner24943d22010-06-08 16:52:24 +00001103 {
1104 const char format[2] = "l";
1105 success = PyArg_Parse (py_return, format, (long *) ret_value);
1106 break;
1107 }
Enrico Granata59df36f2011-10-17 21:45:27 +00001108 case eScriptReturnTypeLongIntUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +00001109 {
1110 const char format[2] = "k";
1111 success = PyArg_Parse (py_return, format, (unsigned long *) ret_value);
1112 break;
1113 }
Enrico Granata59df36f2011-10-17 21:45:27 +00001114 case eScriptReturnTypeLongLong:
Chris Lattner24943d22010-06-08 16:52:24 +00001115 {
1116 const char format[2] = "L";
1117 success = PyArg_Parse (py_return, format, (long long *) ret_value);
1118 break;
1119 }
Enrico Granata59df36f2011-10-17 21:45:27 +00001120 case eScriptReturnTypeLongLongUnsigned:
Chris Lattner24943d22010-06-08 16:52:24 +00001121 {
1122 const char format[2] = "K";
1123 success = PyArg_Parse (py_return, format, (unsigned long long *) ret_value);
1124 break;
1125 }
Enrico Granata59df36f2011-10-17 21:45:27 +00001126 case eScriptReturnTypeFloat:
Chris Lattner24943d22010-06-08 16:52:24 +00001127 {
1128 const char format[2] = "f";
1129 success = PyArg_Parse (py_return, format, (float *) ret_value);
1130 break;
1131 }
Enrico Granata59df36f2011-10-17 21:45:27 +00001132 case eScriptReturnTypeDouble:
Chris Lattner24943d22010-06-08 16:52:24 +00001133 {
1134 const char format[2] = "d";
1135 success = PyArg_Parse (py_return, format, (double *) ret_value);
1136 break;
1137 }
Enrico Granata59df36f2011-10-17 21:45:27 +00001138 case eScriptReturnTypeChar:
Chris Lattner24943d22010-06-08 16:52:24 +00001139 {
1140 const char format[2] = "c";
1141 success = PyArg_Parse (py_return, format, (char *) ret_value);
1142 break;
1143 }
1144 default:
1145 {}
1146 }
1147 Py_DECREF (py_return);
1148 if (success)
1149 ret_success = true;
1150 else
1151 ret_success = false;
1152 }
1153 }
1154
1155 py_error = PyErr_Occurred();
1156 if (py_error != NULL)
1157 {
1158 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
1159 PyErr_Print ();
1160 PyErr_Clear();
1161 ret_success = false;
1162 }
Caroline Tice202f6b82011-01-17 21:55:19 +00001163
Chris Lattner24943d22010-06-08 16:52:24 +00001164 return ret_success;
1165}
1166
1167bool
Enrico Granataa1ba3142012-06-07 00:17:18 +00001168ScriptInterpreterPython::ExecuteMultipleLines (const char *in_string, bool enable_io)
Chris Lattner24943d22010-06-08 16:52:24 +00001169{
Enrico Granatafa1f6172011-10-24 17:22:21 +00001170
1171
1172 Locker locker(this,
1173 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
1174 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001175
Chris Lattner24943d22010-06-08 16:52:24 +00001176 bool success = false;
1177 PyObject *py_return = NULL;
1178 PyObject *mainmod = PyImport_AddModule ("__main__");
1179 PyObject *globals = PyModule_GetDict (mainmod);
Caroline Tice0aa2e552011-01-14 00:29:16 +00001180 PyObject *locals = NULL;
Chris Lattner24943d22010-06-08 16:52:24 +00001181 PyObject *py_error = NULL;
Caroline Tice0aa2e552011-01-14 00:29:16 +00001182 bool should_decrement_locals = false;
Chris Lattner24943d22010-06-08 16:52:24 +00001183
Enrico Granata400105d2012-03-06 23:42:15 +00001184 locals = FindSessionDictionary(m_dictionary_name.c_str());
1185
Caroline Tice0aa2e552011-01-14 00:29:16 +00001186 if (locals == NULL)
1187 {
1188 locals = PyObject_GetAttrString (globals, m_dictionary_name.c_str());
1189 should_decrement_locals = true;
1190 }
1191
1192 if (locals == NULL)
1193 {
1194 locals = globals;
1195 should_decrement_locals = false;
1196 }
1197
1198 py_error = PyErr_Occurred();
1199 if (py_error != NULL)
1200 PyErr_Clear();
1201
Chris Lattner24943d22010-06-08 16:52:24 +00001202 if (in_string != NULL)
1203 {
1204 struct _node *compiled_node = PyParser_SimpleParseString (in_string, Py_file_input);
1205 if (compiled_node)
1206 {
1207 PyCodeObject *compiled_code = PyNode_Compile (compiled_node, "temp.py");
1208 if (compiled_code)
1209 {
Enrico Granataa1ba3142012-06-07 00:17:18 +00001210 { // scope for PythonInputReaderManager
1211 PythonInputReaderManager py_input(enable_io ? this : NULL);
1212 py_return = PyEval_EvalCode (compiled_code, globals, locals);
1213 }
Chris Lattner24943d22010-06-08 16:52:24 +00001214 if (py_return != NULL)
1215 {
1216 success = true;
1217 Py_DECREF (py_return);
1218 }
Caroline Tice0aa2e552011-01-14 00:29:16 +00001219 if (locals && should_decrement_locals)
1220 Py_DECREF (locals);
Chris Lattner24943d22010-06-08 16:52:24 +00001221 }
1222 }
1223 }
1224
1225 py_error = PyErr_Occurred ();
1226 if (py_error != NULL)
1227 {
1228 if (PyErr_GivenExceptionMatches (py_error, PyExc_SyntaxError))
1229 PyErr_Print ();
1230 PyErr_Clear();
1231 success = false;
1232 }
1233
1234 return success;
1235}
1236
1237static const char *g_reader_instructions = "Enter your Python command(s). Type 'DONE' to end.";
1238
1239size_t
1240ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback
1241(
1242 void *baton,
Greg Clayton63094e02010-06-23 01:19:29 +00001243 InputReader &reader,
Greg Clayton5144f382010-10-07 17:14:24 +00001244 InputReaderAction notification,
Chris Lattner24943d22010-06-08 16:52:24 +00001245 const char *bytes,
1246 size_t bytes_len
1247)
1248{
Caroline Tice892fadd2011-06-16 16:27:19 +00001249 static StringList commands_in_progress;
1250
1251 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
1252 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
1253
Chris Lattner24943d22010-06-08 16:52:24 +00001254 switch (notification)
1255 {
1256 case eInputReaderActivate:
1257 {
1258 commands_in_progress.Clear();
Caroline Tice892fadd2011-06-16 16:27:19 +00001259 if (!batch_mode)
Chris Lattner24943d22010-06-08 16:52:24 +00001260 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001261 out_stream->Printf ("%s\n", g_reader_instructions);
Greg Clayton63094e02010-06-23 01:19:29 +00001262 if (reader.GetPrompt())
Caroline Tice892fadd2011-06-16 16:27:19 +00001263 out_stream->Printf ("%s", reader.GetPrompt());
1264 out_stream->Flush ();
Chris Lattner24943d22010-06-08 16:52:24 +00001265 }
1266 }
1267 break;
1268
1269 case eInputReaderDeactivate:
1270 break;
1271
1272 case eInputReaderReactivate:
Caroline Tice892fadd2011-06-16 16:27:19 +00001273 if (reader.GetPrompt() && !batch_mode)
Caroline Ticef81b4c52010-10-27 18:34:42 +00001274 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001275 out_stream->Printf ("%s", reader.GetPrompt());
1276 out_stream->Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +00001277 }
Chris Lattner24943d22010-06-08 16:52:24 +00001278 break;
1279
Caroline Tice4a348082011-05-02 20:41:46 +00001280 case eInputReaderAsynchronousOutputWritten:
1281 break;
1282
Chris Lattner24943d22010-06-08 16:52:24 +00001283 case eInputReaderGotToken:
1284 {
1285 std::string temp_string (bytes, bytes_len);
1286 commands_in_progress.AppendString (temp_string.c_str());
Caroline Tice892fadd2011-06-16 16:27:19 +00001287 if (!reader.IsDone() && reader.GetPrompt() && !batch_mode)
Caroline Ticef81b4c52010-10-27 18:34:42 +00001288 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001289 out_stream->Printf ("%s", reader.GetPrompt());
1290 out_stream->Flush ();
Caroline Ticef81b4c52010-10-27 18:34:42 +00001291 }
Chris Lattner24943d22010-06-08 16:52:24 +00001292 }
1293 break;
1294
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001295 case eInputReaderEndOfFile:
1296 case eInputReaderInterrupt:
1297 // Control-c (SIGINT) & control-d both mean finish & exit.
1298 reader.SetIsDone(true);
1299
1300 // Control-c (SIGINT) ALSO means cancel; do NOT create a breakpoint command.
1301 if (notification == eInputReaderInterrupt)
1302 commands_in_progress.Clear();
1303
1304 // Fall through here...
1305
Chris Lattner24943d22010-06-08 16:52:24 +00001306 case eInputReaderDone:
1307 {
1308 BreakpointOptions *bp_options = (BreakpointOptions *)baton;
1309 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1310 data_ap->user_source.AppendList (commands_in_progress);
1311 if (data_ap.get())
1312 {
Greg Clayton63094e02010-06-23 01:19:29 +00001313 ScriptInterpreter *interpreter = reader.GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
Chris Lattner24943d22010-06-08 16:52:24 +00001314 if (interpreter)
1315 {
1316 if (interpreter->GenerateBreakpointCommandCallbackData (data_ap->user_source,
1317 data_ap->script_source))
1318 {
Enrico Granata400105d2012-03-06 23:42:15 +00001319 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1320 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001321 }
Caroline Tice892fadd2011-06-16 16:27:19 +00001322 else if (!batch_mode)
1323 {
1324 out_stream->Printf ("Warning: No command attached to breakpoint.\n");
1325 out_stream->Flush();
1326 }
Chris Lattner24943d22010-06-08 16:52:24 +00001327 }
1328 else
1329 {
Caroline Tice892fadd2011-06-16 16:27:19 +00001330 if (!batch_mode)
1331 {
1332 out_stream->Printf ("Warning: Unable to find script intepreter; no command attached to breakpoint.\n");
1333 out_stream->Flush();
1334 }
Chris Lattner24943d22010-06-08 16:52:24 +00001335 }
1336 }
1337 }
1338 break;
1339
1340 }
1341
1342 return bytes_len;
1343}
1344
Johnny Chenf3ec4612012-08-09 23:09:42 +00001345size_t
1346ScriptInterpreterPython::GenerateWatchpointOptionsCommandCallback
1347(
1348 void *baton,
1349 InputReader &reader,
1350 InputReaderAction notification,
1351 const char *bytes,
1352 size_t bytes_len
1353)
1354{
1355 static StringList commands_in_progress;
1356
1357 StreamSP out_stream = reader.GetDebugger().GetAsyncOutputStream();
1358 bool batch_mode = reader.GetDebugger().GetCommandInterpreter().GetBatchCommandMode();
1359
1360 switch (notification)
1361 {
1362 case eInputReaderActivate:
1363 {
1364 commands_in_progress.Clear();
1365 if (!batch_mode)
1366 {
1367 out_stream->Printf ("%s\n", g_reader_instructions);
1368 if (reader.GetPrompt())
1369 out_stream->Printf ("%s", reader.GetPrompt());
1370 out_stream->Flush ();
1371 }
1372 }
1373 break;
1374
1375 case eInputReaderDeactivate:
1376 break;
1377
1378 case eInputReaderReactivate:
1379 if (reader.GetPrompt() && !batch_mode)
1380 {
1381 out_stream->Printf ("%s", reader.GetPrompt());
1382 out_stream->Flush ();
1383 }
1384 break;
1385
1386 case eInputReaderAsynchronousOutputWritten:
1387 break;
1388
1389 case eInputReaderGotToken:
1390 {
1391 std::string temp_string (bytes, bytes_len);
1392 commands_in_progress.AppendString (temp_string.c_str());
1393 if (!reader.IsDone() && reader.GetPrompt() && !batch_mode)
1394 {
1395 out_stream->Printf ("%s", reader.GetPrompt());
1396 out_stream->Flush ();
1397 }
1398 }
1399 break;
1400
1401 case eInputReaderEndOfFile:
1402 case eInputReaderInterrupt:
1403 // Control-c (SIGINT) & control-d both mean finish & exit.
1404 reader.SetIsDone(true);
1405
1406 // Control-c (SIGINT) ALSO means cancel; do NOT create a breakpoint command.
1407 if (notification == eInputReaderInterrupt)
1408 commands_in_progress.Clear();
1409
1410 // Fall through here...
1411
1412 case eInputReaderDone:
1413 {
1414 WatchpointOptions *wp_options = (WatchpointOptions *)baton;
1415 std::auto_ptr<WatchpointOptions::CommandData> data_ap(new WatchpointOptions::CommandData());
1416 data_ap->user_source.AppendList (commands_in_progress);
1417 if (data_ap.get())
1418 {
1419 ScriptInterpreter *interpreter = reader.GetDebugger().GetCommandInterpreter().GetScriptInterpreter();
1420 if (interpreter)
1421 {
1422 if (interpreter->GenerateWatchpointCommandCallbackData (data_ap->user_source,
1423 data_ap->script_source))
1424 {
1425 BatonSP baton_sp (new WatchpointOptions::CommandBaton (data_ap.release()));
1426 wp_options->SetCallback (ScriptInterpreterPython::WatchpointCallbackFunction, baton_sp);
1427 }
1428 else if (!batch_mode)
1429 {
1430 out_stream->Printf ("Warning: No command attached to breakpoint.\n");
1431 out_stream->Flush();
1432 }
1433 }
1434 else
1435 {
1436 if (!batch_mode)
1437 {
1438 out_stream->Printf ("Warning: Unable to find script intepreter; no command attached to breakpoint.\n");
1439 out_stream->Flush();
1440 }
1441 }
1442 }
1443 }
1444 break;
1445
1446 }
1447
1448 return bytes_len;
1449}
1450
Chris Lattner24943d22010-06-08 16:52:24 +00001451void
Greg Clayton238c0a12010-09-18 01:14:36 +00001452ScriptInterpreterPython::CollectDataForBreakpointCommandCallback (BreakpointOptions *bp_options,
Chris Lattner24943d22010-06-08 16:52:24 +00001453 CommandReturnObject &result)
1454{
Caroline Tice0aa2e552011-01-14 00:29:16 +00001455 Debugger &debugger = GetCommandInterpreter().GetDebugger();
1456
Greg Clayton63094e02010-06-23 01:19:29 +00001457 InputReaderSP reader_sp (new InputReader (debugger));
Chris Lattner24943d22010-06-08 16:52:24 +00001458
1459 if (reader_sp)
1460 {
1461 Error err = reader_sp->Initialize (
1462 ScriptInterpreterPython::GenerateBreakpointOptionsCommandCallback,
1463 bp_options, // baton
1464 eInputReaderGranularityLine, // token size, for feeding data to callback function
1465 "DONE", // end token
1466 "> ", // prompt
1467 true); // echo input
1468
1469 if (err.Success())
Greg Clayton63094e02010-06-23 01:19:29 +00001470 debugger.PushInputReader (reader_sp);
Chris Lattner24943d22010-06-08 16:52:24 +00001471 else
1472 {
1473 result.AppendError (err.AsCString());
1474 result.SetStatus (eReturnStatusFailed);
1475 }
1476 }
1477 else
1478 {
1479 result.AppendError("out of memory");
1480 result.SetStatus (eReturnStatusFailed);
1481 }
1482}
1483
Johnny Chenf3ec4612012-08-09 23:09:42 +00001484void
1485ScriptInterpreterPython::CollectDataForWatchpointCommandCallback (WatchpointOptions *wp_options,
1486 CommandReturnObject &result)
1487{
1488 Debugger &debugger = GetCommandInterpreter().GetDebugger();
1489
1490 InputReaderSP reader_sp (new InputReader (debugger));
1491
1492 if (reader_sp)
1493 {
1494 Error err = reader_sp->Initialize (
1495 ScriptInterpreterPython::GenerateWatchpointOptionsCommandCallback,
1496 wp_options, // baton
1497 eInputReaderGranularityLine, // token size, for feeding data to callback function
1498 "DONE", // end token
1499 "> ", // prompt
1500 true); // echo input
1501
1502 if (err.Success())
1503 debugger.PushInputReader (reader_sp);
1504 else
1505 {
1506 result.AppendError (err.AsCString());
1507 result.SetStatus (eReturnStatusFailed);
1508 }
1509 }
1510 else
1511 {
1512 result.AppendError("out of memory");
1513 result.SetStatus (eReturnStatusFailed);
1514 }
1515}
1516
Johnny Chen3e0571b2010-09-11 00:23:59 +00001517// Set a Python one-liner as the callback for the breakpoint.
Johnny Chend1c2dca2010-09-10 18:21:10 +00001518void
Greg Clayton238c0a12010-09-18 01:14:36 +00001519ScriptInterpreterPython::SetBreakpointCommandCallback (BreakpointOptions *bp_options,
Johnny Chend1c2dca2010-09-10 18:21:10 +00001520 const char *oneliner)
1521{
1522 std::auto_ptr<BreakpointOptions::CommandData> data_ap(new BreakpointOptions::CommandData());
1523
1524 // It's necessary to set both user_source and script_source to the oneliner.
1525 // The former is used to generate callback description (as in breakpoint command list)
1526 // while the latter is used for Python to interpret during the actual callback.
Caroline Tice5136f942010-09-27 21:35:15 +00001527
Johnny Chend1c2dca2010-09-10 18:21:10 +00001528 data_ap->user_source.AppendString (oneliner);
Johnny Chenf3ec4612012-08-09 23:09:42 +00001529 data_ap->script_source.assign (oneliner);
Johnny Chend1c2dca2010-09-10 18:21:10 +00001530
Caroline Tice5136f942010-09-27 21:35:15 +00001531 if (GenerateBreakpointCommandCallbackData (data_ap->user_source, data_ap->script_source))
1532 {
Enrico Granata400105d2012-03-06 23:42:15 +00001533 BatonSP baton_sp (new BreakpointOptions::CommandBaton (data_ap.release()));
1534 bp_options->SetCallback (ScriptInterpreterPython::BreakpointCallbackFunction, baton_sp);
Caroline Tice5136f942010-09-27 21:35:15 +00001535 }
1536
Johnny Chend1c2dca2010-09-10 18:21:10 +00001537 return;
1538}
1539
Johnny Chenf3ec4612012-08-09 23:09:42 +00001540// Set a Python one-liner as the callback for the watchpoint.
1541void
1542ScriptInterpreterPython::SetWatchpointCommandCallback (WatchpointOptions *wp_options,
1543 const char *oneliner)
1544{
1545 std::auto_ptr<WatchpointOptions::CommandData> data_ap(new WatchpointOptions::CommandData());
1546
1547 // It's necessary to set both user_source and script_source to the oneliner.
1548 // The former is used to generate callback description (as in watchpoint command list)
1549 // while the latter is used for Python to interpret during the actual callback.
1550
1551 data_ap->user_source.AppendString (oneliner);
1552 data_ap->script_source.assign (oneliner);
1553
1554 if (GenerateWatchpointCommandCallbackData (data_ap->user_source, data_ap->script_source))
1555 {
1556 BatonSP baton_sp (new WatchpointOptions::CommandBaton (data_ap.release()));
1557 wp_options->SetCallback (ScriptInterpreterPython::WatchpointCallbackFunction, baton_sp);
1558 }
1559
1560 return;
1561}
1562
Chris Lattner24943d22010-06-08 16:52:24 +00001563bool
1564ScriptInterpreterPython::ExportFunctionDefinitionToInterpreter (StringList &function_def)
1565{
1566 // Convert StringList to one long, newline delimited, const char *.
Enrico Granata400105d2012-03-06 23:42:15 +00001567 std::string function_def_string(function_def.CopyList());
Chris Lattner24943d22010-06-08 16:52:24 +00001568
Enrico Granataa1ba3142012-06-07 00:17:18 +00001569 return ExecuteMultipleLines (function_def_string.c_str(), false);
Chris Lattner24943d22010-06-08 16:52:24 +00001570}
1571
Enrico Granataf7a9b142011-07-15 02:26:42 +00001572bool
Enrico Granata400105d2012-03-06 23:42:15 +00001573ScriptInterpreterPython::GenerateFunction(const char *signature, const StringList &input)
Enrico Granataf7a9b142011-07-15 02:26:42 +00001574{
1575 int num_lines = input.GetSize ();
1576 if (num_lines == 0)
1577 return false;
Enrico Granata400105d2012-03-06 23:42:15 +00001578
1579 if (!signature || *signature == 0)
1580 return false;
1581
Enrico Granataf7a9b142011-07-15 02:26:42 +00001582 StreamString sstr;
1583 StringList auto_generated_function;
Enrico Granata400105d2012-03-06 23:42:15 +00001584 auto_generated_function.AppendString (signature);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001585 auto_generated_function.AppendString (" global_dict = globals()"); // Grab the global dictionary
Enrico Granatac1ca9dc2012-08-08 02:06:30 +00001586 auto_generated_function.AppendString (" new_keys = internal_dict.keys()"); // Make a list of keys in the session dict
Enrico Granataf7a9b142011-07-15 02:26:42 +00001587 auto_generated_function.AppendString (" old_keys = global_dict.keys()"); // Save list of keys in global dict
Enrico Granatac1ca9dc2012-08-08 02:06:30 +00001588 auto_generated_function.AppendString (" global_dict.update (internal_dict)"); // Add the session dictionary to the
Enrico Granataf7a9b142011-07-15 02:26:42 +00001589 // global dictionary.
1590
1591 // Wrap everything up inside the function, increasing the indentation.
1592
1593 for (int i = 0; i < num_lines; ++i)
1594 {
1595 sstr.Clear ();
1596 sstr.Printf (" %s", input.GetStringAtIndex (i));
1597 auto_generated_function.AppendString (sstr.GetData());
1598 }
1599 auto_generated_function.AppendString (" for key in new_keys:"); // Iterate over all the keys from session dict
Enrico Granatac1ca9dc2012-08-08 02:06:30 +00001600 auto_generated_function.AppendString (" internal_dict[key] = global_dict[key]"); // Update session dict values
Enrico Granataf7a9b142011-07-15 02:26:42 +00001601 auto_generated_function.AppendString (" if key not in old_keys:"); // If key was not originally in global dict
1602 auto_generated_function.AppendString (" del global_dict[key]"); // ...then remove key/value from global dict
1603
1604 // Verify that the results are valid Python.
1605
1606 if (!ExportFunctionDefinitionToInterpreter (auto_generated_function))
1607 return false;
1608
1609 return true;
1610
1611}
1612
Enrico Granataf7a9b142011-07-15 02:26:42 +00001613bool
Enrico Granata400105d2012-03-06 23:42:15 +00001614ScriptInterpreterPython::GenerateTypeScriptFunction (StringList &user_input, std::string& output, void* name_token)
Enrico Granataf7a9b142011-07-15 02:26:42 +00001615{
Enrico Granata400105d2012-03-06 23:42:15 +00001616 static uint32_t num_created_functions = 0;
Enrico Granataf7a9b142011-07-15 02:26:42 +00001617 user_input.RemoveBlankLines ();
Enrico Granataf7a9b142011-07-15 02:26:42 +00001618 StreamString sstr;
1619
1620 // Check to see if we have any data; if not, just return.
1621 if (user_input.GetSize() == 0)
1622 return false;
1623
1624 // Take what the user wrote, wrap it all up inside one big auto-generated Python function, passing in the
1625 // ValueObject as parameter to the function.
1626
Enrico Granata400105d2012-03-06 23:42:15 +00001627 std::string auto_generated_function_name(GenerateUniqueName("lldb_autogen_python_type_print_func", num_created_functions, name_token));
Enrico Granatac1ca9dc2012-08-08 02:06:30 +00001628 sstr.Printf ("def %s (valobj, internal_dict):", auto_generated_function_name.c_str());
Enrico Granataf7a9b142011-07-15 02:26:42 +00001629
Enrico Granata400105d2012-03-06 23:42:15 +00001630 if (!GenerateFunction(sstr.GetData(), user_input))
Enrico Granataf7a9b142011-07-15 02:26:42 +00001631 return false;
Enrico Granata400105d2012-03-06 23:42:15 +00001632
Enrico Granataf7a9b142011-07-15 02:26:42 +00001633 // Store the name of the auto-generated function to be called.
Enrico Granata400105d2012-03-06 23:42:15 +00001634 output.assign(auto_generated_function_name);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001635 return true;
1636}
1637
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001638bool
Enrico Granata400105d2012-03-06 23:42:15 +00001639ScriptInterpreterPython::GenerateScriptAliasFunction (StringList &user_input, std::string &output)
Enrico Granatac2a28252011-08-16 16:49:25 +00001640{
Enrico Granata400105d2012-03-06 23:42:15 +00001641 static uint32_t num_created_functions = 0;
Enrico Granatac2a28252011-08-16 16:49:25 +00001642 user_input.RemoveBlankLines ();
Enrico Granatac2a28252011-08-16 16:49:25 +00001643 StreamString sstr;
1644
1645 // Check to see if we have any data; if not, just return.
1646 if (user_input.GetSize() == 0)
1647 return false;
1648
Enrico Granata400105d2012-03-06 23:42:15 +00001649 std::string auto_generated_function_name(GenerateUniqueName("lldb_autogen_python_cmd_alias_func", num_created_functions));
1650
Enrico Granatac1ca9dc2012-08-08 02:06:30 +00001651 sstr.Printf ("def %s (debugger, args, result, internal_dict):", auto_generated_function_name.c_str());
Enrico Granatac2a28252011-08-16 16:49:25 +00001652
Enrico Granata400105d2012-03-06 23:42:15 +00001653 if (!GenerateFunction(sstr.GetData(),user_input))
Enrico Granatac2a28252011-08-16 16:49:25 +00001654 return false;
1655
1656 // Store the name of the auto-generated function to be called.
Enrico Granata400105d2012-03-06 23:42:15 +00001657 output.assign(auto_generated_function_name);
Enrico Granatac2a28252011-08-16 16:49:25 +00001658 return true;
1659}
1660
1661
1662bool
Enrico Granata400105d2012-03-06 23:42:15 +00001663ScriptInterpreterPython::GenerateTypeSynthClass (StringList &user_input, std::string &output, void* name_token)
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001664{
Enrico Granata400105d2012-03-06 23:42:15 +00001665 static uint32_t num_created_classes = 0;
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001666 user_input.RemoveBlankLines ();
1667 int num_lines = user_input.GetSize ();
1668 StreamString sstr;
1669
1670 // Check to see if we have any data; if not, just return.
1671 if (user_input.GetSize() == 0)
1672 return false;
1673
1674 // Wrap all user input into a Python class
1675
Enrico Granata400105d2012-03-06 23:42:15 +00001676 std::string auto_generated_class_name(GenerateUniqueName("lldb_autogen_python_type_synth_class",num_created_classes,name_token));
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001677
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001678 StringList auto_generated_class;
1679
1680 // Create the function name & definition string.
1681
1682 sstr.Printf ("class %s:", auto_generated_class_name.c_str());
1683 auto_generated_class.AppendString (sstr.GetData());
1684
1685 // Wrap everything up inside the class, increasing the indentation.
1686
1687 for (int i = 0; i < num_lines; ++i)
1688 {
1689 sstr.Clear ();
1690 sstr.Printf (" %s", user_input.GetStringAtIndex (i));
1691 auto_generated_class.AppendString (sstr.GetData());
1692 }
1693
1694
1695 // Verify that the results are valid Python.
1696 // (even though the method is ExportFunctionDefinitionToInterpreter, a class will actually be exported)
1697 // (TODO: rename that method to ExportDefinitionToInterpreter)
1698 if (!ExportFunctionDefinitionToInterpreter (auto_generated_class))
1699 return false;
1700
1701 // Store the name of the auto-generated class
1702
Enrico Granata400105d2012-03-06 23:42:15 +00001703 output.assign(auto_generated_class_name);
Enrico Granatae89ab7b2011-07-25 16:59:05 +00001704 return true;
1705}
1706
Enrico Granata400105d2012-03-06 23:42:15 +00001707lldb::ScriptInterpreterObjectSP
Enrico Granata155ee912012-08-24 00:30:47 +00001708ScriptInterpreterPython::CreateOSPlugin (std::string class_name,
1709 lldb::ProcessSP process_sp)
1710{
1711 if (class_name.empty())
1712 return lldb::ScriptInterpreterObjectSP();
1713
1714 if (!process_sp)
1715 return lldb::ScriptInterpreterObjectSP();
1716
1717 void* ret_val;
1718
1719 {
Enrico Granatacec963a2012-08-24 01:34:39 +00001720 Locker py_lock(this,Locker::AcquireLock,Locker::FreeLock);
Enrico Granata155ee912012-08-24 00:30:47 +00001721 ret_val = g_swig_create_os_plugin (class_name,
1722 m_dictionary_name.c_str(),
1723 process_sp);
1724 }
1725
1726 return MakeScriptObject(ret_val);
1727}
1728
1729lldb::ScriptInterpreterObjectSP
1730ScriptInterpreterPython::OSPlugin_QueryForRegisterInfo (lldb::ScriptInterpreterObjectSP object)
1731{
Enrico Granatacec963a2012-08-24 01:34:39 +00001732 Locker py_lock(this,Locker::AcquireLock,Locker::FreeLock);
1733
Enrico Granata155ee912012-08-24 00:30:47 +00001734 static char callee_name[] = "get_register_info";
1735
1736 if (!object)
1737 return lldb::ScriptInterpreterObjectSP();
1738
1739 PyObject* implementor = (PyObject*)object->GetObject();
1740
1741 if (implementor == NULL || implementor == Py_None)
1742 return lldb::ScriptInterpreterObjectSP();
1743
1744 PyObject* pmeth = PyObject_GetAttrString(implementor, callee_name);
1745
1746 if (PyErr_Occurred())
1747 {
1748 PyErr_Clear();
1749 }
1750
1751 if (pmeth == NULL || pmeth == Py_None)
1752 {
1753 Py_XDECREF(pmeth);
1754 return lldb::ScriptInterpreterObjectSP();
1755 }
1756
1757 if (PyCallable_Check(pmeth) == 0)
1758 {
1759 if (PyErr_Occurred())
1760 {
1761 PyErr_Clear();
1762 }
1763
1764 Py_XDECREF(pmeth);
1765 return lldb::ScriptInterpreterObjectSP();
1766 }
1767
1768 if (PyErr_Occurred())
1769 {
1770 PyErr_Clear();
1771 }
1772
1773 Py_XDECREF(pmeth);
1774
1775 // right now we know this function exists and is callable..
1776 PyObject* py_return = PyObject_CallMethod(implementor, callee_name, NULL);
1777
1778 // if it fails, print the error but otherwise go on
1779 if (PyErr_Occurred())
1780 {
1781 PyErr_Print();
1782 PyErr_Clear();
1783 }
1784
1785 return MakeScriptObject(py_return);
1786}
1787
1788lldb::ScriptInterpreterObjectSP
Enrico Granata3e85b632012-08-24 00:51:29 +00001789ScriptInterpreterPython::OSPlugin_QueryForThreadsInfo (lldb::ScriptInterpreterObjectSP object)
1790{
Enrico Granatacec963a2012-08-24 01:34:39 +00001791 Locker py_lock(this,Locker::AcquireLock,Locker::FreeLock);
1792
Enrico Granata3e85b632012-08-24 00:51:29 +00001793 static char callee_name[] = "get_thread_info";
1794
1795 if (!object)
1796 return lldb::ScriptInterpreterObjectSP();
1797
1798 PyObject* implementor = (PyObject*)object->GetObject();
1799
1800 if (implementor == NULL || implementor == Py_None)
1801 return lldb::ScriptInterpreterObjectSP();
1802
1803 PyObject* pmeth = PyObject_GetAttrString(implementor, callee_name);
1804
1805 if (PyErr_Occurred())
1806 {
1807 PyErr_Clear();
1808 }
1809
1810 if (pmeth == NULL || pmeth == Py_None)
1811 {
1812 Py_XDECREF(pmeth);
1813 return lldb::ScriptInterpreterObjectSP();
1814 }
1815
1816 if (PyCallable_Check(pmeth) == 0)
1817 {
1818 if (PyErr_Occurred())
1819 {
1820 PyErr_Clear();
1821 }
1822
1823 Py_XDECREF(pmeth);
1824 return lldb::ScriptInterpreterObjectSP();
1825 }
1826
1827 if (PyErr_Occurred())
1828 {
1829 PyErr_Clear();
1830 }
1831
1832 Py_XDECREF(pmeth);
1833
1834 // right now we know this function exists and is callable..
1835 PyObject* py_return = PyObject_CallMethod(implementor, callee_name, NULL);
1836
1837 // if it fails, print the error but otherwise go on
1838 if (PyErr_Occurred())
1839 {
1840 PyErr_Print();
1841 PyErr_Clear();
1842 }
1843
1844 return MakeScriptObject(py_return);
1845}
1846
1847lldb::ScriptInterpreterObjectSP
Greg Claytonb8f126a2012-08-24 05:45:15 +00001848ScriptInterpreterPython::OSPlugin_QueryForRegisterContextData (lldb::ScriptInterpreterObjectSP object,
1849 lldb::tid_t thread_id)
Enrico Granata3e85b632012-08-24 00:51:29 +00001850{
Enrico Granatacec963a2012-08-24 01:34:39 +00001851 Locker py_lock(this,Locker::AcquireLock,Locker::FreeLock);
1852
Enrico Granata3e85b632012-08-24 00:51:29 +00001853 static char callee_name[] = "get_register_data";
1854 static char param_format[] = "l";
1855
1856 if (!object)
1857 return lldb::ScriptInterpreterObjectSP();
1858
1859 PyObject* implementor = (PyObject*)object->GetObject();
1860
1861 if (implementor == NULL || implementor == Py_None)
1862 return lldb::ScriptInterpreterObjectSP();
1863
1864 PyObject* pmeth = PyObject_GetAttrString(implementor, callee_name);
1865
1866 if (PyErr_Occurred())
1867 {
1868 PyErr_Clear();
1869 }
1870
1871 if (pmeth == NULL || pmeth == Py_None)
1872 {
1873 Py_XDECREF(pmeth);
1874 return lldb::ScriptInterpreterObjectSP();
1875 }
1876
1877 if (PyCallable_Check(pmeth) == 0)
1878 {
1879 if (PyErr_Occurred())
1880 {
1881 PyErr_Clear();
1882 }
1883
1884 Py_XDECREF(pmeth);
1885 return lldb::ScriptInterpreterObjectSP();
1886 }
1887
1888 if (PyErr_Occurred())
1889 {
1890 PyErr_Clear();
1891 }
1892
1893 Py_XDECREF(pmeth);
1894
1895 // right now we know this function exists and is callable..
1896 PyObject* py_return = PyObject_CallMethod(implementor, callee_name, param_format, thread_id);
1897
1898 // if it fails, print the error but otherwise go on
1899 if (PyErr_Occurred())
1900 {
1901 PyErr_Print();
1902 PyErr_Clear();
1903 }
1904
1905 return MakeScriptObject(py_return);
1906}
1907
1908lldb::ScriptInterpreterObjectSP
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001909ScriptInterpreterPython::CreateSyntheticScriptedProvider (std::string class_name,
1910 lldb::ValueObjectSP valobj)
1911{
1912 if (class_name.empty())
Enrico Granata400105d2012-03-06 23:42:15 +00001913 return lldb::ScriptInterpreterObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001914
1915 if (!valobj.get())
Enrico Granata400105d2012-03-06 23:42:15 +00001916 return lldb::ScriptInterpreterObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001917
Greg Claytonb4d7fc02012-02-17 07:49:44 +00001918 ExecutionContext exe_ctx (valobj->GetExecutionContextRef());
1919 Target *target = exe_ctx.GetTargetPtr();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001920
1921 if (!target)
Enrico Granata400105d2012-03-06 23:42:15 +00001922 return lldb::ScriptInterpreterObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001923
1924 Debugger &debugger = target->GetDebugger();
1925 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
1926 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
1927
1928 if (!script_interpreter)
Enrico Granata400105d2012-03-06 23:42:15 +00001929 return lldb::ScriptInterpreterObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001930
1931 void* ret_val;
Enrico Granatafa1f6172011-10-24 17:22:21 +00001932
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001933 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00001934 Locker py_lock(this);
Enrico Granatadba1de82012-03-27 02:35:13 +00001935 ForceDisableSyntheticChildren no_synthetics(target);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001936 ret_val = g_swig_synthetic_script (class_name,
1937 python_interpreter->m_dictionary_name.c_str(),
1938 valobj);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001939 }
1940
Enrico Granata400105d2012-03-06 23:42:15 +00001941 return MakeScriptObject(ret_val);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00001942}
1943
Enrico Granataf7a9b142011-07-15 02:26:42 +00001944bool
Enrico Granata400105d2012-03-06 23:42:15 +00001945ScriptInterpreterPython::GenerateTypeScriptFunction (const char* oneliner, std::string& output, void* name_token)
Enrico Granataf7a9b142011-07-15 02:26:42 +00001946{
Enrico Granata16376ed2012-02-15 02:34:21 +00001947 StringList input;
1948 input.SplitIntoLines(oneliner, strlen(oneliner));
1949 return GenerateTypeScriptFunction(input, output, name_token);
Enrico Granataf7a9b142011-07-15 02:26:42 +00001950}
1951
Chris Lattner24943d22010-06-08 16:52:24 +00001952bool
Enrico Granata400105d2012-03-06 23:42:15 +00001953ScriptInterpreterPython::GenerateTypeSynthClass (const char* oneliner, std::string& output, void* name_token)
Enrico Granata16376ed2012-02-15 02:34:21 +00001954{
1955 StringList input;
1956 input.SplitIntoLines(oneliner, strlen(oneliner));
1957 return GenerateTypeSynthClass(input, output, name_token);
1958}
1959
1960
1961bool
Enrico Granata400105d2012-03-06 23:42:15 +00001962ScriptInterpreterPython::GenerateBreakpointCommandCallbackData (StringList &user_input, std::string& output)
Chris Lattner24943d22010-06-08 16:52:24 +00001963{
Enrico Granata400105d2012-03-06 23:42:15 +00001964 static uint32_t num_created_functions = 0;
Chris Lattner24943d22010-06-08 16:52:24 +00001965 user_input.RemoveBlankLines ();
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001966 StreamString sstr;
Chris Lattner24943d22010-06-08 16:52:24 +00001967
Caroline Ticec4f55fe2010-11-19 20:47:54 +00001968 if (user_input.GetSize() == 0)
1969 return false;
1970
Enrico Granata400105d2012-03-06 23:42:15 +00001971 std::string auto_generated_function_name(GenerateUniqueName("lldb_autogen_python_bp_callback_func_",num_created_functions));
Enrico Granatac1ca9dc2012-08-08 02:06:30 +00001972 sstr.Printf ("def %s (frame, bp_loc, internal_dict):", auto_generated_function_name.c_str());
Caroline Tice0aa2e552011-01-14 00:29:16 +00001973
Enrico Granata400105d2012-03-06 23:42:15 +00001974 if (!GenerateFunction(sstr.GetData(), user_input))
Caroline Ticeb447e842010-09-21 19:25:28 +00001975 return false;
Enrico Granata400105d2012-03-06 23:42:15 +00001976
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001977 // Store the name of the auto-generated function to be called.
Enrico Granata400105d2012-03-06 23:42:15 +00001978 output.assign(auto_generated_function_name);
Caroline Tice59c5d5d2010-09-27 18:00:20 +00001979 return true;
Chris Lattner24943d22010-06-08 16:52:24 +00001980}
1981
Enrico Granata1328b142012-02-29 03:28:49 +00001982bool
Johnny Chenf3ec4612012-08-09 23:09:42 +00001983ScriptInterpreterPython::GenerateWatchpointCommandCallbackData (StringList &user_input, std::string& output)
1984{
1985 static uint32_t num_created_functions = 0;
1986 user_input.RemoveBlankLines ();
1987 StreamString sstr;
1988
1989 if (user_input.GetSize() == 0)
1990 return false;
1991
1992 std::string auto_generated_function_name(GenerateUniqueName("lldb_autogen_python_wp_callback_func_",num_created_functions));
1993 sstr.Printf ("def %s (frame, wp, internal_dict):", auto_generated_function_name.c_str());
1994
1995 if (!GenerateFunction(sstr.GetData(), user_input))
1996 return false;
1997
1998 // Store the name of the auto-generated function to be called.
1999 output.assign(auto_generated_function_name);
2000 return true;
2001}
2002
2003bool
Enrico Granata1328b142012-02-29 03:28:49 +00002004ScriptInterpreterPython::GetScriptedSummary (const char *python_function_name,
2005 lldb::ValueObjectSP valobj,
2006 lldb::ScriptInterpreterObjectSP& callee_wrapper_sp,
2007 std::string& retval)
Enrico Granataf7a9b142011-07-15 02:26:42 +00002008{
2009
Enrico Granata1328b142012-02-29 03:28:49 +00002010 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
Enrico Granataf7a9b142011-07-15 02:26:42 +00002011
2012 if (!valobj.get())
Enrico Granata1328b142012-02-29 03:28:49 +00002013 {
2014 retval.assign("<no object>");
2015 return false;
2016 }
Enrico Granataf7a9b142011-07-15 02:26:42 +00002017
Enrico Granata1328b142012-02-29 03:28:49 +00002018 void* old_callee = (callee_wrapper_sp ? callee_wrapper_sp->GetObject() : NULL);
2019 void* new_callee = old_callee;
Enrico Granataf7a9b142011-07-15 02:26:42 +00002020
Enrico Granata1328b142012-02-29 03:28:49 +00002021 bool ret_val;
Enrico Granataf7a9b142011-07-15 02:26:42 +00002022 if (python_function_name
2023 && *python_function_name)
2024 {
Enrico Granataf7a9b142011-07-15 02:26:42 +00002025 {
Enrico Granata1328b142012-02-29 03:28:49 +00002026 Locker py_lock(this);
2027 {
2028 Timer scoped_timer ("g_swig_typescript_callback","g_swig_typescript_callback");
2029 ret_val = g_swig_typescript_callback (python_function_name,
2030 FindSessionDictionary(m_dictionary_name.c_str()),
2031 valobj,
2032 &new_callee,
2033 retval);
2034 }
Enrico Granataf7a9b142011-07-15 02:26:42 +00002035 }
2036 }
2037 else
Enrico Granata1328b142012-02-29 03:28:49 +00002038 {
2039 retval.assign("<no function name>");
2040 return false;
2041 }
2042
2043 if (new_callee && old_callee != new_callee)
2044 callee_wrapper_sp = MakeScriptObject(new_callee);
Enrico Granataf7a9b142011-07-15 02:26:42 +00002045
2046 return ret_val;
2047
2048}
2049
Greg Clayton5144f382010-10-07 17:14:24 +00002050bool
2051ScriptInterpreterPython::BreakpointCallbackFunction
2052(
2053 void *baton,
2054 StoppointCallbackContext *context,
2055 user_id_t break_id,
2056 user_id_t break_loc_id
2057)
2058{
2059 BreakpointOptions::CommandData *bp_option_data = (BreakpointOptions::CommandData *) baton;
Enrico Granata400105d2012-03-06 23:42:15 +00002060 const char *python_function_name = bp_option_data->script_source.c_str();
Caroline Tice0aa2e552011-01-14 00:29:16 +00002061
2062 if (!context)
2063 return true;
2064
Greg Claytonf4124de2012-02-21 00:09:25 +00002065 ExecutionContext exe_ctx (context->exe_ctx_ref);
2066 Target *target = exe_ctx.GetTargetPtr();
Caroline Tice0aa2e552011-01-14 00:29:16 +00002067
2068 if (!target)
2069 return true;
2070
2071 Debugger &debugger = target->GetDebugger();
2072 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
2073 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
2074
2075 if (!script_interpreter)
2076 return true;
Greg Clayton5144f382010-10-07 17:14:24 +00002077
2078 if (python_function_name != NULL
2079 && python_function_name[0] != '\0')
2080 {
Greg Claytonf4124de2012-02-21 00:09:25 +00002081 const StackFrameSP stop_frame_sp (exe_ctx.GetFrameSP());
Greg Clayton5144f382010-10-07 17:14:24 +00002082 BreakpointSP breakpoint_sp = target->GetBreakpointByID (break_id);
Greg Claytone86cbb92011-03-22 01:14:58 +00002083 if (breakpoint_sp)
Caroline Tice0aa2e552011-01-14 00:29:16 +00002084 {
Greg Claytone86cbb92011-03-22 01:14:58 +00002085 const BreakpointLocationSP bp_loc_sp (breakpoint_sp->FindLocationByID (break_loc_id));
2086
2087 if (stop_frame_sp && bp_loc_sp)
Caroline Tice202f6b82011-01-17 21:55:19 +00002088 {
Greg Claytone86cbb92011-03-22 01:14:58 +00002089 bool ret_val = true;
Greg Claytone86cbb92011-03-22 01:14:58 +00002090 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00002091 Locker py_lock(python_interpreter);
Greg Claytone86cbb92011-03-22 01:14:58 +00002092 ret_val = g_swig_breakpoint_callback (python_function_name,
2093 python_interpreter->m_dictionary_name.c_str(),
2094 stop_frame_sp,
2095 bp_loc_sp);
Greg Claytone86cbb92011-03-22 01:14:58 +00002096 }
2097 return ret_val;
Caroline Tice202f6b82011-01-17 21:55:19 +00002098 }
Caroline Tice0aa2e552011-01-14 00:29:16 +00002099 }
Greg Clayton5144f382010-10-07 17:14:24 +00002100 }
2101 // We currently always true so we stop in case anything goes wrong when
2102 // trying to call the script function
2103 return true;
2104}
Caroline Tice2ade6112010-11-10 19:18:14 +00002105
Johnny Chenf3ec4612012-08-09 23:09:42 +00002106bool
2107ScriptInterpreterPython::WatchpointCallbackFunction
2108(
2109 void *baton,
2110 StoppointCallbackContext *context,
2111 user_id_t watch_id
2112)
2113{
2114 WatchpointOptions::CommandData *wp_option_data = (WatchpointOptions::CommandData *) baton;
2115 const char *python_function_name = wp_option_data->script_source.c_str();
2116
2117 if (!context)
2118 return true;
2119
2120 ExecutionContext exe_ctx (context->exe_ctx_ref);
2121 Target *target = exe_ctx.GetTargetPtr();
2122
2123 if (!target)
2124 return true;
2125
2126 Debugger &debugger = target->GetDebugger();
2127 ScriptInterpreter *script_interpreter = debugger.GetCommandInterpreter().GetScriptInterpreter();
2128 ScriptInterpreterPython *python_interpreter = (ScriptInterpreterPython *) script_interpreter;
2129
2130 if (!script_interpreter)
2131 return true;
2132
2133 if (python_function_name != NULL
2134 && python_function_name[0] != '\0')
2135 {
2136 const StackFrameSP stop_frame_sp (exe_ctx.GetFrameSP());
2137 WatchpointSP wp_sp = target->GetWatchpointList().FindByID (watch_id);
2138 if (wp_sp)
2139 {
2140 if (stop_frame_sp && wp_sp)
2141 {
2142 bool ret_val = true;
2143 {
2144 Locker py_lock(python_interpreter);
2145 ret_val = g_swig_watchpoint_callback (python_function_name,
2146 python_interpreter->m_dictionary_name.c_str(),
2147 stop_frame_sp,
2148 wp_sp);
2149 }
2150 return ret_val;
2151 }
2152 }
2153 }
2154 // We currently always true so we stop in case anything goes wrong when
2155 // trying to call the script function
2156 return true;
2157}
2158
Caroline Tice2ade6112010-11-10 19:18:14 +00002159lldb::thread_result_t
2160ScriptInterpreterPython::RunEmbeddedPythonInterpreter (lldb::thread_arg_t baton)
2161{
2162 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
2163
2164 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT));
2165
2166 if (log)
2167 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread starting...", baton);
2168
2169 char error_str[1024];
2170 const char *pty_slave_name = script_interpreter->m_embedded_python_pty.GetSlaveName (error_str, sizeof (error_str));
Caroline Tice0aa2e552011-01-14 00:29:16 +00002171
Enrico Granatafa1f6172011-10-24 17:22:21 +00002172 if (pty_slave_name != NULL)
Caroline Tice202f6b82011-01-17 21:55:19 +00002173 {
Caroline Tice2ade6112010-11-10 19:18:14 +00002174 StreamString run_string;
Johnny Chen8165d432012-08-18 04:14:54 +00002175
2176 // Ensure we have the GIL before running any Python code.
2177 // Since we're only running a few one-liners and then dropping to the interpreter (which will release the GIL when needed),
2178 // we can just release the GIL after finishing our work.
2179 // If finer-grained locking is desirable, we can lock and unlock the GIL only when calling a python function.
2180 Locker locker(script_interpreter,
2181 ScriptInterpreterPython::Locker::AcquireLock | ScriptInterpreterPython::Locker::InitSession,
2182 ScriptInterpreterPython::Locker::FreeAcquiredLock | ScriptInterpreterPython::Locker::TearDownSession);
2183
Caroline Tice0aa2e552011-01-14 00:29:16 +00002184 run_string.Printf ("run_one_line (%s, 'save_stderr = sys.stderr')", script_interpreter->m_dictionary_name.c_str());
2185 PyRun_SimpleString (run_string.GetData());
2186 run_string.Clear ();
2187
2188 run_string.Printf ("run_one_line (%s, 'sys.stderr = sys.stdout')", script_interpreter->m_dictionary_name.c_str());
2189 PyRun_SimpleString (run_string.GetData());
2190 run_string.Clear ();
2191
2192 run_string.Printf ("run_one_line (%s, 'save_stdin = sys.stdin')", script_interpreter->m_dictionary_name.c_str());
2193 PyRun_SimpleString (run_string.GetData());
2194 run_string.Clear ();
2195
2196 run_string.Printf ("run_one_line (%s, \"sys.stdin = open ('%s', 'r')\")", script_interpreter->m_dictionary_name.c_str(),
2197 pty_slave_name);
2198 PyRun_SimpleString (run_string.GetData());
2199 run_string.Clear ();
2200
Johnny Chen8054ba32011-03-11 00:28:50 +00002201 // The following call drops into the embedded interpreter loop and stays there until the
2202 // user chooses to exit from the Python interpreter.
Johnny Chen8165d432012-08-18 04:14:54 +00002203 // This embedded interpreter will, as any Python code that performs I/O, unlock the GIL before
2204 // a system call that can hang, and lock it when the syscall has returned.
Caroline Tice0aa2e552011-01-14 00:29:16 +00002205
Johnny Chen8165d432012-08-18 04:14:54 +00002206 // We need to surround the call to the embedded interpreter with calls to PyGILState_Ensure and
2207 // PyGILState_Release (using the Locker above). This is because Python has a global lock which must be held whenever we want
2208 // to touch any Python objects. Otherwise, if the user calls Python code, the interpreter state will be off,
2209 // and things could hang (it's happened before).
Caroline Ticece207c12011-03-11 00:21:55 +00002210
Caroline Tice0aa2e552011-01-14 00:29:16 +00002211 run_string.Printf ("run_python_interpreter (%s)", script_interpreter->m_dictionary_name.c_str());
2212 PyRun_SimpleString (run_string.GetData());
2213 run_string.Clear ();
Johnny Chen8165d432012-08-18 04:14:54 +00002214
Caroline Tice0aa2e552011-01-14 00:29:16 +00002215 run_string.Printf ("run_one_line (%s, 'sys.stdin = save_stdin')", script_interpreter->m_dictionary_name.c_str());
2216 PyRun_SimpleString (run_string.GetData());
2217 run_string.Clear();
Johnny Chen8165d432012-08-18 04:14:54 +00002218
Caroline Tice0aa2e552011-01-14 00:29:16 +00002219 run_string.Printf ("run_one_line (%s, 'sys.stderr = save_stderr')", script_interpreter->m_dictionary_name.c_str());
2220 PyRun_SimpleString (run_string.GetData());
2221 run_string.Clear();
Caroline Tice2ade6112010-11-10 19:18:14 +00002222 }
2223
Johnny Chen8121d7a2012-08-17 23:44:35 +00002224 if (script_interpreter->m_embedded_python_input_reader_sp)
2225 script_interpreter->m_embedded_python_input_reader_sp->SetIsDone (true);
Caroline Tice2ade6112010-11-10 19:18:14 +00002226
2227 script_interpreter->m_embedded_python_pty.CloseSlaveFileDescriptor();
Caroline Tice0aa2e552011-01-14 00:29:16 +00002228
Caroline Tice2ade6112010-11-10 19:18:14 +00002229 log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT);
2230 if (log)
2231 log->Printf ("%p ScriptInterpreterPython::RunEmbeddedPythonInterpreter () thread exiting...", baton);
2232
2233
Johnny Chen8054ba32011-03-11 00:28:50 +00002234 // Clean up the input reader and make the debugger pop it off the stack.
Caroline Tice0aa2e552011-01-14 00:29:16 +00002235 Debugger &debugger = script_interpreter->GetCommandInterpreter().GetDebugger();
Johnny Chen8121d7a2012-08-17 23:44:35 +00002236 const InputReaderSP reader_sp = script_interpreter->m_embedded_python_input_reader_sp;
2237 if (reader_sp)
2238 {
2239 debugger.PopInputReader (reader_sp);
2240 script_interpreter->m_embedded_python_input_reader_sp.reset();
2241 }
Caroline Tice0aa2e552011-01-14 00:29:16 +00002242
Caroline Tice2ade6112010-11-10 19:18:14 +00002243 return NULL;
2244}
2245
Enrico Granataa1ba3142012-06-07 00:17:18 +00002246lldb::thread_result_t
2247ScriptInterpreterPython::PythonInputReaderManager::RunPythonInputReader (lldb::thread_arg_t baton)
2248{
2249 ScriptInterpreterPython *script_interpreter = (ScriptInterpreterPython *) baton;
2250
2251 const InputReaderSP reader_sp = script_interpreter->m_embedded_thread_input_reader_sp;
2252
2253 if (reader_sp)
2254 reader_sp->WaitOnReaderIsDone();
2255
2256 return NULL;
2257}
2258
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002259uint32_t
Enrico Granata400105d2012-03-06 23:42:15 +00002260ScriptInterpreterPython::CalculateNumChildren (const lldb::ScriptInterpreterObjectSP& implementor_sp)
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002261{
Enrico Granata400105d2012-03-06 23:42:15 +00002262 if (!implementor_sp)
2263 return 0;
2264
2265 void* implementor = implementor_sp->GetObject();
2266
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002267 if (!implementor)
2268 return 0;
2269
2270 if (!g_swig_calc_children)
2271 return 0;
Enrico Granatafa1f6172011-10-24 17:22:21 +00002272
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002273 uint32_t ret_val = 0;
2274
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002275 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00002276 Locker py_lock(this);
Enrico Granatadba1de82012-03-27 02:35:13 +00002277 ForceDisableSyntheticChildren no_synthetics(GetCommandInterpreter().GetDebugger().GetSelectedTarget().get());
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002278 ret_val = g_swig_calc_children (implementor);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002279 }
2280
2281 return ret_val;
2282}
2283
Enrico Granata91544802011-09-06 19:20:51 +00002284lldb::ValueObjectSP
Enrico Granata400105d2012-03-06 23:42:15 +00002285ScriptInterpreterPython::GetChildAtIndex (const lldb::ScriptInterpreterObjectSP& implementor_sp, uint32_t idx)
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002286{
Enrico Granata400105d2012-03-06 23:42:15 +00002287 if (!implementor_sp)
2288 return lldb::ValueObjectSP();
2289
2290 void* implementor = implementor_sp->GetObject();
2291
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002292 if (!implementor)
Enrico Granata91544802011-09-06 19:20:51 +00002293 return lldb::ValueObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002294
Enrico Granata91544802011-09-06 19:20:51 +00002295 if (!g_swig_get_child_index || !g_swig_cast_to_sbvalue)
2296 return lldb::ValueObjectSP();
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002297
Enrico Granata91544802011-09-06 19:20:51 +00002298 void* child_ptr = NULL;
2299 lldb::SBValue* value_sb = NULL;
2300 lldb::ValueObjectSP ret_val;
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002301
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002302 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00002303 Locker py_lock(this);
Enrico Granatadba1de82012-03-27 02:35:13 +00002304 ForceDisableSyntheticChildren no_synthetics(GetCommandInterpreter().GetDebugger().GetSelectedTarget().get());
Enrico Granata91544802011-09-06 19:20:51 +00002305 child_ptr = g_swig_get_child_index (implementor,idx);
2306 if (child_ptr != NULL && child_ptr != Py_None)
2307 {
2308 value_sb = (lldb::SBValue*)g_swig_cast_to_sbvalue(child_ptr);
2309 if (value_sb == NULL)
2310 Py_XDECREF(child_ptr);
2311 else
2312 ret_val = value_sb->get_sp();
2313 }
2314 else
2315 {
2316 Py_XDECREF(child_ptr);
2317 }
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002318 }
2319
2320 return ret_val;
2321}
2322
2323int
Enrico Granata400105d2012-03-06 23:42:15 +00002324ScriptInterpreterPython::GetIndexOfChildWithName (const lldb::ScriptInterpreterObjectSP& implementor_sp, const char* child_name)
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002325{
Enrico Granata400105d2012-03-06 23:42:15 +00002326 if (!implementor_sp)
2327 return UINT32_MAX;
2328
2329 void* implementor = implementor_sp->GetObject();
2330
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002331 if (!implementor)
2332 return UINT32_MAX;
2333
2334 if (!g_swig_get_index_child)
2335 return UINT32_MAX;
2336
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002337 int ret_val = UINT32_MAX;
2338
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002339 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00002340 Locker py_lock(this);
Enrico Granatadba1de82012-03-27 02:35:13 +00002341 ForceDisableSyntheticChildren no_synthetics(GetCommandInterpreter().GetDebugger().GetSelectedTarget().get());
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002342 ret_val = g_swig_get_index_child (implementor, child_name);
Enrico Granata9ae7cef2011-07-24 00:14:56 +00002343 }
2344
2345 return ret_val;
2346}
2347
Enrico Granatacf09f882012-03-19 22:58:49 +00002348bool
Enrico Granata400105d2012-03-06 23:42:15 +00002349ScriptInterpreterPython::UpdateSynthProviderInstance (const lldb::ScriptInterpreterObjectSP& implementor_sp)
Enrico Granata979e20d2011-07-29 19:53:35 +00002350{
Enrico Granatacf09f882012-03-19 22:58:49 +00002351 bool ret_val = false;
2352
Enrico Granata400105d2012-03-06 23:42:15 +00002353 if (!implementor_sp)
Enrico Granatacf09f882012-03-19 22:58:49 +00002354 return ret_val;
Enrico Granata400105d2012-03-06 23:42:15 +00002355
2356 void* implementor = implementor_sp->GetObject();
2357
Enrico Granata979e20d2011-07-29 19:53:35 +00002358 if (!implementor)
Enrico Granatacf09f882012-03-19 22:58:49 +00002359 return ret_val;
Enrico Granata979e20d2011-07-29 19:53:35 +00002360
2361 if (!g_swig_update_provider)
Enrico Granatacf09f882012-03-19 22:58:49 +00002362 return ret_val;
Enrico Granata979e20d2011-07-29 19:53:35 +00002363
Enrico Granata979e20d2011-07-29 19:53:35 +00002364 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00002365 Locker py_lock(this);
Enrico Granatadba1de82012-03-27 02:35:13 +00002366 ForceDisableSyntheticChildren no_synthetics(GetCommandInterpreter().GetDebugger().GetSelectedTarget().get());
Enrico Granatacf09f882012-03-19 22:58:49 +00002367 ret_val = g_swig_update_provider (implementor);
Enrico Granata979e20d2011-07-29 19:53:35 +00002368 }
2369
Enrico Granatacf09f882012-03-19 22:58:49 +00002370 return ret_val;
Enrico Granata979e20d2011-07-29 19:53:35 +00002371}
2372
Enrico Granatac2a28252011-08-16 16:49:25 +00002373bool
Enrico Granata59df36f2011-10-17 21:45:27 +00002374ScriptInterpreterPython::LoadScriptingModule (const char* pathname,
Enrico Granata6010ace2011-11-07 22:57:04 +00002375 bool can_reload,
Enrico Granata59df36f2011-10-17 21:45:27 +00002376 lldb_private::Error& error)
2377{
2378 if (!pathname || !pathname[0])
2379 {
2380 error.SetErrorString("invalid pathname");
2381 return false;
2382 }
2383
2384 if (!g_swig_call_module_init)
2385 {
2386 error.SetErrorString("internal helper function missing");
2387 return false;
2388 }
2389
Greg Clayton13d24fb2012-01-29 20:56:30 +00002390 lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().shared_from_this();
Enrico Granatafa1f6172011-10-24 17:22:21 +00002391
Enrico Granata59df36f2011-10-17 21:45:27 +00002392 {
Enrico Granata59df36f2011-10-17 21:45:27 +00002393 FileSpec target_file(pathname, true);
2394
2395 // TODO: would we want to reject any other value?
2396 if (target_file.GetFileType() == FileSpec::eFileTypeInvalid ||
2397 target_file.GetFileType() == FileSpec::eFileTypeUnknown)
2398 {
2399 error.SetErrorString("invalid pathname");
2400 return false;
2401 }
2402
2403 const char* directory = target_file.GetDirectory().GetCString();
2404 std::string basename(target_file.GetFilename().GetCString());
Johnny Chen8165d432012-08-18 04:14:54 +00002405
2406 // Before executing Pyton code, lock the GIL.
2407 Locker py_lock(this);
Enrico Granata59df36f2011-10-17 21:45:27 +00002408
2409 // now make sure that Python has "directory" in the search path
2410 StreamString command_stream;
2411 command_stream.Printf("if not (sys.path.__contains__('%s')):\n sys.path.append('%s');\n\n",
2412 directory,
2413 directory);
Enrico Granataa1ba3142012-06-07 00:17:18 +00002414 bool syspath_retval = ExecuteMultipleLines(command_stream.GetData(), false);
Enrico Granata59df36f2011-10-17 21:45:27 +00002415 if (!syspath_retval)
2416 {
2417 error.SetErrorString("Python sys.path handling failed");
2418 return false;
2419 }
2420
2421 // strip .py or .pyc extension
2422 ConstString extension = target_file.GetFileNameExtension();
2423 if (::strcmp(extension.GetCString(), "py") == 0)
2424 basename.resize(basename.length()-3);
2425 else if(::strcmp(extension.GetCString(), "pyc") == 0)
2426 basename.resize(basename.length()-4);
2427
2428 // check if the module is already import-ed
2429 command_stream.Clear();
2430 command_stream.Printf("sys.getrefcount(%s)",basename.c_str());
2431 int refcount = 0;
2432 // this call will fail if the module does not exist (because the parameter to it is not a string
2433 // but an actual Python module object, which is non-existant if the module was not imported before)
Enrico Granata6010ace2011-11-07 22:57:04 +00002434 bool was_imported = (ExecuteOneLineWithReturn(command_stream.GetData(),
Enrico Granataa1ba3142012-06-07 00:17:18 +00002435 ScriptInterpreterPython::eScriptReturnTypeInt, &refcount, false) && refcount > 0);
Enrico Granata6010ace2011-11-07 22:57:04 +00002436 if (was_imported == true && can_reload == false)
Enrico Granata59df36f2011-10-17 21:45:27 +00002437 {
2438 error.SetErrorString("module already imported");
2439 return false;
2440 }
2441
2442 // now actually do the import
2443 command_stream.Clear();
2444 command_stream.Printf("import %s",basename.c_str());
Enrico Granataa1ba3142012-06-07 00:17:18 +00002445 bool import_retval = ExecuteOneLine(command_stream.GetData(), NULL, false);
Enrico Granata59df36f2011-10-17 21:45:27 +00002446 if (!import_retval)
2447 {
2448 error.SetErrorString("Python import statement failed");
2449 return false;
2450 }
2451
Enrico Granata16376ed2012-02-15 02:34:21 +00002452 // call __lldb_init_module(debugger,dict)
Enrico Granata59df36f2011-10-17 21:45:27 +00002453 if (!g_swig_call_module_init (basename,
Enrico Granatafa1f6172011-10-24 17:22:21 +00002454 m_dictionary_name.c_str(),
Enrico Granata59df36f2011-10-17 21:45:27 +00002455 debugger_sp))
2456 {
Enrico Granata16376ed2012-02-15 02:34:21 +00002457 error.SetErrorString("calling __lldb_init_module failed");
Enrico Granata59df36f2011-10-17 21:45:27 +00002458 return false;
2459 }
2460 return true;
2461 }
2462}
2463
Enrico Granata1328b142012-02-29 03:28:49 +00002464lldb::ScriptInterpreterObjectSP
2465ScriptInterpreterPython::MakeScriptObject (void* object)
2466{
2467 return lldb::ScriptInterpreterObjectSP(new ScriptInterpreterPythonObject(object));
2468}
2469
Enrico Granata6010ace2011-11-07 22:57:04 +00002470ScriptInterpreterPython::SynchronicityHandler::SynchronicityHandler (lldb::DebuggerSP debugger_sp,
2471 ScriptedCommandSynchronicity synchro) :
2472 m_debugger_sp(debugger_sp),
2473 m_synch_wanted(synchro),
2474 m_old_asynch(debugger_sp->GetAsyncExecution())
2475{
2476 if (m_synch_wanted == eScriptedCommandSynchronicitySynchronous)
2477 m_debugger_sp->SetAsyncExecution(false);
2478 else if (m_synch_wanted == eScriptedCommandSynchronicityAsynchronous)
2479 m_debugger_sp->SetAsyncExecution(true);
2480}
2481
2482ScriptInterpreterPython::SynchronicityHandler::~SynchronicityHandler()
2483{
2484 if (m_synch_wanted != eScriptedCommandSynchronicityCurrentValue)
2485 m_debugger_sp->SetAsyncExecution(m_old_asynch);
2486}
2487
Enrico Granata59df36f2011-10-17 21:45:27 +00002488bool
Enrico Granatac2a28252011-08-16 16:49:25 +00002489ScriptInterpreterPython::RunScriptBasedCommand(const char* impl_function,
2490 const char* args,
Enrico Granata6010ace2011-11-07 22:57:04 +00002491 ScriptedCommandSynchronicity synchronicity,
Enrico Granata6b1596d2011-08-16 23:24:13 +00002492 lldb_private::CommandReturnObject& cmd_retobj,
Enrico Granatac2a28252011-08-16 16:49:25 +00002493 Error& error)
2494{
2495 if (!impl_function)
2496 {
2497 error.SetErrorString("no function to execute");
2498 return false;
2499 }
2500
2501 if (!g_swig_call_command)
2502 {
2503 error.SetErrorString("no helper function to run scripted commands");
2504 return false;
2505 }
2506
Greg Clayton13d24fb2012-01-29 20:56:30 +00002507 lldb::DebuggerSP debugger_sp = m_interpreter.GetDebugger().shared_from_this();
Enrico Granata6010ace2011-11-07 22:57:04 +00002508
2509 if (!debugger_sp.get())
2510 {
2511 error.SetErrorString("invalid Debugger pointer");
2512 return false;
2513 }
Enrico Granatac2a28252011-08-16 16:49:25 +00002514
2515 bool ret_val;
2516
2517 std::string err_msg;
Enrico Granata6010ace2011-11-07 22:57:04 +00002518
Enrico Granatac2a28252011-08-16 16:49:25 +00002519 {
Enrico Granatafa1f6172011-10-24 17:22:21 +00002520 Locker py_lock(this);
Enrico Granata6010ace2011-11-07 22:57:04 +00002521 SynchronicityHandler synch_handler(debugger_sp,
2522 synchronicity);
2523
Enrico Granataa1ba3142012-06-07 00:17:18 +00002524 PythonInputReaderManager py_input(this);
2525
Enrico Granatac2a28252011-08-16 16:49:25 +00002526 ret_val = g_swig_call_command (impl_function,
Enrico Granatafa1f6172011-10-24 17:22:21 +00002527 m_dictionary_name.c_str(),
Enrico Granatac2a28252011-08-16 16:49:25 +00002528 debugger_sp,
2529 args,
2530 err_msg,
Enrico Granata3370f0c2011-08-19 23:56:34 +00002531 cmd_retobj);
Enrico Granatac2a28252011-08-16 16:49:25 +00002532 }
Enrico Granata6010ace2011-11-07 22:57:04 +00002533
Enrico Granatac2a28252011-08-16 16:49:25 +00002534 if (!ret_val)
2535 error.SetErrorString(err_msg.c_str());
2536 else
2537 error.Clear();
Enrico Granata6010ace2011-11-07 22:57:04 +00002538
Enrico Granatac2a28252011-08-16 16:49:25 +00002539 return ret_val;
Enrico Granatac2a28252011-08-16 16:49:25 +00002540}
2541
Enrico Granatae5e34cb2011-08-17 01:30:04 +00002542// in Python, a special attribute __doc__ contains the docstring
2543// for an object (function, method, class, ...) if any is defined
2544// Otherwise, the attribute's value is None
2545std::string
2546ScriptInterpreterPython::GetDocumentationForItem(const char* item)
2547{
2548 std::string command(item);
2549 command += ".__doc__";
2550
2551 char* result_ptr = NULL; // Python is going to point this to valid data if ExecuteOneLineWithReturn returns successfully
2552
2553 if (ExecuteOneLineWithReturn (command.c_str(),
Enrico Granata59df36f2011-10-17 21:45:27 +00002554 ScriptInterpreter::eScriptReturnTypeCharStrOrNone,
Enrico Granataa1ba3142012-06-07 00:17:18 +00002555 &result_ptr, false) && result_ptr)
Enrico Granatae5e34cb2011-08-17 01:30:04 +00002556 {
2557 return std::string(result_ptr);
2558 }
2559 else
2560 return std::string("");
2561}
Caroline Tice2ade6112010-11-10 19:18:14 +00002562
Caroline Tice0aa2e552011-01-14 00:29:16 +00002563void
Enrico Granata1328b142012-02-29 03:28:49 +00002564ScriptInterpreterPython::InitializeInterpreter (SWIGInitCallback python_swig_init_callback)
Greg Claytone86cbb92011-03-22 01:14:58 +00002565{
2566 g_swig_init_callback = python_swig_init_callback;
Enrico Granata1328b142012-02-29 03:28:49 +00002567 g_swig_breakpoint_callback = LLDBSwigPythonBreakpointCallbackFunction;
Johnny Chenf3ec4612012-08-09 23:09:42 +00002568 g_swig_watchpoint_callback = LLDBSwigPythonWatchpointCallbackFunction;
Enrico Granata1328b142012-02-29 03:28:49 +00002569 g_swig_typescript_callback = LLDBSwigPythonCallTypeScript;
2570 g_swig_synthetic_script = LLDBSwigPythonCreateSyntheticProvider;
2571 g_swig_calc_children = LLDBSwigPython_CalculateNumChildren;
2572 g_swig_get_child_index = LLDBSwigPython_GetChildAtIndex;
2573 g_swig_get_index_child = LLDBSwigPython_GetIndexOfChildWithName;
2574 g_swig_cast_to_sbvalue = LLDBSWIGPython_CastPyObjectToSBValue;
2575 g_swig_update_provider = LLDBSwigPython_UpdateSynthProviderInstance;
2576 g_swig_call_command = LLDBSwigPythonCallCommand;
2577 g_swig_call_module_init = LLDBSwigPythonCallModuleInit;
Enrico Granata155ee912012-08-24 00:30:47 +00002578 g_swig_create_os_plugin = LLDBSWIGPythonCreateOSPlugin;
Greg Claytone86cbb92011-03-22 01:14:58 +00002579}
2580
2581void
2582ScriptInterpreterPython::InitializePrivate ()
Caroline Tice0aa2e552011-01-14 00:29:16 +00002583{
Caroline Tice0aa2e552011-01-14 00:29:16 +00002584 Timer scoped_timer (__PRETTY_FUNCTION__, __PRETTY_FUNCTION__);
2585
Greg Clayton0fdd4a02011-02-07 23:24:47 +00002586 // Python will muck with STDIN terminal state, so save off any current TTY
2587 // settings so we can restore them.
2588 TerminalState stdin_tty_state;
2589 stdin_tty_state.Save(STDIN_FILENO, false);
Caroline Tice0aa2e552011-01-14 00:29:16 +00002590
Johnny Chen8165d432012-08-18 04:14:54 +00002591 PyGILState_STATE gstate;
2592 LogSP log (lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_SCRIPT | LIBLLDB_LOG_VERBOSE));
2593 bool threads_already_initialized = false;
2594 if (PyEval_ThreadsInitialized ()) {
2595 gstate = PyGILState_Ensure ();
2596 if (log)
2597 log->Printf("Ensured PyGILState. Previous state = %slocked\n", gstate == PyGILState_UNLOCKED ? "un" : "");
2598 threads_already_initialized = true;
2599 } else {
2600 // InitThreads acquires the GIL if it hasn't been called before.
2601 PyEval_InitThreads ();
2602 }
Caroline Ticea54461d2011-06-02 22:09:43 +00002603 Py_InitializeEx (0);
Caroline Tice0aa2e552011-01-14 00:29:16 +00002604
Greg Claytone86cbb92011-03-22 01:14:58 +00002605 // Initialize SWIG after setting up python
2606 assert (g_swig_init_callback != NULL);
2607 g_swig_init_callback ();
Caroline Tice0aa2e552011-01-14 00:29:16 +00002608
2609 // Update the path python uses to search for modules to include the current directory.
2610
Caroline Ticed4d92832011-06-13 21:33:00 +00002611 PyRun_SimpleString ("import sys");
2612 PyRun_SimpleString ("sys.path.append ('.')");
Jim Ingham2a19ef92011-08-27 01:24:08 +00002613
2614 // Find the module that owns this code and use that path we get to
2615 // set the sys.path appropriately.
2616
2617 FileSpec file_spec;
2618 char python_dir_path[PATH_MAX];
2619 if (Host::GetLLDBPath (ePathTypePythonDir, file_spec))
2620 {
2621 std::string python_path("sys.path.insert(0,\"");
2622 size_t orig_len = python_path.length();
2623 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
2624 {
2625 python_path.append (python_dir_path);
2626 python_path.append ("\")");
2627 PyRun_SimpleString (python_path.c_str());
2628 python_path.resize (orig_len);
2629 }
2630
2631 if (Host::GetLLDBPath (ePathTypeLLDBShlibDir, file_spec))
2632 {
2633 if (file_spec.GetPath(python_dir_path, sizeof (python_dir_path)))
2634 {
2635 python_path.append (python_dir_path);
2636 python_path.append ("\")");
2637 PyRun_SimpleString (python_path.c_str());
2638 python_path.resize (orig_len);
2639 }
2640 }
2641 }
2642
Greg Clayton4e651b12012-04-25 00:58:03 +00002643 PyRun_SimpleString ("sys.dont_write_bytecode = 1; import lldb.embedded_interpreter; from lldb.embedded_interpreter import run_python_interpreter; from lldb.embedded_interpreter import run_one_line; from termios import *");
Greg Clayton99208582011-02-07 19:04:58 +00002644
Johnny Chen8165d432012-08-18 04:14:54 +00002645 if (threads_already_initialized) {
2646 if (log)
2647 log->Printf("Releasing PyGILState. Returning to state = %slocked\n", gstate == PyGILState_UNLOCKED ? "un" : "");
2648 PyGILState_Release (gstate);
2649 } else {
2650 // We initialized the threads in this function, just unlock the GIL.
2651 PyEval_SaveThread();
2652 }
2653
Greg Clayton0fdd4a02011-02-07 23:24:47 +00002654 stdin_tty_state.Restore();
Caroline Tice0aa2e552011-01-14 00:29:16 +00002655}
2656
Greg Claytone86cbb92011-03-22 01:14:58 +00002657//void
2658//ScriptInterpreterPython::Terminate ()
2659//{
2660// // We are intentionally NOT calling Py_Finalize here (this would be the logical place to call it). Calling
2661// // Py_Finalize here causes test suite runs to seg fault: The test suite runs in Python. It registers
2662// // SBDebugger::Terminate to be called 'at_exit'. When the test suite Python harness finishes up, it calls
2663// // Py_Finalize, which calls all the 'at_exit' registered functions. SBDebugger::Terminate calls Debugger::Terminate,
2664// // which calls lldb::Terminate, which calls ScriptInterpreter::Terminate, which calls
2665// // ScriptInterpreterPython::Terminate. So if we call Py_Finalize here, we end up with Py_Finalize being called from
2666// // within Py_Finalize, which results in a seg fault.
2667// //
2668// // Since this function only gets called when lldb is shutting down and going away anyway, the fact that we don't
2669// // actually call Py_Finalize should not cause any problems (everything should shut down/go away anyway when the
2670// // process exits).
2671// //
2672//// Py_Finalize ();
2673//}
Greg Clayton3e4238d2011-11-04 03:34:56 +00002674
2675#endif // #ifdef LLDB_DISABLE_PYTHON