xref: /llvm-project/lldb/include/lldb/Utility/Log.h (revision cd4b33c9a976543171bb7b3455c485f99cfe654b)
1 //===-- Log.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_UTILITY_LOG_H
10 #define LLDB_UTILITY_LOG_H
11 
12 #include "lldb/Utility/Flags.h"
13 #include "lldb/lldb-defines.h"
14 
15 #include "llvm/ADT/ArrayRef.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/StringMap.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/Support/Error.h"
20 #include "llvm/Support/FormatVariadic.h"
21 #include "llvm/Support/ManagedStatic.h"
22 #include "llvm/Support/RWMutex.h"
23 
24 #include <atomic>
25 #include <cstdarg>
26 #include <cstdint>
27 #include <memory>
28 #include <mutex>
29 #include <string>
30 #include <type_traits>
31 
32 namespace llvm {
33 class raw_ostream;
34 }
35 // Logging Options
36 #define LLDB_LOG_OPTION_VERBOSE (1u << 1)
37 #define LLDB_LOG_OPTION_PREPEND_SEQUENCE (1u << 3)
38 #define LLDB_LOG_OPTION_PREPEND_TIMESTAMP (1u << 4)
39 #define LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD (1u << 5)
40 #define LLDB_LOG_OPTION_PREPEND_THREAD_NAME (1U << 6)
41 #define LLDB_LOG_OPTION_BACKTRACE (1U << 7)
42 #define LLDB_LOG_OPTION_APPEND (1U << 8)
43 #define LLDB_LOG_OPTION_PREPEND_FILE_FUNCTION (1U << 9)
44 
45 // Logging Functions
46 namespace lldb_private {
47 
48 class LogHandler {
49 public:
50   virtual ~LogHandler() = default;
51   virtual void Emit(llvm::StringRef message) = 0;
52 
53   virtual bool isA(const void *ClassID) const { return ClassID == &ID; }
54   static bool classof(const LogHandler *obj) { return obj->isA(&ID); }
55 
56 private:
57   static char ID;
58 };
59 
60 class StreamLogHandler : public LogHandler {
61 public:
62   StreamLogHandler(int fd, bool should_close, size_t buffer_size = 0);
63   ~StreamLogHandler() override;
64 
65   void Emit(llvm::StringRef message) override;
66   void Flush();
67 
68   bool isA(const void *ClassID) const override { return ClassID == &ID; }
69   static bool classof(const LogHandler *obj) { return obj->isA(&ID); }
70 
71 private:
72   std::mutex m_mutex;
73   llvm::raw_fd_ostream m_stream;
74   static char ID;
75 };
76 
77 class CallbackLogHandler : public LogHandler {
78 public:
79   CallbackLogHandler(lldb::LogOutputCallback callback, void *baton);
80 
81   void Emit(llvm::StringRef message) override;
82 
83   bool isA(const void *ClassID) const override { return ClassID == &ID; }
84   static bool classof(const LogHandler *obj) { return obj->isA(&ID); }
85 
86 private:
87   lldb::LogOutputCallback m_callback;
88   void *m_baton;
89   static char ID;
90 };
91 
92 class RotatingLogHandler : public LogHandler {
93 public:
94   RotatingLogHandler(size_t size);
95 
96   void Emit(llvm::StringRef message) override;
97   void Dump(llvm::raw_ostream &stream) const;
98 
99   bool isA(const void *ClassID) const override { return ClassID == &ID; }
100   static bool classof(const LogHandler *obj) { return obj->isA(&ID); }
101 
102 private:
103   size_t NormalizeIndex(size_t i) const;
104   size_t GetNumMessages() const;
105   size_t GetFirstMessageIndex() const;
106 
107   mutable std::mutex m_mutex;
108   std::unique_ptr<std::string[]> m_messages;
109   const size_t m_size = 0;
110   size_t m_next_index = 0;
111   size_t m_total_count = 0;
112   static char ID;
113 };
114 
115 /// A T-style log handler that multiplexes messages to two log handlers.
116 class TeeLogHandler : public LogHandler {
117 public:
118   TeeLogHandler(std::shared_ptr<LogHandler> first_log_handler,
119                 std::shared_ptr<LogHandler> second_log_handler);
120 
121   void Emit(llvm::StringRef message) override;
122 
123   bool isA(const void *ClassID) const override { return ClassID == &ID; }
124   static bool classof(const LogHandler *obj) { return obj->isA(&ID); }
125 
126 private:
127   std::shared_ptr<LogHandler> m_first_log_handler;
128   std::shared_ptr<LogHandler> m_second_log_handler;
129   static char ID;
130 };
131 
132 class Log final {
133 public:
134   /// The underlying type of all log channel enums. Declare them as:
135   /// enum class MyLog : MaskType {
136   ///   Channel0 = Log::ChannelFlag<0>,
137   ///   Channel1 = Log::ChannelFlag<1>,
138   ///   ...,
139   ///   LLVM_MARK_AS_BITMASK_ENUM(LastChannel),
140   /// };
141   using MaskType = uint64_t;
142 
143   template <MaskType Bit>
144   static constexpr MaskType ChannelFlag = MaskType(1) << Bit;
145 
146   // Description of a log channel category.
147   struct Category {
148     llvm::StringLiteral name;
149     llvm::StringLiteral description;
150     MaskType flag;
151 
152     template <typename Cat>
153     constexpr Category(llvm::StringLiteral name,
154                        llvm::StringLiteral description, Cat mask)
155         : name(name), description(description), flag(MaskType(mask)) {
156       static_assert(
157           std::is_same<Log::MaskType, std::underlying_type_t<Cat>>::value);
158     }
159   };
160 
161   // This class describes a log channel. It also encapsulates the behavior
162   // necessary to enable a log channel in an atomic manner.
163   class Channel {
164     std::atomic<Log *> log_ptr;
165     friend class Log;
166 
167   public:
168     const llvm::ArrayRef<Category> categories;
169     const MaskType default_flags;
170 
171     template <typename Cat>
172     constexpr Channel(llvm::ArrayRef<Log::Category> categories,
173                       Cat default_flags)
174         : log_ptr(nullptr), categories(categories),
175           default_flags(MaskType(default_flags)) {
176       static_assert(
177           std::is_same<Log::MaskType, std::underlying_type_t<Cat>>::value);
178     }
179 
180     // This function is safe to call at any time. If the channel is disabled
181     // after (or concurrently with) this function returning a non-null Log
182     // pointer, it is still safe to attempt to write to the Log object -- the
183     // output will be discarded.
184     Log *GetLog(MaskType mask) {
185       Log *log = log_ptr.load(std::memory_order_relaxed);
186       if (log && ((log->GetMask() & mask) != 0))
187         return log;
188       return nullptr;
189     }
190   };
191 
192 
193   // Static accessors for logging channels
194   static void Register(llvm::StringRef name, Channel &channel);
195   static void Unregister(llvm::StringRef name);
196 
197   static bool
198   EnableLogChannel(const std::shared_ptr<LogHandler> &log_handler_sp,
199                    uint32_t log_options, llvm::StringRef channel,
200                    llvm::ArrayRef<const char *> categories,
201                    llvm::raw_ostream &error_stream);
202 
203   static bool DisableLogChannel(llvm::StringRef channel,
204                                 llvm::ArrayRef<const char *> categories,
205                                 llvm::raw_ostream &error_stream);
206 
207   static bool DumpLogChannel(llvm::StringRef channel,
208                              llvm::raw_ostream &output_stream,
209                              llvm::raw_ostream &error_stream);
210 
211   static bool ListChannelCategories(llvm::StringRef channel,
212                                     llvm::raw_ostream &stream);
213 
214   /// Returns the list of log channels.
215   static std::vector<llvm::StringRef> ListChannels();
216   /// Calls the given lambda for every category in the given channel.
217   /// If no channel with the given name exists, lambda is never called.
218   static void ForEachChannelCategory(
219       llvm::StringRef channel,
220       llvm::function_ref<void(llvm::StringRef, llvm::StringRef)> lambda);
221 
222   static void DisableAllLogChannels();
223 
224   static void ListAllLogChannels(llvm::raw_ostream &stream);
225 
226   // Member functions
227   //
228   // These functions are safe to call at any time you have a Log* obtained from
229   // the Channel class. If logging is disabled between you obtaining the Log
230   // object and writing to it, the output will be silently discarded.
231   Log(Channel &channel) : m_channel(channel) {}
232   ~Log() = default;
233 
234   void PutCString(const char *cstr);
235   void PutString(llvm::StringRef str);
236 
237   template <typename... Args>
238   void Format(llvm::StringRef file, llvm::StringRef function,
239               const char *format, Args &&... args) {
240     Format(file, function, llvm::formatv(format, std::forward<Args>(args)...));
241   }
242 
243   template <typename... Args>
244   void FormatError(llvm::Error error, llvm::StringRef file,
245                    llvm::StringRef function, const char *format,
246                    Args &&... args) {
247     Format(file, function,
248            llvm::formatv(format, llvm::toString(std::move(error)),
249                          std::forward<Args>(args)...));
250   }
251 
252   void Formatf(llvm::StringRef file, llvm::StringRef function,
253                const char *format, ...) __attribute__((format(printf, 4, 5)));
254 
255   /// Prefer using LLDB_LOGF whenever possible.
256   void Printf(const char *format, ...) __attribute__((format(printf, 2, 3)));
257 
258   void Error(const char *fmt, ...) __attribute__((format(printf, 2, 3)));
259 
260   void Verbose(const char *fmt, ...) __attribute__((format(printf, 2, 3)));
261 
262   void Warning(const char *fmt, ...) __attribute__((format(printf, 2, 3)));
263 
264   const Flags GetOptions() const;
265 
266   MaskType GetMask() const;
267 
268   bool GetVerbose() const;
269 
270   void VAPrintf(const char *format, va_list args);
271   void VAError(const char *format, va_list args);
272   void VAFormatf(llvm::StringRef file, llvm::StringRef function,
273                  const char *format, va_list args);
274 
275   void Enable(const std::shared_ptr<LogHandler> &handler_sp,
276               std::optional<MaskType> flags = std::nullopt,
277               uint32_t options = 0);
278 
279   void Disable(std::optional<MaskType> flags = std::nullopt);
280 
281 private:
282   Channel &m_channel;
283 
284   // The mutex makes sure enable/disable operations are thread-safe. The
285   // options and mask variables are atomic to enable their reading in
286   // Channel::GetLogIfAny without taking the mutex to speed up the fast path.
287   // Their modification however, is still protected by this mutex.
288   llvm::sys::RWMutex m_mutex;
289 
290   std::shared_ptr<LogHandler> m_handler;
291   std::atomic<uint32_t> m_options{0};
292   std::atomic<MaskType> m_mask{0};
293 
294   void WriteHeader(llvm::raw_ostream &OS, llvm::StringRef file,
295                    llvm::StringRef function);
296   void WriteMessage(llvm::StringRef message);
297 
298   void Format(llvm::StringRef file, llvm::StringRef function,
299               const llvm::formatv_object_base &payload);
300 
301   std::shared_ptr<LogHandler> GetHandler() {
302     llvm::sys::ScopedReader lock(m_mutex);
303     return m_handler;
304   }
305 
306   bool Dump(llvm::raw_ostream &stream);
307 
308   typedef llvm::StringMap<Log> ChannelMap;
309   static llvm::ManagedStatic<ChannelMap> g_channel_map;
310 
311   static void ForEachCategory(
312       const Log::ChannelMap::value_type &entry,
313       llvm::function_ref<void(llvm::StringRef, llvm::StringRef)> lambda);
314 
315   static void ListCategories(llvm::raw_ostream &stream,
316                              const ChannelMap::value_type &entry);
317   static Log::MaskType GetFlags(llvm::raw_ostream &stream,
318                                 const ChannelMap::value_type &entry,
319                                 llvm::ArrayRef<const char *> categories);
320 
321   Log(const Log &) = delete;
322   void operator=(const Log &) = delete;
323 };
324 
325 // Must be specialized for a particular log type.
326 template <typename Cat> Log::Channel &LogChannelFor() = delete;
327 
328 /// Retrieve the Log object for the channel associated with the given log enum.
329 ///
330 /// Returns a valid Log object if any of the provided categories are enabled.
331 /// Otherwise, returns nullptr.
332 template <typename Cat> Log *GetLog(Cat mask) {
333   static_assert(
334       std::is_same<Log::MaskType, std::underlying_type_t<Cat>>::value);
335   return LogChannelFor<Cat>().GetLog(Log::MaskType(mask));
336 }
337 
338 /// Getter and setter for the error log (see g_error_log).
339 /// The error log is set to the system log in SystemInitializerFull. We can't
340 /// use the system log directly because that would violate the layering between
341 /// Utility and Host.
342 /// @{
343 void SetLLDBErrorLog(Log *log);
344 Log *GetLLDBErrorLog();
345 /// @}
346 
347 } // namespace lldb_private
348 
349 /// The LLDB_LOG* macros defined below are the way to emit log messages.
350 ///
351 /// Note that the macros surround the arguments in a check for the log
352 /// being on, so you can freely call methods in arguments without affecting
353 /// the non-log execution flow.
354 ///
355 /// If you need to do more complex computations to prepare the log message
356 /// be sure to add your own if (log) check, since we don't want logging to
357 /// have any effect when not on.
358 ///
359 /// However, the LLDB_LOG macro uses the llvm::formatv system (see the
360 /// ProgrammersManual page in the llvm docs for more details).  This allows
361 /// the use of "format_providers" to auto-format datatypes, and there are
362 /// already formatters for some of the llvm and lldb datatypes.
363 ///
364 /// So if you need to do non-trivial formatting of one of these types, be
365 /// sure to grep the lldb and llvm sources for "format_provider" to see if
366 /// there is already a formatter before doing in situ formatting, and if
367 /// possible add a provider if one does not already exist.
368 
369 #define LLDB_LOG(log, ...)                                                     \
370   do {                                                                         \
371     ::lldb_private::Log *log_private = (log);                                  \
372     if (log_private)                                                           \
373       log_private->Format(__FILE__, __func__, __VA_ARGS__);                    \
374   } while (0)
375 
376 #define LLDB_LOGF(log, ...)                                                    \
377   do {                                                                         \
378     ::lldb_private::Log *log_private = (log);                                  \
379     if (log_private)                                                           \
380       log_private->Formatf(__FILE__, __func__, __VA_ARGS__);                   \
381   } while (0)
382 
383 #define LLDB_LOGV(log, ...)                                                    \
384   do {                                                                         \
385     ::lldb_private::Log *log_private = (log);                                  \
386     if (log_private && log_private->GetVerbose())                              \
387       log_private->Format(__FILE__, __func__, __VA_ARGS__);                    \
388   } while (0)
389 
390 // Write message to log, if error is set. In the log message refer to the error
391 // with {0}. Error is cleared regardless of whether logging is enabled.
392 #define LLDB_LOG_ERROR(log, error, ...)                                        \
393   do {                                                                         \
394     ::lldb_private::Log *log_private = (log);                                  \
395     ::llvm::Error error_private = (error);                                     \
396     if (!log_private)                                                          \
397       log_private = lldb_private::GetLLDBErrorLog();                           \
398     if (log_private && error_private) {                                        \
399       log_private->FormatError(::std::move(error_private), __FILE__, __func__, \
400                                __VA_ARGS__);                                   \
401     } else                                                                     \
402       ::llvm::consumeError(::std::move(error_private));                        \
403   } while (0)
404 
405 // Write message to the verbose log, if error is set. In the log
406 // message refer to the error with {0}. Error is cleared regardless of
407 // whether logging is enabled.
408 #define LLDB_LOG_ERRORV(log, error, ...)                                       \
409   do {                                                                         \
410     ::lldb_private::Log *log_private = (log);                                  \
411     ::llvm::Error error_private = (error);                                     \
412     if (log_private && log_private->GetVerbose() && error_private) {           \
413       log_private->FormatError(::std::move(error_private), __FILE__, __func__, \
414                                __VA_ARGS__);                                   \
415     } else                                                                     \
416       ::llvm::consumeError(::std::move(error_private));                        \
417   } while (0)
418 
419 #endif // LLDB_UTILITY_LOG_H
420