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