1 //===-- ScriptInterpreterPython.h -------------------------------*- 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 #ifndef LLDB_PLUGINS_SCRIPTINTERPRETER_PYTHON_SCRIPTINTERPRETERPYTHON_H 11 #define LLDB_PLUGINS_SCRIPTINTERPRETER_PYTHON_SCRIPTINTERPRETERPYTHON_H 12 13 #ifdef LLDB_DISABLE_PYTHON 14 15 // Python is disabled in this build 16 17 #else 18 19 // C Includes 20 // C++ Includes 21 #include <memory> 22 #include <string> 23 #include <vector> 24 25 // Other libraries and framework includes 26 // Project includes 27 #include "lldb/lldb-private.h" 28 #include "PythonDataObjects.h" 29 #include "lldb/Core/IOHandler.h" 30 #include "lldb/Interpreter/ScriptInterpreter.h" 31 #include "lldb/Host/Terminal.h" 32 33 class IOHandlerPythonInterpreter; 34 35 namespace lldb_private { 36 37 class ScriptInterpreterPython : 38 public ScriptInterpreter, 39 public IOHandlerDelegateMultiline 40 { 41 public: 42 #if PY_MAJOR_VERSION >= 3 43 typedef PyObject*(*SWIGInitCallback) (void); 44 #else 45 typedef void(*SWIGInitCallback) (void); 46 #endif 47 48 typedef bool (*SWIGBreakpointCallbackFunction) (const char *python_function_name, 49 const char *session_dictionary_name, 50 const lldb::StackFrameSP& frame_sp, 51 const lldb::BreakpointLocationSP &bp_loc_sp); 52 53 typedef bool (*SWIGWatchpointCallbackFunction) (const char *python_function_name, 54 const char *session_dictionary_name, 55 const lldb::StackFrameSP& frame_sp, 56 const lldb::WatchpointSP &wp_sp); 57 58 typedef bool (*SWIGPythonTypeScriptCallbackFunction) (const char *python_function_name, 59 void *session_dictionary, 60 const lldb::ValueObjectSP& valobj_sp, 61 void** pyfunct_wrapper, 62 const lldb::TypeSummaryOptionsSP& options, 63 std::string& retval); 64 65 typedef void* (*SWIGPythonCreateSyntheticProvider) (const char *python_class_name, 66 const char *session_dictionary_name, 67 const lldb::ValueObjectSP& valobj_sp); 68 69 typedef void* (*SWIGPythonCreateCommandObject) (const char *python_class_name, 70 const char *session_dictionary_name, 71 const lldb::DebuggerSP debugger_sp); 72 73 typedef void* (*SWIGPythonCreateScriptedThreadPlan) (const char *python_class_name, 74 const char *session_dictionary_name, 75 const lldb::ThreadPlanSP& thread_plan_sp); 76 77 typedef bool (*SWIGPythonCallThreadPlan) (void *implementor, const char *method_name, Event *event_sp, bool &got_error); 78 79 typedef void* (*SWIGPythonCreateOSPlugin) (const char *python_class_name, 80 const char *session_dictionary_name, 81 const lldb::ProcessSP& process_sp); 82 83 typedef size_t (*SWIGPythonCalculateNumChildren) (void *implementor, uint32_t max); 84 85 typedef void* (*SWIGPythonGetChildAtIndex) (void *implementor, uint32_t idx); 86 87 typedef int (*SWIGPythonGetIndexOfChildWithName) (void *implementor, const char* child_name); 88 89 typedef void* (*SWIGPythonCastPyObjectToSBValue) (void* data); 90 91 typedef lldb::ValueObjectSP (*SWIGPythonGetValueObjectSPFromSBValue) (void* data); 92 93 typedef bool (*SWIGPythonUpdateSynthProviderInstance) (void* data); 94 95 typedef bool (*SWIGPythonMightHaveChildrenSynthProviderInstance) (void* data); 96 97 typedef void* (*SWIGPythonGetValueSynthProviderInstance) (void *implementor); 98 99 typedef bool (*SWIGPythonCallCommand) (const char *python_function_name, 100 const char *session_dictionary_name, 101 lldb::DebuggerSP& debugger, 102 const char* args, 103 lldb_private::CommandReturnObject& cmd_retobj, 104 lldb::ExecutionContextRefSP exe_ctx_ref_sp); 105 106 typedef bool (*SWIGPythonCallCommandObject) (void *implementor, 107 lldb::DebuggerSP& debugger, 108 const char* args, 109 lldb_private::CommandReturnObject& cmd_retobj, 110 lldb::ExecutionContextRefSP exe_ctx_ref_sp); 111 112 typedef bool (*SWIGPythonCallModuleInit) (const char *python_module_name, 113 const char *session_dictionary_name, 114 lldb::DebuggerSP& debugger); 115 116 typedef bool (*SWIGPythonScriptKeyword_Process) (const char* python_function_name, 117 const char* session_dictionary_name, 118 lldb::ProcessSP& process, 119 std::string& output); 120 121 typedef bool (*SWIGPythonScriptKeyword_Thread) (const char* python_function_name, 122 const char* session_dictionary_name, 123 lldb::ThreadSP& thread, 124 std::string& output); 125 126 typedef bool (*SWIGPythonScriptKeyword_Target) (const char* python_function_name, 127 const char* session_dictionary_name, 128 lldb::TargetSP& target, 129 std::string& output); 130 131 typedef bool (*SWIGPythonScriptKeyword_Frame) (const char* python_function_name, 132 const char* session_dictionary_name, 133 lldb::StackFrameSP& frame, 134 std::string& output); 135 136 typedef bool (*SWIGPythonScriptKeyword_Value) (const char* python_function_name, 137 const char* session_dictionary_name, 138 lldb::ValueObjectSP& value, 139 std::string& output); 140 141 typedef void* (*SWIGPython_GetDynamicSetting) (void* module, 142 const char* setting, 143 const lldb::TargetSP& target_sp); 144 145 friend class ::IOHandlerPythonInterpreter; 146 147 ScriptInterpreterPython (CommandInterpreter &interpreter); 148 149 ~ScriptInterpreterPython() override; 150 151 bool 152 Interrupt() override; 153 154 bool 155 ExecuteOneLine (const char *command, 156 CommandReturnObject *result, 157 const ExecuteScriptOptions &options = ExecuteScriptOptions()) override; 158 159 void 160 ExecuteInterpreterLoop () override; 161 162 bool 163 ExecuteOneLineWithReturn (const char *in_string, 164 ScriptInterpreter::ScriptReturnType return_type, 165 void *ret_value, 166 const ExecuteScriptOptions &options = ExecuteScriptOptions()) override; 167 168 lldb_private::Error 169 ExecuteMultipleLines (const char *in_string, 170 const ExecuteScriptOptions &options = ExecuteScriptOptions()) override; 171 172 Error 173 ExportFunctionDefinitionToInterpreter (StringList &function_def) override; 174 175 bool 176 GenerateTypeScriptFunction(StringList &input, std::string& output, const void* name_token = nullptr) override; 177 178 bool 179 GenerateTypeSynthClass(StringList &input, std::string& output, const void* name_token = nullptr) override; 180 181 bool 182 GenerateTypeSynthClass(const char* oneliner, std::string& output, const void* name_token = nullptr) override; 183 184 // use this if the function code is just a one-liner script 185 bool 186 GenerateTypeScriptFunction(const char* oneliner, std::string& output, const void* name_token = nullptr) override; 187 188 bool 189 GenerateScriptAliasFunction (StringList &input, std::string& output) override; 190 191 StructuredData::ObjectSP CreateSyntheticScriptedProvider(const char *class_name, lldb::ValueObjectSP valobj) override; 192 193 StructuredData::GenericSP CreateScriptCommandObject (const char *class_name) override; 194 195 StructuredData::ObjectSP CreateScriptedThreadPlan(const char *class_name, lldb::ThreadPlanSP thread_plan) override; 196 197 bool ScriptedThreadPlanExplainsStop(StructuredData::ObjectSP implementor_sp, Event *event, bool &script_error) override; 198 199 bool ScriptedThreadPlanShouldStop(StructuredData::ObjectSP implementor_sp, Event *event, bool &script_error) override; 200 201 lldb::StateType ScriptedThreadPlanGetRunState(StructuredData::ObjectSP implementor_sp, bool &script_error) override; 202 203 StructuredData::GenericSP OSPlugin_CreatePluginObject(const char *class_name, lldb::ProcessSP process_sp) override; 204 205 StructuredData::DictionarySP OSPlugin_RegisterInfo(StructuredData::ObjectSP os_plugin_object_sp) override; 206 207 StructuredData::ArraySP OSPlugin_ThreadsInfo(StructuredData::ObjectSP os_plugin_object_sp) override; 208 209 StructuredData::StringSP OSPlugin_RegisterContextData(StructuredData::ObjectSP os_plugin_object_sp, lldb::tid_t thread_id) override; 210 211 StructuredData::DictionarySP OSPlugin_CreateThread(StructuredData::ObjectSP os_plugin_object_sp, lldb::tid_t tid, 212 lldb::addr_t context) override; 213 214 StructuredData::ObjectSP LoadPluginModule(const FileSpec &file_spec, lldb_private::Error &error) override; 215 216 StructuredData::DictionarySP GetDynamicSettings(StructuredData::ObjectSP plugin_module_sp, Target *target, const char *setting_name, 217 lldb_private::Error &error) override; 218 219 size_t CalculateNumChildren(const StructuredData::ObjectSP &implementor, uint32_t max) override; 220 221 lldb::ValueObjectSP GetChildAtIndex(const StructuredData::ObjectSP &implementor, uint32_t idx) override; 222 223 int GetIndexOfChildWithName(const StructuredData::ObjectSP &implementor, const char *child_name) override; 224 225 bool UpdateSynthProviderInstance(const StructuredData::ObjectSP &implementor) override; 226 227 bool MightHaveChildrenSynthProviderInstance(const StructuredData::ObjectSP &implementor) override; 228 229 lldb::ValueObjectSP GetSyntheticValue(const StructuredData::ObjectSP &implementor) override; 230 231 bool 232 RunScriptBasedCommand(const char* impl_function, 233 const char* args, 234 ScriptedCommandSynchronicity synchronicity, 235 lldb_private::CommandReturnObject& cmd_retobj, 236 Error& error, 237 const lldb_private::ExecutionContext& exe_ctx) override; 238 239 bool 240 RunScriptBasedCommand (StructuredData::GenericSP impl_obj_sp, 241 const char* args, 242 ScriptedCommandSynchronicity synchronicity, 243 lldb_private::CommandReturnObject& cmd_retobj, 244 Error& error, 245 const lldb_private::ExecutionContext& exe_ctx) override; 246 247 Error 248 GenerateFunction(const char *signature, const StringList &input) override; 249 250 Error 251 GenerateBreakpointCommandCallbackData (StringList &input, std::string& output) override; 252 253 bool 254 GenerateWatchpointCommandCallbackData (StringList &input, std::string& output) override; 255 256 // static size_t 257 // GenerateBreakpointOptionsCommandCallback (void *baton, 258 // InputReader &reader, 259 // lldb::InputReaderAction notification, 260 // const char *bytes, 261 // size_t bytes_len); 262 // 263 // static size_t 264 // GenerateWatchpointOptionsCommandCallback (void *baton, 265 // InputReader &reader, 266 // lldb::InputReaderAction notification, 267 // const char *bytes, 268 // size_t bytes_len); 269 270 static bool 271 BreakpointCallbackFunction (void *baton, 272 StoppointCallbackContext *context, 273 lldb::user_id_t break_id, 274 lldb::user_id_t break_loc_id); 275 276 static bool 277 WatchpointCallbackFunction (void *baton, 278 StoppointCallbackContext *context, 279 lldb::user_id_t watch_id); 280 281 bool GetScriptedSummary(const char *function_name, lldb::ValueObjectSP valobj, StructuredData::ObjectSP &callee_wrapper_sp, 282 const TypeSummaryOptions &options, std::string &retval) override; 283 284 void 285 Clear () override; 286 287 bool 288 GetDocumentationForItem (const char* item, std::string& dest) override; 289 290 bool 291 GetShortHelpForCommandObject(StructuredData::GenericSP cmd_obj_sp, std::string& dest) override; 292 293 uint32_t 294 GetFlagsForCommandObject (StructuredData::GenericSP cmd_obj_sp) override; 295 296 bool 297 GetLongHelpForCommandObject(StructuredData::GenericSP cmd_obj_sp, std::string& dest) override; 298 299 bool 300 CheckObjectExists (const char* name) override 301 { 302 if (!name || !name[0]) 303 return false; 304 std::string temp; 305 return GetDocumentationForItem (name,temp); 306 } 307 308 bool 309 RunScriptFormatKeyword (const char* impl_function, 310 Process* process, 311 std::string& output, 312 Error& error) override; 313 314 bool 315 RunScriptFormatKeyword (const char* impl_function, 316 Thread* thread, 317 std::string& output, 318 Error& error) override; 319 320 bool 321 RunScriptFormatKeyword (const char* impl_function, 322 Target* target, 323 std::string& output, 324 Error& error) override; 325 326 bool 327 RunScriptFormatKeyword (const char* impl_function, 328 StackFrame* frame, 329 std::string& output, 330 Error& error) override; 331 332 bool 333 RunScriptFormatKeyword (const char* impl_function, 334 ValueObject* value, 335 std::string& output, 336 Error& error) override; 337 338 bool LoadScriptingModule(const char *filename, bool can_reload, bool init_session, lldb_private::Error &error, 339 StructuredData::ObjectSP *module_sp = nullptr) override; 340 341 bool 342 IsReservedWord (const char* word) override; 343 344 std::unique_ptr<ScriptInterpreterLocker> 345 AcquireInterpreterLock () override; 346 347 void 348 CollectDataForBreakpointCommandCallback (std::vector<BreakpointOptions *> &bp_options_vec, 349 CommandReturnObject &result) override; 350 351 void 352 CollectDataForWatchpointCommandCallback (WatchpointOptions *wp_options, 353 CommandReturnObject &result) override; 354 355 /// Set the callback body text into the callback for the breakpoint. 356 Error 357 SetBreakpointCommandCallback (BreakpointOptions *bp_options, 358 const char *callback_body) override; 359 360 void 361 SetBreakpointCommandCallbackFunction (BreakpointOptions *bp_options, 362 const char *function_name) override; 363 364 /// Set a one-liner as the callback for the watchpoint. 365 void 366 SetWatchpointCommandCallback (WatchpointOptions *wp_options, 367 const char *oneliner) override; 368 369 StringList 370 ReadCommandInputFromUser (FILE *in_file); 371 372 void ResetOutputFileHandle(FILE *new_fh) override; 373 374 static void 375 InitializePrivate (); 376 377 static void 378 InitializeInterpreter (SWIGInitCallback python_swig_init_callback, 379 SWIGBreakpointCallbackFunction swig_breakpoint_callback, 380 SWIGWatchpointCallbackFunction swig_watchpoint_callback, 381 SWIGPythonTypeScriptCallbackFunction swig_typescript_callback, 382 SWIGPythonCreateSyntheticProvider swig_synthetic_script, 383 SWIGPythonCreateCommandObject swig_create_cmd, 384 SWIGPythonCalculateNumChildren swig_calc_children, 385 SWIGPythonGetChildAtIndex swig_get_child_index, 386 SWIGPythonGetIndexOfChildWithName swig_get_index_child, 387 SWIGPythonCastPyObjectToSBValue swig_cast_to_sbvalue , 388 SWIGPythonGetValueObjectSPFromSBValue swig_get_valobj_sp_from_sbvalue, 389 SWIGPythonUpdateSynthProviderInstance swig_update_provider, 390 SWIGPythonMightHaveChildrenSynthProviderInstance swig_mighthavechildren_provider, 391 SWIGPythonGetValueSynthProviderInstance swig_getvalue_provider, 392 SWIGPythonCallCommand swig_call_command, 393 SWIGPythonCallCommandObject swig_call_command_object, 394 SWIGPythonCallModuleInit swig_call_module_init, 395 SWIGPythonCreateOSPlugin swig_create_os_plugin, 396 SWIGPythonScriptKeyword_Process swig_run_script_keyword_process, 397 SWIGPythonScriptKeyword_Thread swig_run_script_keyword_thread, 398 SWIGPythonScriptKeyword_Target swig_run_script_keyword_target, 399 SWIGPythonScriptKeyword_Frame swig_run_script_keyword_frame, 400 SWIGPythonScriptKeyword_Value swig_run_script_keyword_value, 401 SWIGPython_GetDynamicSetting swig_plugin_get, 402 SWIGPythonCreateScriptedThreadPlan swig_thread_plan_script, 403 SWIGPythonCallThreadPlan swig_call_thread_plan); 404 405 const char * 406 GetDictionaryName () 407 { 408 return m_dictionary_name.c_str(); 409 } 410 411 PyThreadState * 412 GetThreadState() 413 { 414 return m_command_thread_state; 415 } 416 417 void 418 SetThreadState (PyThreadState *s) 419 { 420 if (s) 421 m_command_thread_state = s; 422 } 423 424 //---------------------------------------------------------------------- 425 // IOHandlerDelegate 426 //---------------------------------------------------------------------- 427 void 428 IOHandlerActivated (IOHandler &io_handler) override; 429 430 void 431 IOHandlerInputComplete (IOHandler &io_handler, std::string &data) override; 432 433 //------------------------------------------------------------------ 434 // Static Functions 435 //------------------------------------------------------------------ 436 static void 437 Initialize(); 438 439 static void 440 Terminate(); 441 442 static lldb::ScriptInterpreterSP 443 CreateInstance(CommandInterpreter &interpreter); 444 445 static lldb_private::ConstString 446 GetPluginNameStatic(); 447 448 static const char * 449 GetPluginDescriptionStatic(); 450 451 //------------------------------------------------------------------ 452 // PluginInterface protocol 453 //------------------------------------------------------------------ 454 lldb_private::ConstString 455 GetPluginName() override; 456 457 uint32_t 458 GetPluginVersion() override; 459 460 class Locker : public ScriptInterpreterLocker 461 { 462 public: 463 enum OnEntry 464 { 465 AcquireLock = 0x0001, 466 InitSession = 0x0002, 467 InitGlobals = 0x0004, 468 NoSTDIN = 0x0008 469 }; 470 471 enum OnLeave 472 { 473 FreeLock = 0x0001, 474 FreeAcquiredLock = 0x0002, // do not free the lock if we already held it when calling constructor 475 TearDownSession = 0x0004 476 }; 477 478 Locker(ScriptInterpreterPython *py_interpreter = nullptr, 479 uint16_t on_entry = AcquireLock | InitSession, 480 uint16_t on_leave = FreeLock | TearDownSession, 481 FILE *in = nullptr, 482 FILE *out = nullptr, 483 FILE *err = nullptr); 484 485 ~Locker () override; 486 487 private: 488 bool 489 DoAcquireLock (); 490 491 bool 492 DoInitSession (uint16_t on_entry_flags, FILE *in, FILE *out, FILE *err); 493 494 bool 495 DoFreeLock (); 496 497 bool 498 DoTearDownSession (); 499 500 static void 501 ReleasePythonLock (); 502 503 bool m_teardown_session; 504 ScriptInterpreterPython *m_python_interpreter; 505 // FILE* m_tmp_fh; 506 PyGILState_STATE m_GILState; 507 }; 508 509 protected: 510 class SynchronicityHandler 511 { 512 private: 513 lldb::DebuggerSP m_debugger_sp; 514 ScriptedCommandSynchronicity m_synch_wanted; 515 bool m_old_asynch; 516 517 public: 518 SynchronicityHandler(lldb::DebuggerSP, 519 ScriptedCommandSynchronicity); 520 521 ~SynchronicityHandler(); 522 }; 523 524 enum class AddLocation 525 { 526 Beginning, 527 End 528 }; 529 530 static void AddToSysPath(AddLocation location, std::string path); 531 532 bool 533 EnterSession(uint16_t on_entry_flags, 534 FILE *in, 535 FILE *out, 536 FILE *err); 537 538 void 539 LeaveSession(); 540 541 void 542 SaveTerminalState(int fd); 543 544 void 545 RestoreTerminalState(); 546 547 uint32_t 548 IsExecutingPython () const 549 { 550 return m_lock_count > 0; 551 } 552 553 uint32_t 554 IncrementLockCount() 555 { 556 return ++m_lock_count; 557 } 558 559 uint32_t 560 DecrementLockCount() 561 { 562 if (m_lock_count > 0) 563 --m_lock_count; 564 return m_lock_count; 565 } 566 567 enum ActiveIOHandler { 568 eIOHandlerNone, 569 eIOHandlerBreakpoint, 570 eIOHandlerWatchpoint 571 }; 572 573 PythonObject &GetMainModule(); 574 575 PythonDictionary & 576 GetSessionDictionary (); 577 578 PythonDictionary & 579 GetSysModuleDictionary (); 580 581 bool 582 GetEmbeddedInterpreterModuleObjects (); 583 584 PythonFile m_saved_stdin; 585 PythonFile m_saved_stdout; 586 PythonFile m_saved_stderr; 587 PythonObject m_main_module; 588 PythonObject m_lldb_module; 589 PythonDictionary m_session_dict; 590 PythonDictionary m_sys_module_dict; 591 PythonObject m_run_one_line_function; 592 PythonObject m_run_one_line_str_global; 593 std::string m_dictionary_name; 594 TerminalState m_terminal_state; 595 ActiveIOHandler m_active_io_handler; 596 bool m_session_is_active; 597 bool m_pty_slave_is_open; 598 bool m_valid_session; 599 uint32_t m_lock_count; 600 PyThreadState *m_command_thread_state; 601 }; 602 603 } // namespace lldb_private 604 605 #endif // LLDB_DISABLE_PYTHON 606 607 #endif // LLDB_PLUGINS_SCRIPTINTERPRETER_PYTHON_SCRIPTINTERPRETERPYTHON_H 608