xref: /freebsd/contrib/llvm-project/lldb/include/lldb/Core/Debugger.h (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
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 <optional>
16 #include <vector>
17 
18 #include "lldb/Core/DebuggerEvents.h"
19 #include "lldb/Core/FormatEntity.h"
20 #include "lldb/Core/IOHandler.h"
21 #include "lldb/Core/SourceManager.h"
22 #include "lldb/Core/UserSettingsController.h"
23 #include "lldb/Host/HostThread.h"
24 #include "lldb/Host/StreamFile.h"
25 #include "lldb/Host/Terminal.h"
26 #include "lldb/Target/ExecutionContext.h"
27 #include "lldb/Target/Platform.h"
28 #include "lldb/Target/TargetList.h"
29 #include "lldb/Utility/Broadcaster.h"
30 #include "lldb/Utility/ConstString.h"
31 #include "lldb/Utility/Diagnostics.h"
32 #include "lldb/Utility/FileSpec.h"
33 #include "lldb/Utility/Status.h"
34 #include "lldb/Utility/UserID.h"
35 #include "lldb/lldb-defines.h"
36 #include "lldb/lldb-enumerations.h"
37 #include "lldb/lldb-forward.h"
38 #include "lldb/lldb-private-enumerations.h"
39 #include "lldb/lldb-private-types.h"
40 #include "lldb/lldb-types.h"
41 
42 #include "llvm/ADT/ArrayRef.h"
43 #include "llvm/ADT/SmallVector.h"
44 #include "llvm/ADT/StringMap.h"
45 #include "llvm/ADT/StringRef.h"
46 #include "llvm/Support/DynamicLibrary.h"
47 #include "llvm/Support/FormatVariadic.h"
48 #include "llvm/Support/Threading.h"
49 
50 #include <cassert>
51 #include <cstddef>
52 #include <cstdio>
53 
54 namespace llvm {
55 class raw_ostream;
56 class ThreadPoolInterface;
57 } // namespace llvm
58 
59 namespace lldb_private {
60 class Address;
61 class CallbackLogHandler;
62 class CommandInterpreter;
63 class LogHandler;
64 class Process;
65 class Stream;
66 class SymbolContext;
67 class Target;
68 
69 namespace repro {
70 class DataRecorder;
71 }
72 
73 /// \class Debugger Debugger.h "lldb/Core/Debugger.h"
74 /// A class to manage flag bits.
75 ///
76 /// Provides a global root objects for the debugger core.
77 
78 class Debugger : public std::enable_shared_from_this<Debugger>,
79                  public UserID,
80                  public Properties {
81 public:
82   using DebuggerList = std::vector<lldb::DebuggerSP>;
83 
84   static llvm::StringRef GetStaticBroadcasterClass();
85 
86   /// Get the public broadcaster for this debugger.
GetBroadcaster()87   Broadcaster &GetBroadcaster() { return m_broadcaster; }
GetBroadcaster()88   const Broadcaster &GetBroadcaster() const { return m_broadcaster; }
89 
90   ~Debugger() override;
91 
92   static lldb::DebuggerSP
93   CreateInstance(lldb::LogOutputCallback log_callback = nullptr,
94                  void *baton = nullptr);
95 
96   static lldb::TargetSP FindTargetWithProcessID(lldb::pid_t pid);
97 
98   static lldb::TargetSP FindTargetWithProcess(Process *process);
99 
100   static void Initialize(LoadPluginCallbackType load_plugin_callback);
101 
102   static void Terminate();
103 
104   static void SettingsInitialize();
105 
106   static void SettingsTerminate();
107 
108   static void Destroy(lldb::DebuggerSP &debugger_sp);
109 
110   static lldb::DebuggerSP FindDebuggerWithID(lldb::user_id_t id);
111 
112   static lldb::DebuggerSP
113   FindDebuggerWithInstanceName(llvm::StringRef instance_name);
114 
115   static size_t GetNumDebuggers();
116 
117   static lldb::DebuggerSP GetDebuggerAtIndex(size_t index);
118 
119   static bool FormatDisassemblerAddress(const FormatEntity::Entry *format,
120                                         const SymbolContext *sc,
121                                         const SymbolContext *prev_sc,
122                                         const ExecutionContext *exe_ctx,
123                                         const Address *addr, Stream &s);
124 
125   static void AssertCallback(llvm::StringRef message, llvm::StringRef backtrace,
126                              llvm::StringRef prompt);
127 
128   void Clear();
129 
130   bool GetAsyncExecution();
131 
132   void SetAsyncExecution(bool async);
133 
GetInputFileSP()134   lldb::FileSP GetInputFileSP() { return m_input_file_sp; }
135 
GetOutputStreamSP()136   lldb::StreamFileSP GetOutputStreamSP() { return m_output_stream_sp; }
137 
GetErrorStreamSP()138   lldb::StreamFileSP GetErrorStreamSP() { return m_error_stream_sp; }
139 
GetInputFile()140   File &GetInputFile() { return *m_input_file_sp; }
141 
GetOutputFile()142   File &GetOutputFile() { return m_output_stream_sp->GetFile(); }
143 
GetErrorFile()144   File &GetErrorFile() { return m_error_stream_sp->GetFile(); }
145 
GetOutputStream()146   StreamFile &GetOutputStream() { return *m_output_stream_sp; }
147 
GetErrorStream()148   StreamFile &GetErrorStream() { return *m_error_stream_sp; }
149 
150   repro::DataRecorder *GetInputRecorder();
151 
152   Status SetInputString(const char *data);
153 
154   void SetInputFile(lldb::FileSP file);
155 
156   void SetOutputFile(lldb::FileSP file);
157 
158   void SetErrorFile(lldb::FileSP file);
159 
160   void SaveInputTerminalState();
161 
162   void RestoreInputTerminalState();
163 
164   lldb::StreamSP GetAsyncOutputStream();
165 
166   lldb::StreamSP GetAsyncErrorStream();
167 
GetCommandInterpreter()168   CommandInterpreter &GetCommandInterpreter() {
169     assert(m_command_interpreter_up.get());
170     return *m_command_interpreter_up;
171   }
172 
173   ScriptInterpreter *
174   GetScriptInterpreter(bool can_create = true,
175                        std::optional<lldb::ScriptLanguage> language = {});
176 
GetListener()177   lldb::ListenerSP GetListener() { return m_listener_sp; }
178 
179   // This returns the Debugger's scratch source manager.  It won't be able to
180   // look up files in debug information, but it can look up files by absolute
181   // path and display them to you. To get the target's source manager, call
182   // GetSourceManager on the target instead.
183   SourceManager &GetSourceManager();
184 
GetSelectedTarget()185   lldb::TargetSP GetSelectedTarget() {
186     return m_target_list.GetSelectedTarget();
187   }
188 
189   ExecutionContext GetSelectedExecutionContext();
190   /// Get accessor for the target list.
191   ///
192   /// The target list is part of the global debugger object. This the single
193   /// debugger shared instance to control where targets get created and to
194   /// allow for tracking and searching for targets based on certain criteria.
195   ///
196   /// \return
197   ///     A global shared target list.
GetTargetList()198   TargetList &GetTargetList() { return m_target_list; }
199 
GetPlatformList()200   PlatformList &GetPlatformList() { return m_platform_list; }
201 
202   void DispatchInputInterrupt();
203 
204   void DispatchInputEndOfFile();
205 
206   // If any of the streams are not set, set them to the in/out/err stream of
207   // the top most input reader to ensure they at least have something
208   void AdoptTopIOHandlerFilesIfInvalid(lldb::FileSP &in,
209                                        lldb::StreamFileSP &out,
210                                        lldb::StreamFileSP &err);
211 
212   /// Run the given IO handler and return immediately.
213   void RunIOHandlerAsync(const lldb::IOHandlerSP &reader_sp,
214                          bool cancel_top_handler = true);
215 
216   /// Run the given IO handler and block until it's complete.
217   void RunIOHandlerSync(const lldb::IOHandlerSP &reader_sp);
218 
219   ///  Remove the given IO handler if it's currently active.
220   bool RemoveIOHandler(const lldb::IOHandlerSP &reader_sp);
221 
222   bool IsTopIOHandler(const lldb::IOHandlerSP &reader_sp);
223 
224   bool CheckTopIOHandlerTypes(IOHandler::Type top_type,
225                               IOHandler::Type second_top_type);
226 
227   void PrintAsync(const char *s, size_t len, bool is_stdout);
228 
229   llvm::StringRef GetTopIOHandlerControlSequence(char ch);
230 
231   const char *GetIOHandlerCommandPrefix();
232 
233   const char *GetIOHandlerHelpPrologue();
234 
235   void ClearIOHandlers();
236 
237   bool EnableLog(llvm::StringRef channel,
238                  llvm::ArrayRef<const char *> categories,
239                  llvm::StringRef log_file, uint32_t log_options,
240                  size_t buffer_size, LogHandlerKind log_handler_kind,
241                  llvm::raw_ostream &error_stream);
242 
243   void SetLoggingCallback(lldb::LogOutputCallback log_callback, void *baton);
244 
245   // Properties Functions
246   enum StopDisassemblyType {
247     eStopDisassemblyTypeNever = 0,
248     eStopDisassemblyTypeNoDebugInfo,
249     eStopDisassemblyTypeNoSource,
250     eStopDisassemblyTypeAlways
251   };
252 
253   Status SetPropertyValue(const ExecutionContext *exe_ctx,
254                           VarSetOperationType op, llvm::StringRef property_path,
255                           llvm::StringRef value) override;
256 
257   bool GetAutoConfirm() const;
258 
259   const FormatEntity::Entry *GetDisassemblyFormat() const;
260 
261   const FormatEntity::Entry *GetFrameFormat() const;
262 
263   const FormatEntity::Entry *GetFrameFormatUnique() const;
264 
265   uint64_t GetStopDisassemblyMaxSize() const;
266 
267   const FormatEntity::Entry *GetThreadFormat() const;
268 
269   const FormatEntity::Entry *GetThreadStopFormat() const;
270 
271   lldb::ScriptLanguage GetScriptLanguage() const;
272 
273   bool SetScriptLanguage(lldb::ScriptLanguage script_lang);
274 
275   lldb::LanguageType GetREPLLanguage() const;
276 
277   bool SetREPLLanguage(lldb::LanguageType repl_lang);
278 
279   uint64_t GetTerminalWidth() const;
280 
281   bool SetTerminalWidth(uint64_t term_width);
282 
283   llvm::StringRef GetPrompt() const;
284 
285   llvm::StringRef GetPromptAnsiPrefix() const;
286 
287   llvm::StringRef GetPromptAnsiSuffix() const;
288 
289   void SetPrompt(llvm::StringRef p);
290   void SetPrompt(const char *) = delete;
291 
292   bool GetUseExternalEditor() const;
293   bool SetUseExternalEditor(bool use_external_editor_p);
294 
295   llvm::StringRef GetExternalEditor() const;
296 
297   bool SetExternalEditor(llvm::StringRef editor);
298 
299   bool GetUseColor() const;
300 
301   bool SetUseColor(bool use_color);
302 
303   bool GetShowProgress() const;
304 
305   bool SetShowProgress(bool show_progress);
306 
307   llvm::StringRef GetShowProgressAnsiPrefix() const;
308 
309   llvm::StringRef GetShowProgressAnsiSuffix() const;
310 
311   bool GetUseAutosuggestion() const;
312 
313   llvm::StringRef GetAutosuggestionAnsiPrefix() const;
314 
315   llvm::StringRef GetAutosuggestionAnsiSuffix() const;
316 
317   llvm::StringRef GetRegexMatchAnsiPrefix() const;
318 
319   llvm::StringRef GetRegexMatchAnsiSuffix() const;
320 
321   bool GetShowDontUsePoHint() const;
322 
323   bool GetUseSourceCache() const;
324 
325   bool SetUseSourceCache(bool use_source_cache);
326 
327   bool GetHighlightSource() const;
328 
329   lldb::StopShowColumn GetStopShowColumn() const;
330 
331   llvm::StringRef GetStopShowColumnAnsiPrefix() const;
332 
333   llvm::StringRef GetStopShowColumnAnsiSuffix() const;
334 
335   uint64_t GetStopSourceLineCount(bool before) const;
336 
337   StopDisassemblyType GetStopDisassemblyDisplay() const;
338 
339   uint64_t GetDisassemblyLineCount() const;
340 
341   llvm::StringRef GetStopShowLineMarkerAnsiPrefix() const;
342 
343   llvm::StringRef GetStopShowLineMarkerAnsiSuffix() const;
344 
345   bool GetAutoOneLineSummaries() const;
346 
347   bool GetAutoIndent() const;
348 
349   bool SetAutoIndent(bool b);
350 
351   bool GetPrintDecls() const;
352 
353   bool SetPrintDecls(bool b);
354 
355   uint64_t GetTabSize() const;
356 
357   bool SetTabSize(uint64_t tab_size);
358 
359   lldb::DWIMPrintVerbosity GetDWIMPrintVerbosity() const;
360 
361   bool GetEscapeNonPrintables() const;
362 
363   bool GetNotifyVoid() const;
364 
GetInstanceName()365   const std::string &GetInstanceName() { return m_instance_name; }
366 
367   bool LoadPlugin(const FileSpec &spec, Status &error);
368 
369   void RunIOHandlers();
370 
371   bool IsForwardingEvents();
372 
373   void EnableForwardEvents(const lldb::ListenerSP &listener_sp);
374 
375   void CancelForwardEvents(const lldb::ListenerSP &listener_sp);
376 
IsHandlingEvents()377   bool IsHandlingEvents() const { return m_event_handler_thread.IsJoinable(); }
378 
379   Status RunREPL(lldb::LanguageType language, const char *repl_options);
380 
381   /// Interruption in LLDB:
382   ///
383   /// This is a voluntary interruption mechanism, not preemptive.  Parts of lldb
384   /// that do work that can be safely interrupted call
385   /// Debugger::InterruptRequested and if that returns true, they should return
386   /// at a safe point, shortcutting the rest of the work they were to do.
387   ///
388   /// lldb clients can both offer a CommandInterpreter (through
389   /// RunCommandInterpreter) and use the SB API's for their own purposes, so it
390   /// is convenient to separate "interrupting the CommandInterpreter execution"
391   /// and interrupting the work it is doing with the SB API's.  So there are two
392   /// ways to cause an interrupt:
393   ///   * CommandInterpreter::InterruptCommand: Interrupts the command currently
394   ///     running in the command interpreter IOHandler thread
395   ///   * Debugger::RequestInterrupt: Interrupts are active on anything but the
396   ///     CommandInterpreter thread till CancelInterruptRequest is called.
397   ///
398   /// Since the two checks are mutually exclusive, however, it's also convenient
399   /// to have just one function to check the interrupt state.
400 
401   /// Bump the "interrupt requested" count on the debugger to support
402   /// cooperative interruption.  If this is non-zero, InterruptRequested will
403   /// return true.  Interruptible operations are expected to query the
404   /// InterruptRequested API periodically, and interrupt what they were doing
405   /// if it returns \b true.
406   ///
407   void RequestInterrupt();
408 
409   /// Decrement the "interrupt requested" counter.
410   void CancelInterruptRequest();
411 
412   /// This is the correct way to query the state of Interruption.
413   /// If you are on the RunCommandInterpreter thread, it will check the
414   /// command interpreter state, and if it is on another thread it will
415   /// check the debugger Interrupt Request state.
416   /// \param[in] cur_func
417   /// For reporting if the interruption was requested.  Don't provide this by
418   /// hand, use INTERRUPT_REQUESTED so this gets done consistently.
419   ///
420   /// \param[in] formatv
421   /// A formatv string for the interrupt message.  If the elements of the
422   /// message are expensive to compute, you can use the no-argument form of
423   /// InterruptRequested, then make up the report using REPORT_INTERRUPTION.
424   ///
425   /// \return
426   ///  A boolean value, if \b true an interruptible operation should interrupt
427   ///  itself.
428   template <typename... Args>
InterruptRequested(const char * cur_func,const char * formatv,Args &&...args)429   bool InterruptRequested(const char *cur_func, const char *formatv,
430                           Args &&...args) {
431     bool ret_val = InterruptRequested();
432     if (ret_val) {
433       if (!formatv)
434         formatv = "Unknown message";
435       if (!cur_func)
436         cur_func = "<UNKNOWN>";
437       ReportInterruption(InterruptionReport(
438           cur_func, llvm::formatv(formatv, std::forward<Args>(args)...)));
439     }
440     return ret_val;
441   }
442 
443   /// This handy define will keep you from having to generate a report for the
444   /// interruption by hand.  Use this except in the case where the arguments to
445   /// the message description are expensive to compute.
446 #define INTERRUPT_REQUESTED(debugger, ...)                                     \
447   (debugger).InterruptRequested(__func__, __VA_ARGS__)
448 
449   // This form just queries for whether to interrupt, and does no reporting:
450   bool InterruptRequested();
451 
452   // FIXME: Do we want to capture a backtrace at the interruption point?
453   class InterruptionReport {
454   public:
InterruptionReport(std::string function_name,std::string description)455     InterruptionReport(std::string function_name, std::string description)
456         : m_function_name(std::move(function_name)),
457           m_description(std::move(description)),
458           m_interrupt_time(std::chrono::system_clock::now()),
459           m_thread_id(llvm::get_threadid()) {}
460 
461     InterruptionReport(std::string function_name,
462                        const llvm::formatv_object_base &payload);
463 
464     template <typename... Args>
InterruptionReport(std::string function_name,const char * format,Args &&...args)465     InterruptionReport(std::string function_name, const char *format,
466                        Args &&...args)
467         : InterruptionReport(
468               function_name,
469               llvm::formatv(format, std::forward<Args>(args)...)) {}
470 
471     std::string m_function_name;
472     std::string m_description;
473     const std::chrono::time_point<std::chrono::system_clock> m_interrupt_time;
474     const uint64_t m_thread_id;
475   };
476   void ReportInterruption(const InterruptionReport &report);
477 #define REPORT_INTERRUPTION(debugger, ...)                                     \
478   (debugger).ReportInterruption(                                               \
479       Debugger::InterruptionReport(__func__, __VA_ARGS__))
480 
481   static DebuggerList DebuggersRequestingInterruption();
482 
483 public:
484   // This is for use in the command interpreter, when you either want the
485   // selected target, or if no target is present you want to prime the dummy
486   // target with entities that will be copied over to new targets.
487   Target &GetSelectedOrDummyTarget(bool prefer_dummy = false);
GetDummyTarget()488   Target &GetDummyTarget() { return *m_dummy_target_sp; }
489 
GetBroadcasterManager()490   lldb::BroadcasterManagerSP GetBroadcasterManager() {
491     return m_broadcaster_manager_sp;
492   }
493 
494   /// Shared thread pool. Use only with ThreadPoolTaskGroup.
495   static llvm::ThreadPoolInterface &GetThreadPool();
496 
497   /// Report warning events.
498   ///
499   /// Warning events will be delivered to any debuggers that have listeners
500   /// for the eBroadcastBitWarning.
501   ///
502   /// \param[in] message
503   ///   The warning message to be reported.
504   ///
505   /// \param [in] debugger_id
506   ///   If this optional parameter has a value, it indicates the unique
507   ///   debugger identifier that this diagnostic should be delivered to. If
508   ///   this optional parameter does not have a value, the diagnostic event
509   ///   will be delivered to all debuggers.
510   ///
511   /// \param [in] once
512   ///   If a pointer is passed to a std::once_flag, then it will be used to
513   ///   ensure the given warning is only broadcast once.
514   static void
515   ReportWarning(std::string message,
516                 std::optional<lldb::user_id_t> debugger_id = std::nullopt,
517                 std::once_flag *once = nullptr);
518 
519   /// Report error events.
520   ///
521   /// Error events will be delivered to any debuggers that have listeners
522   /// for the eBroadcastBitError.
523   ///
524   /// \param[in] message
525   ///   The error message to be reported.
526   ///
527   /// \param [in] debugger_id
528   ///   If this optional parameter has a value, it indicates the unique
529   ///   debugger identifier that this diagnostic should be delivered to. If
530   ///   this optional parameter does not have a value, the diagnostic event
531   ///   will be delivered to all debuggers.
532   ///
533   /// \param [in] once
534   ///   If a pointer is passed to a std::once_flag, then it will be used to
535   ///   ensure the given error is only broadcast once.
536   static void
537   ReportError(std::string message,
538               std::optional<lldb::user_id_t> debugger_id = std::nullopt,
539               std::once_flag *once = nullptr);
540 
541   /// Report info events.
542   ///
543   /// Unlike warning and error events, info events are not broadcast but are
544   /// logged for diagnostic purposes.
545   ///
546   /// \param[in] message
547   ///   The info message to be reported.
548   ///
549   /// \param [in] debugger_id
550   ///   If this optional parameter has a value, it indicates this diagnostic is
551   ///   associated with a unique debugger instance.
552   ///
553   /// \param [in] once
554   ///   If a pointer is passed to a std::once_flag, then it will be used to
555   ///   ensure the given info is only logged once.
556   static void
557   ReportInfo(std::string message,
558              std::optional<lldb::user_id_t> debugger_id = std::nullopt,
559              std::once_flag *once = nullptr);
560 
561   static void ReportSymbolChange(const ModuleSpec &module_spec);
562 
563   /// DEPRECATED: We used to only support one Destroy callback. Now that we
564   /// support Add and Remove, you should only remove callbacks that you added.
565   /// Use Add and Remove instead.
566   ///
567   /// Clear all previously added callbacks and only add the given one.
568   void
569   SetDestroyCallback(lldb_private::DebuggerDestroyCallback destroy_callback,
570                      void *baton);
571 
572   /// Add a callback for when the debugger is destroyed. Return a token, which
573   /// can be used to remove said callback. Multiple callbacks can be added by
574   /// calling this function multiple times, and will be invoked in FIFO order.
575   lldb::callback_token_t
576   AddDestroyCallback(lldb_private::DebuggerDestroyCallback destroy_callback,
577                      void *baton);
578 
579   /// Remove the specified callback. Return true if successful.
580   bool RemoveDestroyCallback(lldb::callback_token_t token);
581 
582   /// Manually start the global event handler thread. It is useful to plugins
583   /// that directly use the \a lldb_private namespace and want to use the
584   /// debugger's default event handler thread instead of defining their own.
585   bool StartEventHandlerThread();
586 
587   /// Manually stop the debugger's default event handler.
588   void StopEventHandlerThread();
589 
590   /// Force flushing the process's pending stdout and stderr to the debugger's
591   /// asynchronous stdout and stderr streams.
592   void FlushProcessOutput(Process &process, bool flush_stdout,
593                           bool flush_stderr);
594 
GetSourceFileCache()595   SourceManager::SourceFileCache &GetSourceFileCache() {
596     return m_source_file_cache;
597   }
598 
599 protected:
600   friend class CommandInterpreter;
601   friend class REPL;
602   friend class Progress;
603   friend class ProgressManager;
604 
605   /// Report progress events.
606   ///
607   /// Progress events will be delivered to any debuggers that have listeners
608   /// for the eBroadcastBitProgress. This function is called by the
609   /// lldb_private::Progress class to deliver the events to any debuggers that
610   /// qualify.
611   ///
612   /// \param [in] progress_id
613   ///   The unique integer identifier for the progress to report.
614   ///
615   /// \param[in] message
616   ///   The title of the progress dialog to display in the UI.
617   ///
618   /// \param [in] completed
619   ///   The amount of work completed. If \a completed is zero, then this event
620   ///   is a progress started event. If \a completed is equal to \a total, then
621   ///   this event is a progress end event. Otherwise completed indicates the
622   ///   current progress compare to the total value.
623   ///
624   /// \param [in] total
625   ///   The total amount of work units that need to be completed. If this value
626   ///   is UINT64_MAX, then an indeterminate progress indicator should be
627   ///   displayed.
628   ///
629   /// \param [in] debugger_id
630   ///   If this optional parameter has a value, it indicates the unique
631   ///   debugger identifier that this progress should be delivered to. If this
632   ///   optional parameter does not have a value, the progress will be
633   ///   delivered to all debuggers.
634   static void
635   ReportProgress(uint64_t progress_id, std::string title, std::string details,
636                  uint64_t completed, uint64_t total,
637                  std::optional<lldb::user_id_t> debugger_id,
638                  uint32_t progress_category_bit = lldb::eBroadcastBitProgress);
639 
640   static void ReportDiagnosticImpl(lldb::Severity severity, std::string message,
641                                    std::optional<lldb::user_id_t> debugger_id,
642                                    std::once_flag *once);
643 
644   void HandleDestroyCallback();
645 
646   void PrintProgress(const ProgressEventData &data);
647 
648   void PushIOHandler(const lldb::IOHandlerSP &reader_sp,
649                      bool cancel_top_handler = true);
650 
651   bool PopIOHandler(const lldb::IOHandlerSP &reader_sp);
652 
653   bool HasIOHandlerThread() const;
654 
655   bool StartIOHandlerThread();
656 
657   void StopIOHandlerThread();
658 
659   // Sets the IOHandler thread to the new_thread, and returns
660   // the previous IOHandler thread.
661   HostThread SetIOHandlerThread(HostThread &new_thread);
662 
663   void JoinIOHandlerThread();
664 
665   bool IsIOHandlerThreadCurrentThread() const;
666 
667   lldb::thread_result_t IOHandlerThread();
668 
669   lldb::thread_result_t DefaultEventHandler();
670 
671   void HandleBreakpointEvent(const lldb::EventSP &event_sp);
672 
673   void HandleProcessEvent(const lldb::EventSP &event_sp);
674 
675   void HandleThreadEvent(const lldb::EventSP &event_sp);
676 
677   void HandleProgressEvent(const lldb::EventSP &event_sp);
678 
679   void HandleDiagnosticEvent(const lldb::EventSP &event_sp);
680 
681   // Ensures two threads don't attempt to flush process output in parallel.
682   std::mutex m_output_flush_mutex;
683 
684   void InstanceInitialize();
685 
686   // these should never be NULL
687   lldb::FileSP m_input_file_sp;
688   lldb::StreamFileSP m_output_stream_sp;
689   lldb::StreamFileSP m_error_stream_sp;
690 
691   /// Used for shadowing the input file when capturing a reproducer.
692   repro::DataRecorder *m_input_recorder;
693 
694   lldb::BroadcasterManagerSP m_broadcaster_manager_sp; // The debugger acts as a
695                                                        // broadcaster manager of
696                                                        // last resort.
697   // It needs to get constructed before the target_list or any other member
698   // that might want to broadcast through the debugger.
699 
700   TerminalState m_terminal_state;
701   TargetList m_target_list;
702 
703   PlatformList m_platform_list;
704   lldb::ListenerSP m_listener_sp;
705   std::unique_ptr<SourceManager> m_source_manager_up; // This is a scratch
706                                                       // source manager that we
707                                                       // return if we have no
708                                                       // targets.
709   SourceManager::SourceFileCache m_source_file_cache; // All the source managers
710                                                       // for targets created in
711                                                       // this debugger used this
712                                                       // shared
713                                                       // source file cache.
714   std::unique_ptr<CommandInterpreter> m_command_interpreter_up;
715 
716   std::recursive_mutex m_script_interpreter_mutex;
717   std::array<lldb::ScriptInterpreterSP, lldb::eScriptLanguageUnknown>
718       m_script_interpreters;
719 
720   IOHandlerStack m_io_handler_stack;
721   std::recursive_mutex m_io_handler_synchronous_mutex;
722 
723   std::optional<uint64_t> m_current_event_id;
724 
725   llvm::StringMap<std::weak_ptr<LogHandler>> m_stream_handlers;
726   std::shared_ptr<CallbackLogHandler> m_callback_handler_sp;
727   const std::string m_instance_name;
728   static LoadPluginCallbackType g_load_plugin_callback;
729   typedef std::vector<llvm::sys::DynamicLibrary> LoadedPluginsList;
730   LoadedPluginsList m_loaded_plugins;
731   HostThread m_event_handler_thread;
732   HostThread m_io_handler_thread;
733   Broadcaster m_sync_broadcaster; ///< Private debugger synchronization.
734   Broadcaster m_broadcaster;      ///< Public Debugger event broadcaster.
735   lldb::ListenerSP m_forward_listener_sp;
736   llvm::once_flag m_clear_once;
737   lldb::TargetSP m_dummy_target_sp;
738   Diagnostics::CallbackID m_diagnostics_callback_id;
739 
740   std::mutex m_destroy_callback_mutex;
741   lldb::callback_token_t m_destroy_callback_next_token = 0;
742   struct DestroyCallbackInfo {
DestroyCallbackInfoDestroyCallbackInfo743     DestroyCallbackInfo() {}
DestroyCallbackInfoDestroyCallbackInfo744     DestroyCallbackInfo(lldb::callback_token_t token,
745                         lldb_private::DebuggerDestroyCallback callback,
746                         void *baton)
747         : token(token), callback(callback), baton(baton) {}
748     lldb::callback_token_t token;
749     lldb_private::DebuggerDestroyCallback callback;
750     void *baton;
751   };
752   llvm::SmallVector<DestroyCallbackInfo, 2> m_destroy_callbacks;
753 
754   uint32_t m_interrupt_requested = 0; ///< Tracks interrupt requests
755   std::mutex m_interrupt_mutex;
756 
757   // Events for m_sync_broadcaster
758   enum {
759     eBroadcastBitEventThreadIsListening = (1 << 0),
760   };
761 
762 private:
763   // Use Debugger::CreateInstance() to get a shared pointer to a new debugger
764   // object
765   Debugger(lldb::LogOutputCallback m_log_callback, void *baton);
766 
767   Debugger(const Debugger &) = delete;
768   const Debugger &operator=(const Debugger &) = delete;
769 };
770 
771 } // namespace lldb_private
772 
773 #endif // LLDB_CORE_DEBUGGER_H
774