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