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 <string>
29 #include <type_traits>
30 
31 namespace llvm {
32 class raw_ostream;
33 }
34 // Logging Options
35 #define LLDB_LOG_OPTION_THREADSAFE (1u << 0)
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 Log final {
49 public:
50   /// The underlying type of all log channel enums. Declare them as:
51   /// enum class MyLog : MaskType {
52   ///   Channel0 = Log::ChannelFlag<0>,
53   ///   Channel1 = Log::ChannelFlag<1>,
54   ///   ...,
55   ///   LLVM_MARK_AS_BITMASK_ENUM(LastChannel),
56   /// };
57   using MaskType = uint64_t;
58 
59   template <MaskType Bit>
60   static constexpr MaskType ChannelFlag = MaskType(1) << Bit;
61 
62   // Description of a log channel category.
63   struct Category {
64     llvm::StringLiteral name;
65     llvm::StringLiteral description;
66     MaskType flag;
67 
68     template <typename Cat>
69     constexpr Category(llvm::StringLiteral name,
70                        llvm::StringLiteral description, Cat mask)
71         : name(name), description(description), flag(MaskType(mask)) {
72       static_assert(
73           std::is_same<Log::MaskType, std::underlying_type_t<Cat>>::value, "");
74     }
75   };
76 
77   // This class describes a log channel. It also encapsulates the behavior
78   // necessary to enable a log channel in an atomic manner.
79   class Channel {
80     std::atomic<Log *> log_ptr;
81     friend class Log;
82 
83   public:
84     const llvm::ArrayRef<Category> categories;
85     const MaskType default_flags;
86 
87     template <typename Cat>
88     constexpr Channel(llvm::ArrayRef<Log::Category> categories,
89                       Cat default_flags)
90         : log_ptr(nullptr), categories(categories),
91           default_flags(MaskType(default_flags)) {
92       static_assert(
93           std::is_same<Log::MaskType, std::underlying_type_t<Cat>>::value, "");
94     }
95 
96     // This function is safe to call at any time. If the channel is disabled
97     // after (or concurrently with) this function returning a non-null Log
98     // pointer, it is still safe to attempt to write to the Log object -- the
99     // output will be discarded.
100     Log *GetLogIfAll(MaskType mask) {
101       Log *log = log_ptr.load(std::memory_order_relaxed);
102       if (log && log->GetMask().AllSet(mask))
103         return log;
104       return nullptr;
105     }
106 
107     // This function is safe to call at any time. If the channel is disabled
108     // after (or concurrently with) this function returning a non-null Log
109     // pointer, it is still safe to attempt to write to the Log object -- the
110     // output will be discarded.
111     Log *GetLogIfAny(MaskType mask) {
112       Log *log = log_ptr.load(std::memory_order_relaxed);
113       if (log && log->GetMask().AnySet(mask))
114         return log;
115       return nullptr;
116     }
117   };
118 
119 
120   static void Initialize();
121 
122   // Static accessors for logging channels
123   static void Register(llvm::StringRef name, Channel &channel);
124   static void Unregister(llvm::StringRef name);
125 
126   static bool
127   EnableLogChannel(const std::shared_ptr<llvm::raw_ostream> &log_stream_sp,
128                    uint32_t log_options, llvm::StringRef channel,
129                    llvm::ArrayRef<const char *> categories,
130                    llvm::raw_ostream &error_stream);
131 
132   static bool DisableLogChannel(llvm::StringRef channel,
133                                 llvm::ArrayRef<const char *> categories,
134                                 llvm::raw_ostream &error_stream);
135 
136   static bool ListChannelCategories(llvm::StringRef channel,
137                                     llvm::raw_ostream &stream);
138 
139   /// Returns the list of log channels.
140   static std::vector<llvm::StringRef> ListChannels();
141   /// Calls the given lambda for every category in the given channel.
142   /// If no channel with the given name exists, lambda is never called.
143   static void ForEachChannelCategory(
144       llvm::StringRef channel,
145       llvm::function_ref<void(llvm::StringRef, llvm::StringRef)> lambda);
146 
147   static void DisableAllLogChannels();
148 
149   static void ListAllLogChannels(llvm::raw_ostream &stream);
150 
151   // Member functions
152   //
153   // These functions are safe to call at any time you have a Log* obtained from
154   // the Channel class. If logging is disabled between you obtaining the Log
155   // object and writing to it, the output will be silently discarded.
156   Log(Channel &channel) : m_channel(channel) {}
157   ~Log() = default;
158 
159   void PutCString(const char *cstr);
160   void PutString(llvm::StringRef str);
161 
162   template <typename... Args>
163   void Format(llvm::StringRef file, llvm::StringRef function,
164               const char *format, Args &&... args) {
165     Format(file, function, llvm::formatv(format, std::forward<Args>(args)...));
166   }
167 
168   template <typename... Args>
169   void FormatError(llvm::Error error, llvm::StringRef file,
170                    llvm::StringRef function, const char *format,
171                    Args &&... args) {
172     Format(file, function,
173            llvm::formatv(format, llvm::toString(std::move(error)),
174                          std::forward<Args>(args)...));
175   }
176 
177   /// Prefer using LLDB_LOGF whenever possible.
178   void Printf(const char *format, ...) __attribute__((format(printf, 2, 3)));
179 
180   void Error(const char *fmt, ...) __attribute__((format(printf, 2, 3)));
181 
182   void Verbose(const char *fmt, ...) __attribute__((format(printf, 2, 3)));
183 
184   void Warning(const char *fmt, ...) __attribute__((format(printf, 2, 3)));
185 
186   const Flags GetOptions() const;
187 
188   const Flags GetMask() const;
189 
190   bool GetVerbose() const;
191 
192   void VAPrintf(const char *format, va_list args);
193   void VAError(const char *format, va_list args);
194 
195 private:
196   Channel &m_channel;
197 
198   // The mutex makes sure enable/disable operations are thread-safe. The
199   // options and mask variables are atomic to enable their reading in
200   // Channel::GetLogIfAny without taking the mutex to speed up the fast path.
201   // Their modification however, is still protected by this mutex.
202   llvm::sys::RWMutex m_mutex;
203 
204   std::shared_ptr<llvm::raw_ostream> m_stream_sp;
205   std::atomic<uint32_t> m_options{0};
206   std::atomic<MaskType> m_mask{0};
207 
208   void WriteHeader(llvm::raw_ostream &OS, llvm::StringRef file,
209                    llvm::StringRef function);
210   void WriteMessage(const std::string &message);
211 
212   void Format(llvm::StringRef file, llvm::StringRef function,
213               const llvm::formatv_object_base &payload);
214 
215   std::shared_ptr<llvm::raw_ostream> GetStream() {
216     llvm::sys::ScopedReader lock(m_mutex);
217     return m_stream_sp;
218   }
219 
220   void Enable(const std::shared_ptr<llvm::raw_ostream> &stream_sp,
221               uint32_t options, uint32_t flags);
222 
223   void Disable(uint32_t flags);
224 
225   typedef llvm::StringMap<Log> ChannelMap;
226   static llvm::ManagedStatic<ChannelMap> g_channel_map;
227 
228   static void ForEachCategory(
229       const Log::ChannelMap::value_type &entry,
230       llvm::function_ref<void(llvm::StringRef, llvm::StringRef)> lambda);
231 
232   static void ListCategories(llvm::raw_ostream &stream,
233                              const ChannelMap::value_type &entry);
234   static uint32_t GetFlags(llvm::raw_ostream &stream, const ChannelMap::value_type &entry,
235                            llvm::ArrayRef<const char *> categories);
236 
237   Log(const Log &) = delete;
238   void operator=(const Log &) = delete;
239 };
240 
241 // Must be specialized for a particular log type.
242 template <typename Cat> Log::Channel &LogChannelFor() = delete;
243 
244 /// Retrieve the Log object for the channel associated with the given log enum.
245 ///
246 /// Returns a valid Log object if any of the provided categories are enabled.
247 /// Otherwise, returns nullptr.
248 template <typename Cat> Log *GetLog(Cat mask) {
249   static_assert(std::is_same<Log::MaskType, std::underlying_type_t<Cat>>::value,
250                 "");
251   return LogChannelFor<Cat>().GetLogIfAny(Log::MaskType(mask));
252 }
253 
254 } // namespace lldb_private
255 
256 /// The LLDB_LOG* macros defined below are the way to emit log messages.
257 ///
258 /// Note that the macros surround the arguments in a check for the log
259 /// being on, so you can freely call methods in arguments without affecting
260 /// the non-log execution flow.
261 ///
262 /// If you need to do more complex computations to prepare the log message
263 /// be sure to add your own if (log) check, since we don't want logging to
264 /// have any effect when not on.
265 ///
266 /// However, the LLDB_LOG macro uses the llvm::formatv system (see the
267 /// ProgrammersManual page in the llvm docs for more details).  This allows
268 /// the use of "format_providers" to auto-format datatypes, and there are
269 /// already formatters for some of the llvm and lldb datatypes.
270 ///
271 /// So if you need to do non-trivial formatting of one of these types, be
272 /// sure to grep the lldb and llvm sources for "format_provider" to see if
273 /// there is already a formatter before doing in situ formatting, and if
274 /// possible add a provider if one does not already exist.
275 
276 #define LLDB_LOG(log, ...)                                                     \
277   do {                                                                         \
278     ::lldb_private::Log *log_private = (log);                                  \
279     if (log_private)                                                           \
280       log_private->Format(__FILE__, __func__, __VA_ARGS__);                    \
281   } while (0)
282 
283 #define LLDB_LOGF(log, ...)                                                    \
284   do {                                                                         \
285     ::lldb_private::Log *log_private = (log);                                  \
286     if (log_private)                                                           \
287       log_private->Printf(__VA_ARGS__);                                        \
288   } while (0)
289 
290 #define LLDB_LOGV(log, ...)                                                    \
291   do {                                                                         \
292     ::lldb_private::Log *log_private = (log);                                  \
293     if (log_private && log_private->GetVerbose())                              \
294       log_private->Format(__FILE__, __func__, __VA_ARGS__);                    \
295   } while (0)
296 
297 // Write message to log, if error is set. In the log message refer to the error
298 // with {0}. Error is cleared regardless of whether logging is enabled.
299 #define LLDB_LOG_ERROR(log, error, ...)                                        \
300   do {                                                                         \
301     ::lldb_private::Log *log_private = (log);                                  \
302     ::llvm::Error error_private = (error);                                     \
303     if (log_private && error_private) {                                        \
304       log_private->FormatError(::std::move(error_private), __FILE__, __func__, \
305                                __VA_ARGS__);                                   \
306     } else                                                                     \
307       ::llvm::consumeError(::std::move(error_private));                        \
308   } while (0)
309 
310 #endif // LLDB_UTILITY_LOG_H
311 
312 // TODO: Remove this and fix includes everywhere.
313 #include "lldb/Utility/Logging.h"
314