1 //===-- Debugger.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_CORE_DEBUGGER_H 10 #define LLDB_CORE_DEBUGGER_H 11 12 #include <cstdint> 13 14 #include <memory> 15 #include <vector> 16 17 #include "lldb/Core/DebuggerEvents.h" 18 #include "lldb/Core/FormatEntity.h" 19 #include "lldb/Core/IOHandler.h" 20 #include "lldb/Core/SourceManager.h" 21 #include "lldb/Core/StreamFile.h" 22 #include "lldb/Core/UserSettingsController.h" 23 #include "lldb/Host/HostThread.h" 24 #include "lldb/Host/Terminal.h" 25 #include "lldb/Target/ExecutionContext.h" 26 #include "lldb/Target/Platform.h" 27 #include "lldb/Target/TargetList.h" 28 #include "lldb/Utility/Broadcaster.h" 29 #include "lldb/Utility/ConstString.h" 30 #include "lldb/Utility/FileSpec.h" 31 #include "lldb/Utility/Status.h" 32 #include "lldb/Utility/UserID.h" 33 #include "lldb/lldb-defines.h" 34 #include "lldb/lldb-enumerations.h" 35 #include "lldb/lldb-forward.h" 36 #include "lldb/lldb-private-enumerations.h" 37 #include "lldb/lldb-private-types.h" 38 #include "lldb/lldb-types.h" 39 40 #include "llvm/ADT/ArrayRef.h" 41 #include "llvm/ADT/StringMap.h" 42 #include "llvm/ADT/StringRef.h" 43 #include "llvm/Support/DynamicLibrary.h" 44 #include "llvm/Support/Threading.h" 45 46 #include <cassert> 47 #include <cstddef> 48 #include <cstdio> 49 50 namespace llvm { 51 class raw_ostream; 52 class ThreadPool; 53 } 54 55 namespace lldb_private { 56 class Address; 57 class CallbackLogHandler; 58 class CommandInterpreter; 59 class LogHandler; 60 class Process; 61 class Stream; 62 class SymbolContext; 63 class Target; 64 65 namespace repro { 66 class DataRecorder; 67 } 68 69 /// \class Debugger Debugger.h "lldb/Core/Debugger.h" 70 /// A class to manage flag bits. 71 /// 72 /// Provides a global root objects for the debugger core. 73 74 class Debugger : public std::enable_shared_from_this<Debugger>, 75 public UserID, 76 public Properties { 77 friend class SourceManager; // For GetSourceFileCache. 78 79 public: 80 /// Broadcaster event bits definitions. 81 enum { 82 eBroadcastBitProgress = (1 << 0), 83 eBroadcastBitWarning = (1 << 1), 84 eBroadcastBitError = (1 << 2), 85 }; 86 87 static ConstString GetStaticBroadcasterClass(); 88 89 /// Get the public broadcaster for this debugger. 90 Broadcaster &GetBroadcaster() { return m_broadcaster; } 91 const Broadcaster &GetBroadcaster() const { return m_broadcaster; } 92 93 ~Debugger() override; 94 95 static lldb::DebuggerSP 96 CreateInstance(lldb::LogOutputCallback log_callback = nullptr, 97 void *baton = nullptr); 98 99 static lldb::TargetSP FindTargetWithProcessID(lldb::pid_t pid); 100 101 static lldb::TargetSP FindTargetWithProcess(Process *process); 102 103 static void Initialize(LoadPluginCallbackType load_plugin_callback); 104 105 static void Terminate(); 106 107 static void SettingsInitialize(); 108 109 static void SettingsTerminate(); 110 111 static void Destroy(lldb::DebuggerSP &debugger_sp); 112 113 static lldb::DebuggerSP FindDebuggerWithID(lldb::user_id_t id); 114 115 static lldb::DebuggerSP 116 FindDebuggerWithInstanceName(ConstString instance_name); 117 118 static size_t GetNumDebuggers(); 119 120 static lldb::DebuggerSP GetDebuggerAtIndex(size_t index); 121 122 static bool FormatDisassemblerAddress(const FormatEntity::Entry *format, 123 const SymbolContext *sc, 124 const SymbolContext *prev_sc, 125 const ExecutionContext *exe_ctx, 126 const Address *addr, Stream &s); 127 128 void Clear(); 129 130 bool GetAsyncExecution(); 131 132 void SetAsyncExecution(bool async); 133 134 lldb::FileSP GetInputFileSP() { return m_input_file_sp; } 135 136 lldb::StreamFileSP GetOutputStreamSP() { return m_output_stream_sp; } 137 138 lldb::StreamFileSP GetErrorStreamSP() { return m_error_stream_sp; } 139 140 File &GetInputFile() { return *m_input_file_sp; } 141 142 File &GetOutputFile() { return m_output_stream_sp->GetFile(); } 143 144 File &GetErrorFile() { return m_error_stream_sp->GetFile(); } 145 146 StreamFile &GetOutputStream() { return *m_output_stream_sp; } 147 148 StreamFile &GetErrorStream() { return *m_error_stream_sp; } 149 150 repro::DataRecorder *GetInputRecorder(); 151 152 Status SetInputString(const char *data); 153 154 // This method will setup data recorder if reproducer enabled. 155 // On reply mode this method should take instructions from reproducer file. 156 Status SetInputFile(lldb::FileSP file); 157 158 void SetInputFile(lldb::FileSP file, repro::DataRecorder *recorder); 159 160 void SetOutputFile(lldb::FileSP file); 161 162 void SetErrorFile(lldb::FileSP file); 163 164 void SaveInputTerminalState(); 165 166 void RestoreInputTerminalState(); 167 168 lldb::StreamSP GetAsyncOutputStream(); 169 170 lldb::StreamSP GetAsyncErrorStream(); 171 172 CommandInterpreter &GetCommandInterpreter() { 173 assert(m_command_interpreter_up.get()); 174 return *m_command_interpreter_up; 175 } 176 177 ScriptInterpreter * 178 GetScriptInterpreter(bool can_create = true, 179 llvm::Optional<lldb::ScriptLanguage> language = {}); 180 181 lldb::ListenerSP GetListener() { return m_listener_sp; } 182 183 // This returns the Debugger's scratch source manager. It won't be able to 184 // look up files in debug information, but it can look up files by absolute 185 // path and display them to you. To get the target's source manager, call 186 // GetSourceManager on the target instead. 187 SourceManager &GetSourceManager(); 188 189 lldb::TargetSP GetSelectedTarget() { 190 return m_target_list.GetSelectedTarget(); 191 } 192 193 ExecutionContext GetSelectedExecutionContext(); 194 /// Get accessor for the target list. 195 /// 196 /// The target list is part of the global debugger object. This the single 197 /// debugger shared instance to control where targets get created and to 198 /// allow for tracking and searching for targets based on certain criteria. 199 /// 200 /// \return 201 /// A global shared target list. 202 TargetList &GetTargetList() { return m_target_list; } 203 204 PlatformList &GetPlatformList() { return m_platform_list; } 205 206 void DispatchInputInterrupt(); 207 208 void DispatchInputEndOfFile(); 209 210 // If any of the streams are not set, set them to the in/out/err stream of 211 // the top most input reader to ensure they at least have something 212 void AdoptTopIOHandlerFilesIfInvalid(lldb::FileSP &in, 213 lldb::StreamFileSP &out, 214 lldb::StreamFileSP &err); 215 216 /// Run the given IO handler and return immediately. 217 void RunIOHandlerAsync(const lldb::IOHandlerSP &reader_sp, 218 bool cancel_top_handler = true); 219 220 /// Run the given IO handler and block until it's complete. 221 void RunIOHandlerSync(const lldb::IOHandlerSP &reader_sp); 222 223 /// Remove the given IO handler if it's currently active. 224 bool RemoveIOHandler(const lldb::IOHandlerSP &reader_sp); 225 226 bool IsTopIOHandler(const lldb::IOHandlerSP &reader_sp); 227 228 bool CheckTopIOHandlerTypes(IOHandler::Type top_type, 229 IOHandler::Type second_top_type); 230 231 void PrintAsync(const char *s, size_t len, bool is_stdout); 232 233 ConstString GetTopIOHandlerControlSequence(char ch); 234 235 const char *GetIOHandlerCommandPrefix(); 236 237 const char *GetIOHandlerHelpPrologue(); 238 239 void ClearIOHandlers(); 240 241 bool GetCloseInputOnEOF() const; 242 243 void SetCloseInputOnEOF(bool b); 244 245 bool EnableLog(llvm::StringRef channel, 246 llvm::ArrayRef<const char *> categories, 247 llvm::StringRef log_file, uint32_t log_options, 248 size_t buffer_size, LogHandlerKind log_handler_kind, 249 llvm::raw_ostream &error_stream); 250 251 void SetLoggingCallback(lldb::LogOutputCallback log_callback, void *baton); 252 253 // Properties Functions 254 enum StopDisassemblyType { 255 eStopDisassemblyTypeNever = 0, 256 eStopDisassemblyTypeNoDebugInfo, 257 eStopDisassemblyTypeNoSource, 258 eStopDisassemblyTypeAlways 259 }; 260 261 Status SetPropertyValue(const ExecutionContext *exe_ctx, 262 VarSetOperationType op, llvm::StringRef property_path, 263 llvm::StringRef value) override; 264 265 bool GetAutoConfirm() const; 266 267 const FormatEntity::Entry *GetDisassemblyFormat() const; 268 269 const FormatEntity::Entry *GetFrameFormat() const; 270 271 const FormatEntity::Entry *GetFrameFormatUnique() const; 272 273 uint32_t GetStopDisassemblyMaxSize() const; 274 275 const FormatEntity::Entry *GetThreadFormat() const; 276 277 const FormatEntity::Entry *GetThreadStopFormat() const; 278 279 lldb::ScriptLanguage GetScriptLanguage() const; 280 281 bool SetScriptLanguage(lldb::ScriptLanguage script_lang); 282 283 lldb::LanguageType GetREPLLanguage() const; 284 285 bool SetREPLLanguage(lldb::LanguageType repl_lang); 286 287 uint32_t GetTerminalWidth() const; 288 289 bool SetTerminalWidth(uint32_t term_width); 290 291 llvm::StringRef GetPrompt() const; 292 293 void SetPrompt(llvm::StringRef p); 294 void SetPrompt(const char *) = delete; 295 296 llvm::StringRef GetReproducerPath() const; 297 298 bool GetUseExternalEditor() const; 299 300 bool SetUseExternalEditor(bool use_external_editor_p); 301 302 bool GetUseColor() const; 303 304 bool SetUseColor(bool use_color); 305 306 bool GetShowProgress() const; 307 308 bool SetShowProgress(bool show_progress); 309 310 llvm::StringRef GetShowProgressAnsiPrefix() const; 311 312 llvm::StringRef GetShowProgressAnsiSuffix() const; 313 314 bool GetUseAutosuggestion() const; 315 316 llvm::StringRef GetAutosuggestionAnsiPrefix() const; 317 318 llvm::StringRef GetAutosuggestionAnsiSuffix() const; 319 320 bool GetUseSourceCache() const; 321 322 bool SetUseSourceCache(bool use_source_cache); 323 324 bool GetHighlightSource() const; 325 326 lldb::StopShowColumn GetStopShowColumn() const; 327 328 llvm::StringRef GetStopShowColumnAnsiPrefix() const; 329 330 llvm::StringRef GetStopShowColumnAnsiSuffix() const; 331 332 uint32_t GetStopSourceLineCount(bool before) const; 333 334 StopDisassemblyType GetStopDisassemblyDisplay() const; 335 336 uint32_t GetDisassemblyLineCount() const; 337 338 llvm::StringRef GetStopShowLineMarkerAnsiPrefix() const; 339 340 llvm::StringRef GetStopShowLineMarkerAnsiSuffix() const; 341 342 bool GetAutoOneLineSummaries() const; 343 344 bool GetAutoIndent() const; 345 346 bool SetAutoIndent(bool b); 347 348 bool GetPrintDecls() const; 349 350 bool SetPrintDecls(bool b); 351 352 uint32_t GetTabSize() const; 353 354 bool SetTabSize(uint32_t tab_size); 355 356 bool GetEscapeNonPrintables() const; 357 358 bool GetNotifyVoid() const; 359 360 ConstString GetInstanceName() { return m_instance_name; } 361 362 bool LoadPlugin(const FileSpec &spec, Status &error); 363 364 void RunIOHandlers(); 365 366 bool IsForwardingEvents(); 367 368 void EnableForwardEvents(const lldb::ListenerSP &listener_sp); 369 370 void CancelForwardEvents(const lldb::ListenerSP &listener_sp); 371 372 bool IsHandlingEvents() const { return m_event_handler_thread.IsJoinable(); } 373 374 Status RunREPL(lldb::LanguageType language, const char *repl_options); 375 376 // This is for use in the command interpreter, when you either want the 377 // selected target, or if no target is present you want to prime the dummy 378 // target with entities that will be copied over to new targets. 379 Target &GetSelectedOrDummyTarget(bool prefer_dummy = false); 380 Target &GetDummyTarget() { return *m_dummy_target_sp; } 381 382 lldb::BroadcasterManagerSP GetBroadcasterManager() { 383 return m_broadcaster_manager_sp; 384 } 385 386 /// Shared thread poll. Use only with ThreadPoolTaskGroup. 387 static llvm::ThreadPool &GetThreadPool(); 388 389 /// Report warning events. 390 /// 391 /// Progress events will be delivered to any debuggers that have listeners 392 /// for the eBroadcastBitError. 393 /// 394 /// \param[in] message 395 /// The warning message to be reported. 396 /// 397 /// \param [in] debugger_id 398 /// If this optional parameter has a value, it indicates the unique 399 /// debugger identifier that this progress should be delivered to. If this 400 /// optional parameter does not have a value, the progress will be 401 /// delivered to all debuggers. 402 /// 403 /// \param [in] once 404 /// If a pointer is passed to a std::once_flag, then it will be used to 405 /// ensure the given warning is only broadcast once. 406 static void 407 ReportWarning(std::string messsage, 408 llvm::Optional<lldb::user_id_t> debugger_id = llvm::None, 409 std::once_flag *once = nullptr); 410 411 /// Report error events. 412 /// 413 /// Progress events will be delivered to any debuggers that have listeners 414 /// for the eBroadcastBitError. 415 /// 416 /// \param[in] message 417 /// The error message to be reported. 418 /// 419 /// \param [in] debugger_id 420 /// If this optional parameter has a value, it indicates the unique 421 /// debugger identifier that this progress should be delivered to. If this 422 /// optional parameter does not have a value, the progress will be 423 /// delivered to all debuggers. 424 /// 425 /// \param [in] once 426 /// If a pointer is passed to a std::once_flag, then it will be used to 427 /// ensure the given error is only broadcast once. 428 static void 429 ReportError(std::string messsage, 430 llvm::Optional<lldb::user_id_t> debugger_id = llvm::None, 431 std::once_flag *once = nullptr); 432 433 protected: 434 friend class CommandInterpreter; 435 friend class REPL; 436 friend class Progress; 437 438 /// Report progress events. 439 /// 440 /// Progress events will be delivered to any debuggers that have listeners 441 /// for the eBroadcastBitProgress. This function is called by the 442 /// lldb_private::Progress class to deliver the events to any debuggers that 443 /// qualify. 444 /// 445 /// \param [in] progress_id 446 /// The unique integer identifier for the progress to report. 447 /// 448 /// \param[in] message 449 /// The title of the progress dialog to display in the UI. 450 /// 451 /// \param [in] completed 452 /// The amount of work completed. If \a completed is zero, then this event 453 /// is a progress started event. If \a completed is equal to \a total, then 454 /// this event is a progress end event. Otherwise completed indicates the 455 /// current progress compare to the total value. 456 /// 457 /// \param [in] total 458 /// The total amount of work units that need to be completed. If this value 459 /// is UINT64_MAX, then an indeterminate progress indicator should be 460 /// displayed. 461 /// 462 /// \param [in] debugger_id 463 /// If this optional parameter has a value, it indicates the unique 464 /// debugger identifier that this progress should be delivered to. If this 465 /// optional parameter does not have a value, the progress will be 466 /// delivered to all debuggers. 467 static void ReportProgress(uint64_t progress_id, const std::string &message, 468 uint64_t completed, uint64_t total, 469 llvm::Optional<lldb::user_id_t> debugger_id); 470 471 static void ReportDiagnosticImpl(DiagnosticEventData::Type type, 472 std::string message, 473 llvm::Optional<lldb::user_id_t> debugger_id, 474 std::once_flag *once); 475 476 void PrintProgress(const ProgressEventData &data); 477 478 bool StartEventHandlerThread(); 479 480 void StopEventHandlerThread(); 481 482 void PushIOHandler(const lldb::IOHandlerSP &reader_sp, 483 bool cancel_top_handler = true); 484 485 bool PopIOHandler(const lldb::IOHandlerSP &reader_sp); 486 487 bool HasIOHandlerThread(); 488 489 bool StartIOHandlerThread(); 490 491 void StopIOHandlerThread(); 492 493 void JoinIOHandlerThread(); 494 495 lldb::thread_result_t IOHandlerThread(); 496 497 lldb::thread_result_t DefaultEventHandler(); 498 499 void HandleBreakpointEvent(const lldb::EventSP &event_sp); 500 501 void HandleProcessEvent(const lldb::EventSP &event_sp); 502 503 void HandleThreadEvent(const lldb::EventSP &event_sp); 504 505 void HandleProgressEvent(const lldb::EventSP &event_sp); 506 507 void HandleDiagnosticEvent(const lldb::EventSP &event_sp); 508 509 // Ensures two threads don't attempt to flush process output in parallel. 510 std::mutex m_output_flush_mutex; 511 void FlushProcessOutput(Process &process, bool flush_stdout, 512 bool flush_stderr); 513 514 SourceManager::SourceFileCache &GetSourceFileCache() { 515 return m_source_file_cache; 516 } 517 518 void InstanceInitialize(); 519 520 // these should never be NULL 521 lldb::FileSP m_input_file_sp; 522 lldb::StreamFileSP m_output_stream_sp; 523 lldb::StreamFileSP m_error_stream_sp; 524 525 /// Used for shadowing the input file when capturing a reproducer. 526 repro::DataRecorder *m_input_recorder; 527 528 lldb::BroadcasterManagerSP m_broadcaster_manager_sp; // The debugger acts as a 529 // broadcaster manager of 530 // last resort. 531 // It needs to get constructed before the target_list or any other member 532 // that might want to broadcast through the debugger. 533 534 TerminalState m_terminal_state; 535 TargetList m_target_list; 536 537 PlatformList m_platform_list; 538 lldb::ListenerSP m_listener_sp; 539 std::unique_ptr<SourceManager> m_source_manager_up; // This is a scratch 540 // source manager that we 541 // return if we have no 542 // targets. 543 SourceManager::SourceFileCache m_source_file_cache; // All the source managers 544 // for targets created in 545 // this debugger used this 546 // shared 547 // source file cache. 548 std::unique_ptr<CommandInterpreter> m_command_interpreter_up; 549 550 std::recursive_mutex m_script_interpreter_mutex; 551 std::array<lldb::ScriptInterpreterSP, lldb::eScriptLanguageUnknown> 552 m_script_interpreters; 553 554 IOHandlerStack m_io_handler_stack; 555 std::recursive_mutex m_io_handler_synchronous_mutex; 556 557 llvm::Optional<uint64_t> m_current_event_id; 558 559 llvm::StringMap<std::weak_ptr<LogHandler>> m_stream_handlers; 560 std::shared_ptr<CallbackLogHandler> m_callback_handler_sp; 561 ConstString m_instance_name; 562 static LoadPluginCallbackType g_load_plugin_callback; 563 typedef std::vector<llvm::sys::DynamicLibrary> LoadedPluginsList; 564 LoadedPluginsList m_loaded_plugins; 565 HostThread m_event_handler_thread; 566 HostThread m_io_handler_thread; 567 Broadcaster m_sync_broadcaster; ///< Private debugger synchronization. 568 Broadcaster m_broadcaster; ///< Public Debugger event broadcaster. 569 lldb::ListenerSP m_forward_listener_sp; 570 llvm::once_flag m_clear_once; 571 lldb::TargetSP m_dummy_target_sp; 572 573 // Events for m_sync_broadcaster 574 enum { 575 eBroadcastBitEventThreadIsListening = (1 << 0), 576 }; 577 578 private: 579 // Use Debugger::CreateInstance() to get a shared pointer to a new debugger 580 // object 581 Debugger(lldb::LogOutputCallback m_log_callback, void *baton); 582 583 Debugger(const Debugger &) = delete; 584 const Debugger &operator=(const Debugger &) = delete; 585 }; 586 587 } // namespace lldb_private 588 589 #endif // LLDB_CORE_DEBUGGER_H 590