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