LLDB mainline
Log.cpp
Go to the documentation of this file.
1//===-- Log.cpp -----------------------------------------------------------===//
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#include "lldb/Utility/Log.h"
11
12#include "llvm/ADT/SmallString.h"
13#include "llvm/ADT/Twine.h"
14#include "llvm/ADT/iterator.h"
15
16#include "llvm/Support/Casting.h"
17#include "llvm/Support/Chrono.h"
18#include "llvm/Support/ManagedStatic.h"
19#include "llvm/Support/Path.h"
20#include "llvm/Support/Signals.h"
21#include "llvm/Support/Threading.h"
22#include "llvm/Support/raw_ostream.h"
23
24#include <chrono>
25#include <cstdarg>
26#include <mutex>
27#include <utility>
28
29#include <cassert>
30#if defined(_WIN32)
31#include <process.h>
32#else
33#include <unistd.h>
34#endif
35
36using namespace lldb_private;
37
43
44llvm::ManagedStatic<Log::ChannelMap> Log::g_channel_map;
45
46// The error log is used by LLDB_LOG_ERROR. If the given log channel passed to
47// LLDB_LOG_ERROR is not enabled, error messages are logged to the error log.
48static std::atomic<Log *> g_error_log = nullptr;
49
51 const Log::ChannelMap::value_type &entry,
52 llvm::function_ref<void(llvm::StringRef, llvm::StringRef)> lambda) {
53 lambda("all", "all available logging categories");
54 lambda("default", "default set of logging categories");
55 for (const auto &category : entry.second.m_channel.categories)
56 lambda(category.name, category.description);
57}
58
59void Log::ListCategories(llvm::raw_ostream &stream,
60 const ChannelMap::value_type &entry) {
61 stream << llvm::formatv("Logging categories for '{0}':\n", entry.first());
62 ForEachCategory(entry,
63 [&stream](llvm::StringRef name, llvm::StringRef description) {
64 stream << llvm::formatv(" {0} - {1}\n", name, description);
65 });
66}
67
68Log::MaskType Log::GetFlags(llvm::raw_ostream &stream,
69 const ChannelMap::value_type &entry,
70 llvm::ArrayRef<const char *> categories) {
71 bool list_categories = false;
72 Log::MaskType flags = 0;
73 for (const char *category : categories) {
74 if (llvm::StringRef("all").equals_insensitive(category)) {
75 flags |= std::numeric_limits<Log::MaskType>::max();
76 continue;
77 }
78 if (llvm::StringRef("default").equals_insensitive(category)) {
79 flags |= entry.second.m_channel.default_flags;
80 continue;
81 }
82 auto cat = llvm::find_if(entry.second.m_channel.categories,
83 [&](const Log::Category &c) {
84 return c.name.equals_insensitive(category);
85 });
86 if (cat != entry.second.m_channel.categories.end()) {
87 flags |= cat->flag;
88 continue;
89 }
90 stream << llvm::formatv("error: unrecognized log category '{0}'\n",
91 category);
92 list_categories = true;
93 }
94 if (list_categories)
95 ListCategories(stream, entry);
96 return flags;
97}
98
99void Log::Enable(const std::shared_ptr<LogHandler> &handler_sp,
100 std::optional<Log::MaskType> flags, uint32_t options) {
101 llvm::sys::ScopedWriter lock(m_mutex);
102
103 if (!flags)
104 flags = m_channel.default_flags;
105
106 MaskType mask = m_mask.fetch_or(*flags, std::memory_order_relaxed);
107 if (mask | *flags) {
108 m_options.store(options, std::memory_order_relaxed);
109 m_handler = handler_sp;
110 m_channel.log_ptr.store(this, std::memory_order_relaxed);
111 }
112}
113
114void Log::Disable(std::optional<Log::MaskType> flags) {
115 llvm::sys::ScopedWriter lock(m_mutex);
116
117 if (!flags)
118 flags = std::numeric_limits<MaskType>::max();
119
120 MaskType mask = m_mask.fetch_and(~(*flags), std::memory_order_relaxed);
121 if (!(mask & ~(*flags))) {
122 m_handler.reset();
123 m_channel.log_ptr.store(nullptr, std::memory_order_relaxed);
124 }
125}
126
127bool Log::Dump(llvm::raw_ostream &output_stream) {
128 llvm::sys::ScopedReader lock(m_mutex);
129 if (RotatingLogHandler *handler =
130 llvm::dyn_cast_or_null<RotatingLogHandler>(m_handler.get())) {
131 handler->Dump(output_stream);
132 return true;
133 }
134 return false;
135}
136
137const Flags Log::GetOptions() const {
138 return m_options.load(std::memory_order_relaxed);
139}
140
142 return m_mask.load(std::memory_order_relaxed);
143}
144
145void Log::PutCString(const char *cstr) { PutString(cstr); }
146
147void Log::PutString(llvm::StringRef str) {
148 std::string FinalMessage;
149 llvm::raw_string_ostream Stream(FinalMessage);
150 WriteHeader(Stream, "", "");
151 Stream << str << "\n";
152 WriteMessage(FinalMessage);
153}
154
155// Simple variable argument logging with flags.
156void Log::Printf(const char *format, ...) {
157 va_list args;
158 va_start(args, format);
159 VAPrintf(format, args);
160 va_end(args);
161}
162
163void Log::VAPrintf(const char *format, va_list args) {
164 llvm::SmallString<64> Content;
165 lldb_private::VASprintf(Content, format, args);
166 PutString(Content);
167}
168
169void Log::Formatf(llvm::StringRef file, llvm::StringRef function,
170 const char *format, ...) {
171 va_list args;
172 va_start(args, format);
173 VAFormatf(file, function, format, args);
174 va_end(args);
175}
176
177void Log::VAFormatf(llvm::StringRef file, llvm::StringRef function,
178 const char *format, va_list args) {
179 llvm::SmallString<64> Content;
180 lldb_private::VASprintf(Content, format, args);
181 Format(file, function, llvm::formatv("{0}", Content));
182}
183
184// Printing of warnings that are not fatal only if verbose mode is enabled.
185void Log::Verbose(const char *format, ...) {
186 if (!GetVerbose())
187 return;
188
189 va_list args;
190 va_start(args, format);
191 VAPrintf(format, args);
192 va_end(args);
193}
194
195void Log::Register(llvm::StringRef name, Channel &channel) {
196 auto iter = g_channel_map->try_emplace(name, channel);
197 assert(iter.second == true);
199}
200
201void Log::Unregister(llvm::StringRef name) {
202 auto iter = g_channel_map->find(name);
203 assert(iter != g_channel_map->end());
204 iter->second.Disable(std::numeric_limits<MaskType>::max());
205 g_channel_map->erase(iter);
206}
207
208bool Log::EnableLogChannel(const std::shared_ptr<LogHandler> &log_handler_sp,
209 uint32_t log_options, llvm::StringRef channel,
210 llvm::ArrayRef<const char *> categories,
211 llvm::raw_ostream &error_stream) {
212 auto iter = g_channel_map->find(channel);
213 if (iter == g_channel_map->end()) {
214 error_stream << llvm::formatv("Invalid log channel '{0}'.\n", channel);
215 return false;
216 }
217
218 auto flags = categories.empty() ? std::optional<MaskType>{}
219 : GetFlags(error_stream, *iter, categories);
220
221 iter->second.Enable(log_handler_sp, flags, log_options);
222 return true;
223}
224
225bool Log::DisableLogChannel(llvm::StringRef channel,
226 llvm::ArrayRef<const char *> categories,
227 llvm::raw_ostream &error_stream) {
228 auto iter = g_channel_map->find(channel);
229 if (iter == g_channel_map->end()) {
230 error_stream << llvm::formatv("Invalid log channel '{0}'.\n", channel);
231 return false;
232 }
233
234 auto flags = categories.empty() ? std::optional<MaskType>{}
235 : GetFlags(error_stream, *iter, categories);
236
237 iter->second.Disable(flags);
238 return true;
239}
240
241bool Log::DumpLogChannel(llvm::StringRef channel,
242 llvm::raw_ostream &output_stream,
243 llvm::raw_ostream &error_stream) {
244 auto iter = g_channel_map->find(channel);
245 if (iter == g_channel_map->end()) {
246 error_stream << llvm::formatv("Invalid log channel '{0}'.\n", channel);
247 return false;
248 }
249 if (!iter->second.Dump(output_stream)) {
250 error_stream << llvm::formatv(
251 "log channel '{0}' does not support dumping.\n", channel);
252 return false;
253 }
254 return true;
255}
256
257bool Log::ListChannelCategories(llvm::StringRef channel,
258 llvm::raw_ostream &stream) {
259 auto ch = g_channel_map->find(channel);
260 if (ch == g_channel_map->end()) {
261 stream << llvm::formatv("Invalid log channel '{0}'.\n", channel);
262 return false;
263 }
264 ListCategories(stream, *ch);
265 return true;
266}
267
269 for (auto &entry : *g_channel_map)
270 entry.second.Disable(std::numeric_limits<MaskType>::max());
271}
272
274 llvm::StringRef channel,
275 llvm::function_ref<void(llvm::StringRef, llvm::StringRef)> lambda) {
276 auto ch = g_channel_map->find(channel);
277 if (ch == g_channel_map->end())
278 return;
279
280 ForEachCategory(*ch, lambda);
281}
282
283std::vector<llvm::StringRef> Log::ListChannels() {
284 std::vector<llvm::StringRef> result;
285 for (const auto &channel : *g_channel_map)
286 result.push_back(channel.first());
287 return result;
288}
289
290void Log::ListAllLogChannels(llvm::raw_ostream &stream) {
291 if (g_channel_map->empty()) {
292 stream << "No logging channels are currently registered.\n";
293 return;
294 }
295
296 for (const auto &channel : *g_channel_map)
297 ListCategories(stream, channel);
298}
299
300bool Log::GetVerbose() const {
301 return m_options.load(std::memory_order_relaxed) & LLDB_LOG_OPTION_VERBOSE;
302}
303
304void Log::WriteHeader(llvm::raw_ostream &OS, llvm::StringRef file,
305 llvm::StringRef function) {
306 Flags options = GetOptions();
307 static uint32_t g_sequence_id = 0;
308 // Add a sequence ID if requested
310 OS << ++g_sequence_id << " ";
311
312 // Timestamp if requested
314 auto now = std::chrono::duration<double>(
315 std::chrono::system_clock::now().time_since_epoch());
316 OS << llvm::formatv("{0:f9} ", now.count());
317 }
318
319 // Add the process and thread if requested
321 OS << llvm::formatv("[{0,0+4}/{1,0+4}] ", getpid(),
322 llvm::get_threadid());
323
324 // Add the thread name if requested
326 llvm::SmallString<32> thread_name;
327 llvm::get_thread_name(thread_name);
328
329 llvm::SmallString<12> format_str;
330 llvm::raw_svector_ostream format_os(format_str);
331 format_os << "{0,-" << llvm::alignTo<16>(thread_name.size()) << "} ";
332 OS << llvm::formatv(format_str.c_str(), thread_name);
333 }
334
335 if (options.Test(LLDB_LOG_OPTION_BACKTRACE))
336 llvm::sys::PrintStackTrace(OS);
337
339 (!file.empty() || !function.empty())) {
340 file = llvm::sys::path::filename(file).take_front(40);
341 function = function.take_front(40);
342 OS << llvm::formatv("{0,-60:60} ", (file + ":" + function).str());
343 }
344}
345
346// If we have a callback registered, then we call the logging callback. If we
347// have a valid file handle, we also log to the file.
348void Log::WriteMessage(llvm::StringRef message) {
349 // Make a copy of our stream shared pointer in case someone disables our log
350 // while we are logging and releases the stream
351 auto handler_sp = GetHandler();
352 if (!handler_sp)
353 return;
354 handler_sp->Emit(message);
355}
356
357void Log::Format(llvm::StringRef file, llvm::StringRef function,
358 const llvm::formatv_object_base &payload) {
359 std::string message_string;
360 llvm::raw_string_ostream message(message_string);
361 WriteHeader(message, file, function);
362 message << payload << "\n";
363 WriteMessage(message_string);
364}
365
366StreamLogHandler::StreamLogHandler(int fd, bool should_close,
367 size_t buffer_size)
368 : m_stream(fd, should_close, buffer_size == 0) {
369 if (buffer_size > 0)
370 m_stream.SetBufferSize(buffer_size);
371}
372
374
376 std::lock_guard<std::mutex> guard(m_mutex);
377 m_stream.flush();
378}
379
380void StreamLogHandler::Emit(llvm::StringRef message) {
381 if (m_stream.GetBufferSize() > 0) {
382 std::lock_guard<std::mutex> guard(m_mutex);
383 m_stream << message;
384 } else {
385 m_stream << message;
386 }
387}
388
390 void *baton)
391 : m_callback(callback), m_baton(baton) {}
392
393void CallbackLogHandler::Emit(llvm::StringRef message) {
394 m_callback(message.data(), m_baton);
395}
396
398 : m_messages(std::make_unique<std::string[]>(size)), m_size(size) {}
399
400void RotatingLogHandler::Emit(llvm::StringRef message) {
401 std::lock_guard<std::mutex> guard(m_mutex);
403 const size_t index = m_next_index;
404 m_next_index = NormalizeIndex(index + 1);
405 m_messages[index] = message.str();
406}
407
408size_t RotatingLogHandler::NormalizeIndex(size_t i) const { return i % m_size; }
409
413
417
418void RotatingLogHandler::Dump(llvm::raw_ostream &stream) const {
419 std::lock_guard<std::mutex> guard(m_mutex);
420 const size_t start_idx = GetFirstMessageIndex();
421 const size_t stop_idx = start_idx + GetNumMessages();
422 for (size_t i = start_idx; i < stop_idx; ++i) {
423 const size_t idx = NormalizeIndex(i);
424 stream << m_messages[idx];
425 }
426 stream.flush();
427}
428
429TeeLogHandler::TeeLogHandler(std::shared_ptr<LogHandler> first_log_handler,
430 std::shared_ptr<LogHandler> second_log_handler)
431 : m_first_log_handler(first_log_handler),
432 m_second_log_handler(second_log_handler) {
433 assert(m_first_log_handler && "first log handler must be valid");
434 assert(m_second_log_handler && "second log handler must be valid");
435}
436
437void TeeLogHandler::Emit(llvm::StringRef message) {
438 m_first_log_handler->Emit(message);
439 m_second_log_handler->Emit(message);
440}
441
443
static std::atomic< Log * > g_error_log
Definition Log.cpp:48
#define LLDB_LOG_OPTION_PREPEND_FILE_FUNCTION
Definition Log.h:43
#define LLDB_LOG_OPTION_BACKTRACE
Definition Log.h:41
#define LLDB_LOG_OPTION_PREPEND_TIMESTAMP
Definition Log.h:38
#define LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD
Definition Log.h:39
#define LLDB_LOG_OPTION_PREPEND_SEQUENCE
Definition Log.h:37
#define LLDB_LOG_OPTION_VERBOSE
Definition Log.h:36
#define LLDB_LOG_OPTION_PREPEND_THREAD_NAME
Definition Log.h:40
lldb::LogOutputCallback m_callback
Definition Log.h:87
CallbackLogHandler(lldb::LogOutputCallback callback, void *baton)
Definition Log.cpp:389
void Emit(llvm::StringRef message) override
Definition Log.cpp:393
A class to manage flags.
Definition Flags.h:22
bool Test(ValueType bit) const
Test a single flag bit.
Definition Flags.h:96
static char ID
Definition Log.h:57
llvm::sys::RWMutex m_mutex
Definition Log.h:283
static void ListCategories(llvm::raw_ostream &stream, const ChannelMap::value_type &entry)
Definition Log.cpp:59
std::shared_ptr< LogHandler > m_handler
Definition Log.h:285
void WriteMessage(llvm::StringRef message)
Definition Log.cpp:348
void PutCString(const char *cstr)
Definition Log.cpp:145
static void ForEachCategory(const Log::ChannelMap::value_type &entry, llvm::function_ref< void(llvm::StringRef, llvm::StringRef)> lambda)
Definition Log.cpp:50
void Formatf(llvm::StringRef file, llvm::StringRef function, const char *format,...) __attribute__((format(printf
Definition Log.cpp:169
uint64_t MaskType
The underlying type of all log channel enums.
Definition Log.h:141
static bool DisableLogChannel(llvm::StringRef channel, llvm::ArrayRef< const char * > categories, llvm::raw_ostream &error_stream)
Definition Log.cpp:225
static void Register(llvm::StringRef name, Channel &channel)
Definition Log.cpp:195
static void ListAllLogChannels(llvm::raw_ostream &stream)
Definition Log.cpp:290
void VAFormatf(llvm::StringRef file, llvm::StringRef function, const char *format, va_list args)
Definition Log.cpp:177
void WriteHeader(llvm::raw_ostream &OS, llvm::StringRef file, llvm::StringRef function)
Definition Log.cpp:304
static bool DumpLogChannel(llvm::StringRef channel, llvm::raw_ostream &output_stream, llvm::raw_ostream &error_stream)
Definition Log.cpp:241
void VAPrintf(const char *format, va_list args)
Definition Log.cpp:163
void Disable(std::optional< MaskType > flags=std::nullopt)
Definition Log.cpp:114
void Format(llvm::StringRef file, llvm::StringRef function, const char *format, Args &&... args)
Definition Log.h:238
static llvm::ManagedStatic< ChannelMap > g_channel_map
Definition Log.h:304
std::shared_ptr< LogHandler > GetHandler()
Definition Log.h:296
std::atomic< MaskType > m_mask
Definition Log.h:287
static void Unregister(llvm::StringRef name)
Definition Log.cpp:201
void Enable(const std::shared_ptr< LogHandler > &handler_sp, std::optional< MaskType > flags=std::nullopt, uint32_t options=0)
Definition Log.cpp:99
static bool ListChannelCategories(llvm::StringRef channel, llvm::raw_ostream &stream)
Definition Log.cpp:257
static void DisableAllLogChannels()
Definition Log.cpp:268
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:273
void void void const Flags GetOptions() const
Definition Log.cpp:137
static bool EnableLogChannel(const std::shared_ptr< LogHandler > &log_handler_sp, uint32_t log_options, llvm::StringRef channel, llvm::ArrayRef< const char * > categories, llvm::raw_ostream &error_stream)
Definition Log.cpp:208
MaskType GetMask() const
Definition Log.cpp:141
static std::vector< llvm::StringRef > ListChannels()
Returns the list of log channels.
Definition Log.cpp:283
static Log::MaskType GetFlags(llvm::raw_ostream &stream, const ChannelMap::value_type &entry, llvm::ArrayRef< const char * > categories)
Definition Log.cpp:68
bool GetVerbose() const
Definition Log.cpp:300
void PutString(llvm::StringRef str)
Definition Log.cpp:147
bool Dump(llvm::raw_ostream &stream)
Definition Log.cpp:127
void void Printf(const char *format,...) __attribute__((format(printf
Prefer using LLDB_LOGF whenever possible.
Definition Log.cpp:156
void void void Verbose(const char *fmt,...) __attribute__((format(printf
Definition Log.cpp:185
std::atomic< uint32_t > m_options
Definition Log.h:286
Channel & m_channel
Definition Log.h:277
void Dump(llvm::raw_ostream &stream) const
Definition Log.cpp:418
std::unique_ptr< std::string[]> m_messages
Definition Log.h:108
void Emit(llvm::StringRef message) override
Definition Log.cpp:400
size_t NormalizeIndex(size_t i) const
Definition Log.cpp:408
size_t GetNumMessages() const
Definition Log.cpp:410
RotatingLogHandler(size_t size)
Definition Log.cpp:397
size_t GetFirstMessageIndex() const
Definition Log.cpp:414
llvm::raw_fd_ostream m_stream
Definition Log.h:73
StreamLogHandler(int fd, bool should_close, size_t buffer_size=0)
Definition Log.cpp:366
void Emit(llvm::StringRef message) override
Definition Log.cpp:380
A stream class that can stream formatted output to a file.
Definition Stream.h:28
void Emit(llvm::StringRef message) override
Definition Log.cpp:437
std::shared_ptr< LogHandler > m_first_log_handler
Definition Log.h:127
TeeLogHandler(std::shared_ptr< LogHandler > first_log_handler, std::shared_ptr< LogHandler > second_log_handler)
Definition Log.cpp:429
std::shared_ptr< LogHandler > m_second_log_handler
Definition Log.h:128
#define UNUSED_IF_ASSERT_DISABLED(x)
A class that represents a running process on the host machine.
bool VASprintf(llvm::SmallVectorImpl< char > &buf, const char *fmt, va_list args)
Definition VASprintf.cpp:19
void SetLLDBErrorLog(Log *log)
Getter and setter for the error log (see g_error_log).
Definition Log.cpp:442
Log * GetLLDBErrorLog()
Definition Log.cpp:444
void(* LogOutputCallback)(const char *, void *baton)
Definition lldb-types.h:73