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 liblldb_Debugger_h_
10 #define liblldb_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 
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   ~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   void PushIOHandler(const lldb::IOHandlerSP &reader_sp,
194                      bool cancel_top_handler = true);
195 
196   bool PopIOHandler(const lldb::IOHandlerSP &reader_sp);
197 
198   // Synchronously run an input reader until it is done
199   void RunIOHandler(const lldb::IOHandlerSP &reader_sp);
200 
201   bool IsTopIOHandler(const lldb::IOHandlerSP &reader_sp);
202 
203   bool CheckTopIOHandlerTypes(IOHandler::Type top_type,
204                               IOHandler::Type second_top_type);
205 
206   void PrintAsync(const char *s, size_t len, bool is_stdout);
207 
208   ConstString GetTopIOHandlerControlSequence(char ch);
209 
210   const char *GetIOHandlerCommandPrefix();
211 
212   const char *GetIOHandlerHelpPrologue();
213 
214   void ClearIOHandlers();
215 
216   bool GetCloseInputOnEOF() const;
217 
218   void SetCloseInputOnEOF(bool b);
219 
220   bool EnableLog(llvm::StringRef channel,
221                  llvm::ArrayRef<const char *> categories,
222                  llvm::StringRef log_file, uint32_t log_options,
223                  llvm::raw_ostream &error_stream);
224 
225   void SetLoggingCallback(lldb::LogOutputCallback log_callback, void *baton);
226 
227   // Properties Functions
228   enum StopDisassemblyType {
229     eStopDisassemblyTypeNever = 0,
230     eStopDisassemblyTypeNoDebugInfo,
231     eStopDisassemblyTypeNoSource,
232     eStopDisassemblyTypeAlways
233   };
234 
235   Status SetPropertyValue(const ExecutionContext *exe_ctx,
236                           VarSetOperationType op, llvm::StringRef property_path,
237                           llvm::StringRef value) override;
238 
239   bool GetAutoConfirm() const;
240 
241   const FormatEntity::Entry *GetDisassemblyFormat() const;
242 
243   const FormatEntity::Entry *GetFrameFormat() const;
244 
245   const FormatEntity::Entry *GetFrameFormatUnique() const;
246 
247   const FormatEntity::Entry *GetThreadFormat() const;
248 
249   const FormatEntity::Entry *GetThreadStopFormat() const;
250 
251   lldb::ScriptLanguage GetScriptLanguage() const;
252 
253   bool SetScriptLanguage(lldb::ScriptLanguage script_lang);
254 
255   uint32_t GetTerminalWidth() const;
256 
257   bool SetTerminalWidth(uint32_t term_width);
258 
259   llvm::StringRef GetPrompt() const;
260 
261   void SetPrompt(llvm::StringRef p);
262   void SetPrompt(const char *) = delete;
263 
264   llvm::StringRef GetReproducerPath() const;
265 
266   bool GetUseExternalEditor() const;
267 
268   bool SetUseExternalEditor(bool use_external_editor_p);
269 
270   bool GetUseColor() const;
271 
272   bool SetUseColor(bool use_color);
273 
274   bool GetHighlightSource() const;
275 
276   lldb::StopShowColumn GetStopShowColumn() const;
277 
278   llvm::StringRef GetStopShowColumnAnsiPrefix() const;
279 
280   llvm::StringRef GetStopShowColumnAnsiSuffix() const;
281 
282   uint32_t GetStopSourceLineCount(bool before) const;
283 
284   StopDisassemblyType GetStopDisassemblyDisplay() const;
285 
286   uint32_t GetDisassemblyLineCount() const;
287 
288   bool GetAutoOneLineSummaries() const;
289 
290   bool GetAutoIndent() const;
291 
292   bool SetAutoIndent(bool b);
293 
294   bool GetPrintDecls() const;
295 
296   bool SetPrintDecls(bool b);
297 
298   uint32_t GetTabSize() const;
299 
300   bool SetTabSize(uint32_t tab_size);
301 
302   bool GetEscapeNonPrintables() const;
303 
304   bool GetNotifyVoid() const;
305 
306   ConstString GetInstanceName() { return m_instance_name; }
307 
308   bool LoadPlugin(const FileSpec &spec, Status &error);
309 
310   void ExecuteIOHandlers();
311 
312   bool IsForwardingEvents();
313 
314   void EnableForwardEvents(const lldb::ListenerSP &listener_sp);
315 
316   void CancelForwardEvents(const lldb::ListenerSP &listener_sp);
317 
318   bool IsHandlingEvents() const { return m_event_handler_thread.IsJoinable(); }
319 
320   Status RunREPL(lldb::LanguageType language, const char *repl_options);
321 
322   // This is for use in the command interpreter, when you either want the
323   // selected target, or if no target is present you want to prime the dummy
324   // target with entities that will be copied over to new targets.
325   Target *GetSelectedOrDummyTarget(bool prefer_dummy = false);
326   Target *GetDummyTarget() { return m_dummy_target_sp.get(); }
327 
328   lldb::BroadcasterManagerSP GetBroadcasterManager() {
329     return m_broadcaster_manager_sp;
330   }
331 
332 protected:
333   friend class CommandInterpreter;
334   friend class REPL;
335 
336   bool StartEventHandlerThread();
337 
338   void StopEventHandlerThread();
339 
340   static lldb::thread_result_t EventHandlerThread(lldb::thread_arg_t arg);
341 
342   bool HasIOHandlerThread();
343 
344   bool StartIOHandlerThread();
345 
346   void StopIOHandlerThread();
347 
348   void JoinIOHandlerThread();
349 
350   static lldb::thread_result_t IOHandlerThread(lldb::thread_arg_t arg);
351 
352   void DefaultEventHandler();
353 
354   void HandleBreakpointEvent(const lldb::EventSP &event_sp);
355 
356   void HandleProcessEvent(const lldb::EventSP &event_sp);
357 
358   void HandleThreadEvent(const lldb::EventSP &event_sp);
359 
360   // Ensures two threads don't attempt to flush process output in parallel.
361   std::mutex m_output_flush_mutex;
362   void FlushProcessOutput(Process &process, bool flush_stdout,
363                           bool flush_stderr);
364 
365   SourceManager::SourceFileCache &GetSourceFileCache() {
366     return m_source_file_cache;
367   }
368 
369   void InstanceInitialize();
370 
371   // these should never be NULL
372   lldb::FileSP m_input_file_sp;
373   lldb::StreamFileSP m_output_stream_sp;
374   lldb::StreamFileSP m_error_stream_sp;
375 
376   /// Used for shadowing the input file when capturing a reproducer.
377   repro::DataRecorder *m_input_recorder;
378 
379   lldb::BroadcasterManagerSP m_broadcaster_manager_sp; // The debugger acts as a
380                                                        // broadcaster manager of
381                                                        // last resort.
382   // It needs to get constructed before the target_list or any other member
383   // that might want to broadcast through the debugger.
384 
385   TerminalState m_terminal_state;
386   TargetList m_target_list;
387 
388   PlatformList m_platform_list;
389   lldb::ListenerSP m_listener_sp;
390   std::unique_ptr<SourceManager> m_source_manager_up; // This is a scratch
391                                                       // source manager that we
392                                                       // return if we have no
393                                                       // targets.
394   SourceManager::SourceFileCache m_source_file_cache; // All the source managers
395                                                       // for targets created in
396                                                       // this debugger used this
397                                                       // shared
398                                                       // source file cache.
399   std::unique_ptr<CommandInterpreter> m_command_interpreter_up;
400 
401   std::recursive_mutex m_script_interpreter_mutex;
402   std::array<lldb::ScriptInterpreterSP, lldb::eScriptLanguageUnknown>
403       m_script_interpreters;
404 
405   IOHandlerStack m_input_reader_stack;
406   llvm::StringMap<std::weak_ptr<llvm::raw_ostream>> m_log_streams;
407   std::shared_ptr<llvm::raw_ostream> m_log_callback_stream_sp;
408   ConstString m_instance_name;
409   static LoadPluginCallbackType g_load_plugin_callback;
410   typedef std::vector<llvm::sys::DynamicLibrary> LoadedPluginsList;
411   LoadedPluginsList m_loaded_plugins;
412   HostThread m_event_handler_thread;
413   HostThread m_io_handler_thread;
414   Broadcaster m_sync_broadcaster;
415   lldb::ListenerSP m_forward_listener_sp;
416   llvm::once_flag m_clear_once;
417   lldb::TargetSP m_dummy_target_sp;
418 
419   // Events for m_sync_broadcaster
420   enum {
421     eBroadcastBitEventThreadIsListening = (1 << 0),
422   };
423 
424 private:
425   // Use Debugger::CreateInstance() to get a shared pointer to a new debugger
426   // object
427   Debugger(lldb::LogOutputCallback m_log_callback, void *baton);
428 
429   DISALLOW_COPY_AND_ASSIGN(Debugger);
430 };
431 
432 } // namespace lldb_private
433 
434 #endif // liblldb_Debugger_h_
435