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