1 //===-- ScriptInterpreterPythonImpl.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_SCRIPTINTERPRETERPYTHONIMPL_H 10 #define LLDB_PLUGINS_SCRIPTINTERPRETER_PYTHON_SCRIPTINTERPRETERPYTHONIMPL_H 11 12 #include "lldb/Host/Config.h" 13 14 #if LLDB_ENABLE_PYTHON 15 16 #include "lldb-python.h" 17 18 #include "PythonDataObjects.h" 19 #include "ScriptInterpreterPython.h" 20 21 #include "lldb/Host/Terminal.h" 22 #include "lldb/Utility/StreamString.h" 23 24 #include "llvm/ADT/STLExtras.h" 25 #include "llvm/ADT/StringRef.h" 26 27 namespace lldb_private { 28 class IOHandlerPythonInterpreter; 29 class ScriptInterpreterPythonImpl : public ScriptInterpreterPython { 30 public: 31 friend class IOHandlerPythonInterpreter; 32 33 ScriptInterpreterPythonImpl(Debugger &debugger); 34 35 ~ScriptInterpreterPythonImpl() override; 36 37 bool Interrupt() override; 38 39 bool ExecuteOneLine( 40 llvm::StringRef command, CommandReturnObject *result, 41 const ExecuteScriptOptions &options = ExecuteScriptOptions()) override; 42 43 void ExecuteInterpreterLoop() override; 44 45 bool ExecuteOneLineWithReturn( 46 llvm::StringRef in_string, 47 ScriptInterpreter::ScriptReturnType return_type, void *ret_value, 48 const ExecuteScriptOptions &options = ExecuteScriptOptions()) override; 49 50 lldb_private::Status ExecuteMultipleLines( 51 const char *in_string, 52 const ExecuteScriptOptions &options = ExecuteScriptOptions()) override; 53 54 Status 55 ExportFunctionDefinitionToInterpreter(StringList &function_def) override; 56 57 bool GenerateTypeScriptFunction(StringList &input, std::string &output, 58 const void *name_token = nullptr) override; 59 60 bool GenerateTypeSynthClass(StringList &input, std::string &output, 61 const void *name_token = nullptr) override; 62 63 bool GenerateTypeSynthClass(const char *oneliner, std::string &output, 64 const void *name_token = nullptr) override; 65 66 // use this if the function code is just a one-liner script 67 bool GenerateTypeScriptFunction(const char *oneliner, std::string &output, 68 const void *name_token = nullptr) override; 69 70 bool GenerateScriptAliasFunction(StringList &input, 71 std::string &output) override; 72 73 StructuredData::ObjectSP 74 CreateSyntheticScriptedProvider(const char *class_name, 75 lldb::ValueObjectSP valobj) override; 76 77 StructuredData::GenericSP 78 CreateScriptCommandObject(const char *class_name) override; 79 80 StructuredData::ObjectSP 81 CreateScriptedThreadPlan(const char *class_name, 82 const StructuredDataImpl &args_data, 83 std::string &error_str, 84 lldb::ThreadPlanSP thread_plan) override; 85 86 bool ScriptedThreadPlanExplainsStop(StructuredData::ObjectSP implementor_sp, 87 Event *event, 88 bool &script_error) override; 89 90 bool ScriptedThreadPlanShouldStop(StructuredData::ObjectSP implementor_sp, 91 Event *event, bool &script_error) override; 92 93 bool ScriptedThreadPlanIsStale(StructuredData::ObjectSP implementor_sp, 94 bool &script_error) override; 95 96 lldb::StateType 97 ScriptedThreadPlanGetRunState(StructuredData::ObjectSP implementor_sp, 98 bool &script_error) override; 99 100 StructuredData::GenericSP 101 CreateScriptedBreakpointResolver(const char *class_name, 102 const StructuredDataImpl &args_data, 103 lldb::BreakpointSP &bkpt_sp) override; 104 bool ScriptedBreakpointResolverSearchCallback( 105 StructuredData::GenericSP implementor_sp, 106 SymbolContext *sym_ctx) override; 107 108 lldb::SearchDepth ScriptedBreakpointResolverSearchDepth( 109 StructuredData::GenericSP implementor_sp) override; 110 111 StructuredData::GenericSP 112 CreateScriptedStopHook(lldb::TargetSP target_sp, const char *class_name, 113 const StructuredDataImpl &args_data, 114 Status &error) override; 115 116 bool ScriptedStopHookHandleStop(StructuredData::GenericSP implementor_sp, 117 ExecutionContext &exc_ctx, 118 lldb::StreamSP stream_sp) override; 119 120 StructuredData::GenericSP 121 CreateFrameRecognizer(const char *class_name) override; 122 123 lldb::ValueObjectListSP 124 GetRecognizedArguments(const StructuredData::ObjectSP &implementor, 125 lldb::StackFrameSP frame_sp) override; 126 127 lldb::ScriptedProcessInterfaceUP CreateScriptedProcessInterface() override; 128 129 StructuredData::GenericSP 130 OSPlugin_CreatePluginObject(const char *class_name, 131 lldb::ProcessSP process_sp) override; 132 133 StructuredData::DictionarySP 134 OSPlugin_RegisterInfo(StructuredData::ObjectSP os_plugin_object_sp) override; 135 136 StructuredData::ArraySP 137 OSPlugin_ThreadsInfo(StructuredData::ObjectSP os_plugin_object_sp) override; 138 139 StructuredData::StringSP 140 OSPlugin_RegisterContextData(StructuredData::ObjectSP os_plugin_object_sp, 141 lldb::tid_t thread_id) override; 142 143 StructuredData::DictionarySP 144 OSPlugin_CreateThread(StructuredData::ObjectSP os_plugin_object_sp, 145 lldb::tid_t tid, lldb::addr_t context) override; 146 147 StructuredData::ObjectSP 148 LoadPluginModule(const FileSpec &file_spec, 149 lldb_private::Status &error) override; 150 151 StructuredData::DictionarySP 152 GetDynamicSettings(StructuredData::ObjectSP plugin_module_sp, Target *target, 153 const char *setting_name, 154 lldb_private::Status &error) override; 155 156 size_t CalculateNumChildren(const StructuredData::ObjectSP &implementor, 157 uint32_t max) override; 158 159 lldb::ValueObjectSP 160 GetChildAtIndex(const StructuredData::ObjectSP &implementor, 161 uint32_t idx) override; 162 163 int GetIndexOfChildWithName(const StructuredData::ObjectSP &implementor, 164 const char *child_name) override; 165 166 bool UpdateSynthProviderInstance( 167 const StructuredData::ObjectSP &implementor) override; 168 169 bool MightHaveChildrenSynthProviderInstance( 170 const StructuredData::ObjectSP &implementor) override; 171 172 lldb::ValueObjectSP 173 GetSyntheticValue(const StructuredData::ObjectSP &implementor) override; 174 175 ConstString 176 GetSyntheticTypeName(const StructuredData::ObjectSP &implementor) override; 177 178 bool 179 RunScriptBasedCommand(const char *impl_function, llvm::StringRef args, 180 ScriptedCommandSynchronicity synchronicity, 181 lldb_private::CommandReturnObject &cmd_retobj, 182 Status &error, 183 const lldb_private::ExecutionContext &exe_ctx) override; 184 185 bool RunScriptBasedCommand( 186 StructuredData::GenericSP impl_obj_sp, llvm::StringRef args, 187 ScriptedCommandSynchronicity synchronicity, 188 lldb_private::CommandReturnObject &cmd_retobj, Status &error, 189 const lldb_private::ExecutionContext &exe_ctx) override; 190 191 Status GenerateFunction(const char *signature, 192 const StringList &input) override; 193 194 Status GenerateBreakpointCommandCallbackData( 195 StringList &input, 196 std::string &output, 197 bool has_extra_args) override; 198 199 bool GenerateWatchpointCommandCallbackData(StringList &input, 200 std::string &output) override; 201 202 bool GetScriptedSummary(const char *function_name, lldb::ValueObjectSP valobj, 203 StructuredData::ObjectSP &callee_wrapper_sp, 204 const TypeSummaryOptions &options, 205 std::string &retval) override; 206 207 bool FormatterCallbackFunction(const char *function_name, 208 lldb::TypeImplSP type_impl_sp) override; 209 210 bool GetDocumentationForItem(const char *item, std::string &dest) override; 211 212 bool GetShortHelpForCommandObject(StructuredData::GenericSP cmd_obj_sp, 213 std::string &dest) override; 214 215 uint32_t 216 GetFlagsForCommandObject(StructuredData::GenericSP cmd_obj_sp) override; 217 218 bool GetLongHelpForCommandObject(StructuredData::GenericSP cmd_obj_sp, 219 std::string &dest) override; 220 221 bool CheckObjectExists(const char *name) override { 222 if (!name || !name[0]) 223 return false; 224 std::string temp; 225 return GetDocumentationForItem(name, temp); 226 } 227 228 bool RunScriptFormatKeyword(const char *impl_function, Process *process, 229 std::string &output, Status &error) override; 230 231 bool RunScriptFormatKeyword(const char *impl_function, Thread *thread, 232 std::string &output, Status &error) override; 233 234 bool RunScriptFormatKeyword(const char *impl_function, Target *target, 235 std::string &output, Status &error) override; 236 237 bool RunScriptFormatKeyword(const char *impl_function, StackFrame *frame, 238 std::string &output, Status &error) override; 239 240 bool RunScriptFormatKeyword(const char *impl_function, ValueObject *value, 241 std::string &output, Status &error) override; 242 243 bool LoadScriptingModule(const char *filename, 244 const LoadScriptOptions &options, 245 lldb_private::Status &error, 246 StructuredData::ObjectSP *module_sp = nullptr, 247 FileSpec extra_search_dir = {}) override; 248 249 bool IsReservedWord(const char *word) override; 250 251 std::unique_ptr<ScriptInterpreterLocker> AcquireInterpreterLock() override; 252 253 void CollectDataForBreakpointCommandCallback( 254 std::vector<std::reference_wrapper<BreakpointOptions>> &bp_options_vec, 255 CommandReturnObject &result) override; 256 257 void 258 CollectDataForWatchpointCommandCallback(WatchpointOptions *wp_options, 259 CommandReturnObject &result) override; 260 261 /// Set the callback body text into the callback for the breakpoint. 262 Status SetBreakpointCommandCallback(BreakpointOptions &bp_options, 263 const char *callback_body) override; 264 265 Status SetBreakpointCommandCallbackFunction( 266 BreakpointOptions &bp_options, const char *function_name, 267 StructuredData::ObjectSP extra_args_sp) override; 268 269 /// This one is for deserialization: 270 Status SetBreakpointCommandCallback( 271 BreakpointOptions &bp_options, 272 std::unique_ptr<BreakpointOptions::CommandData> &data_up) override; 273 274 Status SetBreakpointCommandCallback(BreakpointOptions &bp_options, 275 const char *command_body_text, 276 StructuredData::ObjectSP extra_args_sp, 277 bool uses_extra_args); 278 279 /// Set a one-liner as the callback for the watchpoint. 280 void SetWatchpointCommandCallback(WatchpointOptions *wp_options, 281 const char *oneliner) override; 282 283 const char *GetDictionaryName() { return m_dictionary_name.c_str(); } 284 285 PyThreadState *GetThreadState() { return m_command_thread_state; } 286 287 void SetThreadState(PyThreadState *s) { 288 if (s) 289 m_command_thread_state = s; 290 } 291 292 // IOHandlerDelegate 293 void IOHandlerActivated(IOHandler &io_handler, bool interactive) override; 294 295 void IOHandlerInputComplete(IOHandler &io_handler, 296 std::string &data) override; 297 298 static lldb::ScriptInterpreterSP CreateInstance(Debugger &debugger); 299 300 // PluginInterface protocol 301 llvm::StringRef GetPluginName() override { return GetPluginNameStatic(); } 302 303 class Locker : public ScriptInterpreterLocker { 304 public: 305 enum OnEntry { 306 AcquireLock = 0x0001, 307 InitSession = 0x0002, 308 InitGlobals = 0x0004, 309 NoSTDIN = 0x0008 310 }; 311 312 enum OnLeave { 313 FreeLock = 0x0001, 314 FreeAcquiredLock = 0x0002, // do not free the lock if we already held it 315 // when calling constructor 316 TearDownSession = 0x0004 317 }; 318 319 Locker(ScriptInterpreterPythonImpl *py_interpreter, 320 uint16_t on_entry = AcquireLock | InitSession, 321 uint16_t on_leave = FreeLock | TearDownSession, 322 lldb::FileSP in = nullptr, lldb::FileSP out = nullptr, 323 lldb::FileSP err = nullptr); 324 325 ~Locker() override; 326 327 private: 328 bool DoAcquireLock(); 329 330 bool DoInitSession(uint16_t on_entry_flags, lldb::FileSP in, 331 lldb::FileSP out, lldb::FileSP err); 332 333 bool DoFreeLock(); 334 335 bool DoTearDownSession(); 336 337 bool m_teardown_session; 338 ScriptInterpreterPythonImpl *m_python_interpreter; 339 PyGILState_STATE m_GILState; 340 }; 341 342 static bool BreakpointCallbackFunction(void *baton, 343 StoppointCallbackContext *context, 344 lldb::user_id_t break_id, 345 lldb::user_id_t break_loc_id); 346 static bool WatchpointCallbackFunction(void *baton, 347 StoppointCallbackContext *context, 348 lldb::user_id_t watch_id); 349 static void Initialize(); 350 351 class SynchronicityHandler { 352 private: 353 lldb::DebuggerSP m_debugger_sp; 354 ScriptedCommandSynchronicity m_synch_wanted; 355 bool m_old_asynch; 356 357 public: 358 SynchronicityHandler(lldb::DebuggerSP, ScriptedCommandSynchronicity); 359 360 ~SynchronicityHandler(); 361 }; 362 363 enum class AddLocation { Beginning, End }; 364 365 static void AddToSysPath(AddLocation location, std::string path); 366 367 bool EnterSession(uint16_t on_entry_flags, lldb::FileSP in, lldb::FileSP out, 368 lldb::FileSP err); 369 370 void LeaveSession(); 371 372 uint32_t IsExecutingPython() const { return m_lock_count > 0; } 373 374 uint32_t IncrementLockCount() { return ++m_lock_count; } 375 376 uint32_t DecrementLockCount() { 377 if (m_lock_count > 0) 378 --m_lock_count; 379 return m_lock_count; 380 } 381 382 enum ActiveIOHandler { 383 eIOHandlerNone, 384 eIOHandlerBreakpoint, 385 eIOHandlerWatchpoint 386 }; 387 388 python::PythonModule &GetMainModule(); 389 390 python::PythonDictionary &GetSessionDictionary(); 391 392 python::PythonDictionary &GetSysModuleDictionary(); 393 394 llvm::Expected<unsigned> GetMaxPositionalArgumentsForCallable( 395 const llvm::StringRef &callable_name) override; 396 397 bool GetEmbeddedInterpreterModuleObjects(); 398 399 bool SetStdHandle(lldb::FileSP file, const char *py_name, 400 python::PythonObject &save_file, const char *mode); 401 402 python::PythonObject m_saved_stdin; 403 python::PythonObject m_saved_stdout; 404 python::PythonObject m_saved_stderr; 405 python::PythonModule m_main_module; 406 python::PythonDictionary m_session_dict; 407 python::PythonDictionary m_sys_module_dict; 408 python::PythonObject m_run_one_line_function; 409 python::PythonObject m_run_one_line_str_global; 410 std::string m_dictionary_name; 411 ActiveIOHandler m_active_io_handler; 412 bool m_session_is_active; 413 bool m_pty_secondary_is_open; 414 bool m_valid_session; 415 uint32_t m_lock_count; 416 PyThreadState *m_command_thread_state; 417 }; 418 419 class IOHandlerPythonInterpreter : public IOHandler { 420 public: 421 IOHandlerPythonInterpreter(Debugger &debugger, 422 ScriptInterpreterPythonImpl *python) 423 : IOHandler(debugger, IOHandler::Type::PythonInterpreter), 424 m_python(python) {} 425 426 ~IOHandlerPythonInterpreter() override = default; 427 428 ConstString GetControlSequence(char ch) override { 429 if (ch == 'd') 430 return ConstString("quit()\n"); 431 return ConstString(); 432 } 433 434 void Run() override { 435 if (m_python) { 436 int stdin_fd = GetInputFD(); 437 if (stdin_fd >= 0) { 438 Terminal terminal(stdin_fd); 439 TerminalState terminal_state(terminal); 440 441 if (terminal.IsATerminal()) { 442 // FIXME: error handling? 443 llvm::consumeError(terminal.SetCanonical(false)); 444 llvm::consumeError(terminal.SetEcho(true)); 445 } 446 447 ScriptInterpreterPythonImpl::Locker locker( 448 m_python, 449 ScriptInterpreterPythonImpl::Locker::AcquireLock | 450 ScriptInterpreterPythonImpl::Locker::InitSession | 451 ScriptInterpreterPythonImpl::Locker::InitGlobals, 452 ScriptInterpreterPythonImpl::Locker::FreeAcquiredLock | 453 ScriptInterpreterPythonImpl::Locker::TearDownSession); 454 455 // The following call drops into the embedded interpreter loop and 456 // stays there until the user chooses to exit from the Python 457 // interpreter. This embedded interpreter will, as any Python code that 458 // performs I/O, unlock the GIL before a system call that can hang, and 459 // lock it when the syscall has returned. 460 461 // We need to surround the call to the embedded interpreter with calls 462 // to PyGILState_Ensure and PyGILState_Release (using the Locker 463 // above). This is because Python has a global lock which must be held 464 // whenever we want to touch any Python objects. Otherwise, if the user 465 // calls Python code, the interpreter state will be off, and things 466 // could hang (it's happened before). 467 468 StreamString run_string; 469 run_string.Printf("run_python_interpreter (%s)", 470 m_python->GetDictionaryName()); 471 PyRun_SimpleString(run_string.GetData()); 472 } 473 } 474 SetIsDone(true); 475 } 476 477 void Cancel() override {} 478 479 bool Interrupt() override { return m_python->Interrupt(); } 480 481 void GotEOF() override {} 482 483 protected: 484 ScriptInterpreterPythonImpl *m_python; 485 }; 486 487 } // namespace lldb_private 488 489 #endif // LLDB_ENABLE_PYTHON 490 #endif // LLDB_PLUGINS_SCRIPTINTERPRETER_PYTHON_SCRIPTINTERPRETERPYTHONIMPL_H 491