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 <stdint.h>
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 <assert.h>
46#include <stddef.h>
47#include <stdio.h>
48
49namespace llvm {
50class raw_ostream;
51}
52
53namespace lldb_private {
54class Address;
55class CommandInterpreter;
56class Process;
57class Stream;
58class SymbolContext;
59class Target;
60
61namespace repro {
62class 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
70class Debugger : public std::enable_shared_from_this<Debugger>,
71                 public UserID,
72                 public Properties {
73  friend class SourceManager; // For GetSourceFileCache.
74
75public:
76  ~Debugger() override;
77
78  static lldb::DebuggerSP
79  CreateInstance(lldb::LogOutputCallback log_callback = nullptr,
80                 void *baton = nullptr);
81
82  static lldb::TargetSP FindTargetWithProcessID(lldb::pid_t pid);
83
84  static lldb::TargetSP FindTargetWithProcess(Process *process);
85
86  static void Initialize(LoadPluginCallbackType load_plugin_callback);
87
88  static void Terminate();
89
90  static void SettingsInitialize();
91
92  static void SettingsTerminate();
93
94  static void Destroy(lldb::DebuggerSP &debugger_sp);
95
96  static lldb::DebuggerSP FindDebuggerWithID(lldb::user_id_t id);
97
98  static lldb::DebuggerSP
99  FindDebuggerWithInstanceName(ConstString instance_name);
100
101  static size_t GetNumDebuggers();
102
103  static lldb::DebuggerSP GetDebuggerAtIndex(size_t index);
104
105  static bool FormatDisassemblerAddress(const FormatEntity::Entry *format,
106                                        const SymbolContext *sc,
107                                        const SymbolContext *prev_sc,
108                                        const ExecutionContext *exe_ctx,
109                                        const Address *addr, Stream &s);
110
111  void Clear();
112
113  bool GetAsyncExecution();
114
115  void SetAsyncExecution(bool async);
116
117  lldb::FileSP GetInputFileSP() { return m_input_file_sp; }
118
119  lldb::StreamFileSP GetOutputStreamSP() { return m_output_stream_sp; }
120
121  lldb::StreamFileSP GetErrorStreamSP() { return m_error_stream_sp; }
122
123  File &GetInputFile() { return *m_input_file_sp; }
124
125  File &GetOutputFile() { return m_output_stream_sp->GetFile(); }
126
127  File &GetErrorFile() { return m_error_stream_sp->GetFile(); }
128
129  StreamFile &GetOutputStream() { return *m_output_stream_sp; }
130
131  StreamFile &GetErrorStream() { return *m_error_stream_sp; }
132
133  repro::DataRecorder *GetInputRecorder();
134
135  void SetInputFile(lldb::FileSP file, repro::DataRecorder *recorder = nullptr);
136
137  void SetOutputFile(lldb::FileSP file);
138
139  void SetErrorFile(lldb::FileSP file);
140
141  void SaveInputTerminalState();
142
143  void RestoreInputTerminalState();
144
145  lldb::StreamSP GetAsyncOutputStream();
146
147  lldb::StreamSP GetAsyncErrorStream();
148
149  CommandInterpreter &GetCommandInterpreter() {
150    assert(m_command_interpreter_up.get());
151    return *m_command_interpreter_up;
152  }
153
154  ScriptInterpreter *
155  GetScriptInterpreter(bool can_create = true,
156                       llvm::Optional<lldb::ScriptLanguage> language = {});
157
158  lldb::ListenerSP GetListener() { return m_listener_sp; }
159
160  // This returns the Debugger's scratch source manager.  It won't be able to
161  // look up files in debug information, but it can look up files by absolute
162  // path and display them to you. To get the target's source manager, call
163  // GetSourceManager on the target instead.
164  SourceManager &GetSourceManager();
165
166  lldb::TargetSP GetSelectedTarget() {
167    return m_target_list.GetSelectedTarget();
168  }
169
170  ExecutionContext GetSelectedExecutionContext();
171  /// Get accessor for the target list.
172  ///
173  /// The target list is part of the global debugger object. This the single
174  /// debugger shared instance to control where targets get created and to
175  /// allow for tracking and searching for targets based on certain criteria.
176  ///
177  /// \return
178  ///     A global shared target list.
179  TargetList &GetTargetList() { return m_target_list; }
180
181  PlatformList &GetPlatformList() { return m_platform_list; }
182
183  void DispatchInputInterrupt();
184
185  void DispatchInputEndOfFile();
186
187  // If any of the streams are not set, set them to the in/out/err stream of
188  // the top most input reader to ensure they at least have something
189  void AdoptTopIOHandlerFilesIfInvalid(lldb::FileSP &in,
190                                       lldb::StreamFileSP &out,
191                                       lldb::StreamFileSP &err);
192
193  /// Run the given IO handler and return immediately.
194  void RunIOHandlerAsync(const lldb::IOHandlerSP &reader_sp,
195                         bool cancel_top_handler = true);
196
197  /// Run the given IO handler and block until it's complete.
198  void RunIOHandlerSync(const lldb::IOHandlerSP &reader_sp);
199
200  ///  Remove the given IO handler if it's currently active.
201  bool RemoveIOHandler(const lldb::IOHandlerSP &reader_sp);
202
203  bool IsTopIOHandler(const lldb::IOHandlerSP &reader_sp);
204
205  bool CheckTopIOHandlerTypes(IOHandler::Type top_type,
206                              IOHandler::Type second_top_type);
207
208  void PrintAsync(const char *s, size_t len, bool is_stdout);
209
210  ConstString GetTopIOHandlerControlSequence(char ch);
211
212  const char *GetIOHandlerCommandPrefix();
213
214  const char *GetIOHandlerHelpPrologue();
215
216  void ClearIOHandlers();
217
218  bool GetCloseInputOnEOF() const;
219
220  void SetCloseInputOnEOF(bool b);
221
222  bool EnableLog(llvm::StringRef channel,
223                 llvm::ArrayRef<const char *> categories,
224                 llvm::StringRef log_file, uint32_t log_options,
225                 llvm::raw_ostream &error_stream);
226
227  void SetLoggingCallback(lldb::LogOutputCallback log_callback, void *baton);
228
229  // Properties Functions
230  enum StopDisassemblyType {
231    eStopDisassemblyTypeNever = 0,
232    eStopDisassemblyTypeNoDebugInfo,
233    eStopDisassemblyTypeNoSource,
234    eStopDisassemblyTypeAlways
235  };
236
237  Status SetPropertyValue(const ExecutionContext *exe_ctx,
238                          VarSetOperationType op, llvm::StringRef property_path,
239                          llvm::StringRef value) override;
240
241  bool GetAutoConfirm() const;
242
243  const FormatEntity::Entry *GetDisassemblyFormat() const;
244
245  const FormatEntity::Entry *GetFrameFormat() const;
246
247  const FormatEntity::Entry *GetFrameFormatUnique() const;
248
249  const FormatEntity::Entry *GetThreadFormat() const;
250
251  const FormatEntity::Entry *GetThreadStopFormat() const;
252
253  lldb::ScriptLanguage GetScriptLanguage() const;
254
255  bool SetScriptLanguage(lldb::ScriptLanguage script_lang);
256
257  uint32_t GetTerminalWidth() const;
258
259  bool SetTerminalWidth(uint32_t term_width);
260
261  llvm::StringRef GetPrompt() const;
262
263  void SetPrompt(llvm::StringRef p);
264  void SetPrompt(const char *) = delete;
265
266  llvm::StringRef GetReproducerPath() const;
267
268  bool GetUseExternalEditor() const;
269
270  bool SetUseExternalEditor(bool use_external_editor_p);
271
272  bool GetUseColor() const;
273
274  bool SetUseColor(bool use_color);
275
276  bool GetUseSourceCache() const;
277
278  bool SetUseSourceCache(bool use_source_cache);
279
280  bool GetHighlightSource() const;
281
282  lldb::StopShowColumn GetStopShowColumn() const;
283
284  llvm::StringRef GetStopShowColumnAnsiPrefix() const;
285
286  llvm::StringRef GetStopShowColumnAnsiSuffix() const;
287
288  uint32_t GetStopSourceLineCount(bool before) const;
289
290  StopDisassemblyType GetStopDisassemblyDisplay() const;
291
292  uint32_t GetDisassemblyLineCount() const;
293
294  llvm::StringRef GetStopShowLineMarkerAnsiPrefix() const;
295
296  llvm::StringRef GetStopShowLineMarkerAnsiSuffix() const;
297
298  bool GetAutoOneLineSummaries() const;
299
300  bool GetAutoIndent() const;
301
302  bool SetAutoIndent(bool b);
303
304  bool GetPrintDecls() const;
305
306  bool SetPrintDecls(bool b);
307
308  uint32_t GetTabSize() const;
309
310  bool SetTabSize(uint32_t tab_size);
311
312  bool GetEscapeNonPrintables() const;
313
314  bool GetNotifyVoid() const;
315
316  ConstString GetInstanceName() { return m_instance_name; }
317
318  bool LoadPlugin(const FileSpec &spec, Status &error);
319
320  void RunIOHandlers();
321
322  bool IsForwardingEvents();
323
324  void EnableForwardEvents(const lldb::ListenerSP &listener_sp);
325
326  void CancelForwardEvents(const lldb::ListenerSP &listener_sp);
327
328  bool IsHandlingEvents() const { return m_event_handler_thread.IsJoinable(); }
329
330  Status RunREPL(lldb::LanguageType language, const char *repl_options);
331
332  // This is for use in the command interpreter, when you either want the
333  // selected target, or if no target is present you want to prime the dummy
334  // target with entities that will be copied over to new targets.
335  Target *GetSelectedOrDummyTarget(bool prefer_dummy = false);
336  Target *GetDummyTarget() { return m_dummy_target_sp.get(); }
337
338  lldb::BroadcasterManagerSP GetBroadcasterManager() {
339    return m_broadcaster_manager_sp;
340  }
341
342protected:
343  friend class CommandInterpreter;
344  friend class REPL;
345
346  bool StartEventHandlerThread();
347
348  void StopEventHandlerThread();
349
350  static lldb::thread_result_t EventHandlerThread(lldb::thread_arg_t arg);
351
352  void PushIOHandler(const lldb::IOHandlerSP &reader_sp,
353                     bool cancel_top_handler = true);
354
355  bool PopIOHandler(const lldb::IOHandlerSP &reader_sp);
356
357  bool HasIOHandlerThread();
358
359  bool StartIOHandlerThread();
360
361  void StopIOHandlerThread();
362
363  void JoinIOHandlerThread();
364
365  static lldb::thread_result_t IOHandlerThread(lldb::thread_arg_t arg);
366
367  void DefaultEventHandler();
368
369  void HandleBreakpointEvent(const lldb::EventSP &event_sp);
370
371  void HandleProcessEvent(const lldb::EventSP &event_sp);
372
373  void HandleThreadEvent(const lldb::EventSP &event_sp);
374
375  // Ensures two threads don't attempt to flush process output in parallel.
376  std::mutex m_output_flush_mutex;
377  void FlushProcessOutput(Process &process, bool flush_stdout,
378                          bool flush_stderr);
379
380  SourceManager::SourceFileCache &GetSourceFileCache() {
381    return m_source_file_cache;
382  }
383
384  void InstanceInitialize();
385
386  // these should never be NULL
387  lldb::FileSP m_input_file_sp;
388  lldb::StreamFileSP m_output_stream_sp;
389  lldb::StreamFileSP m_error_stream_sp;
390
391  /// Used for shadowing the input file when capturing a reproducer.
392  repro::DataRecorder *m_input_recorder;
393
394  lldb::BroadcasterManagerSP m_broadcaster_manager_sp; // The debugger acts as a
395                                                       // broadcaster manager of
396                                                       // last resort.
397  // It needs to get constructed before the target_list or any other member
398  // that might want to broadcast through the debugger.
399
400  TerminalState m_terminal_state;
401  TargetList m_target_list;
402
403  PlatformList m_platform_list;
404  lldb::ListenerSP m_listener_sp;
405  std::unique_ptr<SourceManager> m_source_manager_up; // This is a scratch
406                                                      // source manager that we
407                                                      // return if we have no
408                                                      // targets.
409  SourceManager::SourceFileCache m_source_file_cache; // All the source managers
410                                                      // for targets created in
411                                                      // this debugger used this
412                                                      // shared
413                                                      // source file cache.
414  std::unique_ptr<CommandInterpreter> m_command_interpreter_up;
415
416  std::recursive_mutex m_script_interpreter_mutex;
417  std::array<lldb::ScriptInterpreterSP, lldb::eScriptLanguageUnknown>
418      m_script_interpreters;
419
420  IOHandlerStack m_io_handler_stack;
421  std::recursive_mutex m_io_handler_synchronous_mutex;
422
423  llvm::StringMap<std::weak_ptr<llvm::raw_ostream>> m_log_streams;
424  std::shared_ptr<llvm::raw_ostream> m_log_callback_stream_sp;
425  ConstString m_instance_name;
426  static LoadPluginCallbackType g_load_plugin_callback;
427  typedef std::vector<llvm::sys::DynamicLibrary> LoadedPluginsList;
428  LoadedPluginsList m_loaded_plugins;
429  HostThread m_event_handler_thread;
430  HostThread m_io_handler_thread;
431  Broadcaster m_sync_broadcaster;
432  lldb::ListenerSP m_forward_listener_sp;
433  llvm::once_flag m_clear_once;
434  lldb::TargetSP m_dummy_target_sp;
435
436  // Events for m_sync_broadcaster
437  enum {
438    eBroadcastBitEventThreadIsListening = (1 << 0),
439  };
440
441private:
442  // Use Debugger::CreateInstance() to get a shared pointer to a new debugger
443  // object
444  Debugger(lldb::LogOutputCallback m_log_callback, void *baton);
445
446  Debugger(const Debugger &) = delete;
447  const Debugger &operator=(const Debugger &) = delete;
448};
449
450} // namespace lldb_private
451
452#endif // LLDB_CORE_DEBUGGER_H
453