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