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