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 errors that are not fatal.
185void Log::Error(const char *format, ...) {
186 va_list args;
187 va_start(args, format);
188 VAError(format, args);
189 va_end(args);
190}
191
192void Log::VAError(const char *format, va_list args) {
193 llvm::SmallString<64> Content;
194 VASprintf(Content, format, args);
195
196 Printf("error: %s", Content.c_str());
197}
198
199// Printing of warnings that are not fatal only if verbose mode is enabled.
200void Log::Verbose(const char *format, ...) {
201 if (!GetVerbose())
202 return;
203
204 va_list args;
205 va_start(args, format);
206 VAPrintf(format, args);
207 va_end(args);
208}
209
210// Printing of warnings that are not fatal.
211void Log::Warning(const char *format, ...) {
212 llvm::SmallString<64> Content;
213 va_list args;
214 va_start(args, format);
215 VASprintf(Content, format, args);
216 va_end(args);
217
218 Printf("warning: %s", Content.c_str());
219}
220
221void Log::Register(llvm::StringRef name, Channel &channel) {
222 auto iter = g_channel_map->try_emplace(name, channel);
223 assert(iter.second == true);
225}
226
227void Log::Unregister(llvm::StringRef name) {
228 auto iter = g_channel_map->find(name);
229 assert(iter != g_channel_map->end());
230 iter->second.Disable(std::numeric_limits<MaskType>::max());
231 g_channel_map->erase(iter);
232}
233
234bool Log::EnableLogChannel(const std::shared_ptr<LogHandler> &log_handler_sp,
235 uint32_t log_options, llvm::StringRef channel,
236 llvm::ArrayRef<const char *> categories,
237 llvm::raw_ostream &error_stream) {
238 auto iter = g_channel_map->find(channel);
239 if (iter == g_channel_map->end()) {
240 error_stream << llvm::formatv("Invalid log channel '{0}'.\n", channel);
241 return false;
242 }
243
244 auto flags = categories.empty() ? std::optional<MaskType>{}
245 : GetFlags(error_stream, *iter, categories);
246
247 iter->second.Enable(log_handler_sp, flags, log_options);
248 return true;
249}
250
251bool Log::DisableLogChannel(llvm::StringRef channel,
252 llvm::ArrayRef<const char *> categories,
253 llvm::raw_ostream &error_stream) {
254 auto iter = g_channel_map->find(channel);
255 if (iter == g_channel_map->end()) {
256 error_stream << llvm::formatv("Invalid log channel '{0}'.\n", channel);
257 return false;
258 }
259
260 auto flags = categories.empty() ? std::optional<MaskType>{}
261 : GetFlags(error_stream, *iter, categories);
262
263 iter->second.Disable(flags);
264 return true;
265}
266
267bool Log::DumpLogChannel(llvm::StringRef channel,
268 llvm::raw_ostream &output_stream,
269 llvm::raw_ostream &error_stream) {
270 auto iter = g_channel_map->find(channel);
271 if (iter == g_channel_map->end()) {
272 error_stream << llvm::formatv("Invalid log channel '{0}'.\n", channel);
273 return false;
274 }
275 if (!iter->second.Dump(output_stream)) {
276 error_stream << llvm::formatv(
277 "log channel '{0}' does not support dumping.\n", channel);
278 return false;
279 }
280 return true;
281}
282
283bool Log::ListChannelCategories(llvm::StringRef channel,
284 llvm::raw_ostream &stream) {
285 auto ch = g_channel_map->find(channel);
286 if (ch == g_channel_map->end()) {
287 stream << llvm::formatv("Invalid log channel '{0}'.\n", channel);
288 return false;
289 }
290 ListCategories(stream, *ch);
291 return true;
292}
293
295 for (auto &entry : *g_channel_map)
296 entry.second.Disable(std::numeric_limits<MaskType>::max());
297}
298
300 llvm::StringRef channel,
301 llvm::function_ref<void(llvm::StringRef, llvm::StringRef)> lambda) {
302 auto ch = g_channel_map->find(channel);
303 if (ch == g_channel_map->end())
304 return;
305
306 ForEachCategory(*ch, lambda);
307}
308
309std::vector<llvm::StringRef> Log::ListChannels() {
310 std::vector<llvm::StringRef> result;
311 for (const auto &channel : *g_channel_map)
312 result.push_back(channel.first());
313 return result;
314}
315
316void Log::ListAllLogChannels(llvm::raw_ostream &stream) {
317 if (g_channel_map->empty()) {
318 stream << "No logging channels are currently registered.\n";
319 return;
320 }
321
322 for (const auto &channel : *g_channel_map)
323 ListCategories(stream, channel);
324}
325
326bool Log::GetVerbose() const {
327 return m_options.load(std::memory_order_relaxed) & LLDB_LOG_OPTION_VERBOSE;
328}
329
330void Log::WriteHeader(llvm::raw_ostream &OS, llvm::StringRef file,
331 llvm::StringRef function) {
332 Flags options = GetOptions();
333 static uint32_t g_sequence_id = 0;
334 // Add a sequence ID if requested
336 OS << ++g_sequence_id << " ";
337
338 // Timestamp if requested
340 auto now = std::chrono::duration<double>(
341 std::chrono::system_clock::now().time_since_epoch());
342 OS << llvm::formatv("{0:f9} ", now.count());
343 }
344
345 // Add the process and thread if requested
347 OS << llvm::formatv("[{0,0+4}/{1,0+4}] ", getpid(),
348 llvm::get_threadid());
349
350 // Add the thread name if requested
352 llvm::SmallString<32> thread_name;
353 llvm::get_thread_name(thread_name);
354
355 llvm::SmallString<12> format_str;
356 llvm::raw_svector_ostream format_os(format_str);
357 format_os << "{0,-" << llvm::alignTo<16>(thread_name.size()) << "} ";
358 OS << llvm::formatv(format_str.c_str(), thread_name);
359 }
360
361 if (options.Test(LLDB_LOG_OPTION_BACKTRACE))
362 llvm::sys::PrintStackTrace(OS);
363
365 (!file.empty() || !function.empty())) {
366 file = llvm::sys::path::filename(file).take_front(40);
367 function = function.take_front(40);
368 OS << llvm::formatv("{0,-60:60} ", (file + ":" + function).str());
369 }
370}
371
372// If we have a callback registered, then we call the logging callback. If we
373// have a valid file handle, we also log to the file.
374void Log::WriteMessage(llvm::StringRef message) {
375 // Make a copy of our stream shared pointer in case someone disables our log
376 // while we are logging and releases the stream
377 auto handler_sp = GetHandler();
378 if (!handler_sp)
379 return;
380 handler_sp->Emit(message);
381}
382
383void Log::Format(llvm::StringRef file, llvm::StringRef function,
384 const llvm::formatv_object_base &payload) {
385 std::string message_string;
386 llvm::raw_string_ostream message(message_string);
387 WriteHeader(message, file, function);
388 message << payload << "\n";
389 WriteMessage(message_string);
390}
391
392StreamLogHandler::StreamLogHandler(int fd, bool should_close,
393 size_t buffer_size)
394 : m_stream(fd, should_close, buffer_size == 0) {
395 if (buffer_size > 0)
396 m_stream.SetBufferSize(buffer_size);
397}
398
400
402 std::lock_guard<std::mutex> guard(m_mutex);
403 m_stream.flush();
404}
405
406void StreamLogHandler::Emit(llvm::StringRef message) {
407 if (m_stream.GetBufferSize() > 0) {
408 std::lock_guard<std::mutex> guard(m_mutex);
409 m_stream << message;
410 } else {
411 m_stream << message;
412 }
413}
414
416 void *baton)
417 : m_callback(callback), m_baton(baton) {}
418
419void CallbackLogHandler::Emit(llvm::StringRef message) {
420 m_callback(message.data(), m_baton);
421}
422
424 : m_messages(std::make_unique<std::string[]>(size)), m_size(size) {}
425
426void RotatingLogHandler::Emit(llvm::StringRef message) {
427 std::lock_guard<std::mutex> guard(m_mutex);
429 const size_t index = m_next_index;
430 m_next_index = NormalizeIndex(index + 1);
431 m_messages[index] = message.str();
432}
433
434size_t RotatingLogHandler::NormalizeIndex(size_t i) const { return i % m_size; }
435
438}
439
441 return m_total_count < m_size ? 0 : m_next_index;
442}
443
444void RotatingLogHandler::Dump(llvm::raw_ostream &stream) const {
445 std::lock_guard<std::mutex> guard(m_mutex);
446 const size_t start_idx = GetFirstMessageIndex();
447 const size_t stop_idx = start_idx + GetNumMessages();
448 for (size_t i = start_idx; i < stop_idx; ++i) {
449 const size_t idx = NormalizeIndex(i);
450 stream << m_messages[idx];
451 }
452 stream.flush();
453}
454
455TeeLogHandler::TeeLogHandler(std::shared_ptr<LogHandler> first_log_handler,
456 std::shared_ptr<LogHandler> second_log_handler)
457 : m_first_log_handler(first_log_handler),
458 m_second_log_handler(second_log_handler) {
459 assert(m_first_log_handler && "first log handler must be valid");
460 assert(m_second_log_handler && "second log handler must be valid");
461}
462
463void TeeLogHandler::Emit(llvm::StringRef message) {
464 m_first_log_handler->Emit(message);
465 m_second_log_handler->Emit(message);
466}
467
469
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:415
void Emit(llvm::StringRef message) override
Definition: Log.cpp:419
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
std::atomic< Log * > log_ptr
Definition: Log.h:164
const MaskType default_flags
Definition: Log.h:169
llvm::sys::RWMutex m_mutex
Definition: Log.h:288
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:290
void WriteMessage(llvm::StringRef message)
Definition: Log.cpp:374
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:251
static void Register(llvm::StringRef name, Channel &channel)
Definition: Log.cpp:221
static void ListAllLogChannels(llvm::raw_ostream &stream)
Definition: Log.cpp:316
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:330
static bool DumpLogChannel(llvm::StringRef channel, llvm::raw_ostream &output_stream, llvm::raw_ostream &error_stream)
Definition: Log.cpp:267
void VAPrintf(const char *format, va_list args)
Definition: Log.cpp:163
void void void Error(const char *fmt,...) __attribute__((format(printf
Definition: Log.cpp:185
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:309
std::shared_ptr< LogHandler > GetHandler()
Definition: Log.h:301
void void void void void Warning(const char *fmt,...) __attribute__((format(printf
Definition: Log.cpp:211
std::atomic< MaskType > m_mask
Definition: Log.h:292
static void Unregister(llvm::StringRef name)
Definition: Log.cpp:227
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:283
static void DisableAllLogChannels()
Definition: Log.cpp:294
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:299
void void 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:234
MaskType GetMask() const
Definition: Log.cpp:141
void VAError(const char *format, va_list args)
Definition: Log.cpp:192
static std::vector< llvm::StringRef > ListChannels()
Returns the list of log channels.
Definition: Log.cpp:309
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:326
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 void Verbose(const char *fmt,...) __attribute__((format(printf
Definition: Log.cpp:200
std::atomic< uint32_t > m_options
Definition: Log.h:291
Channel & m_channel
Definition: Log.h:282
void Dump(llvm::raw_ostream &stream) const
Definition: Log.cpp:444
std::unique_ptr< std::string[]> m_messages
Definition: Log.h:108
void Emit(llvm::StringRef message) override
Definition: Log.cpp:426
size_t NormalizeIndex(size_t i) const
Definition: Log.cpp:434
size_t GetNumMessages() const
Definition: Log.cpp:436
RotatingLogHandler(size_t size)
Definition: Log.cpp:423
size_t GetFirstMessageIndex() const
Definition: Log.cpp:440
~StreamLogHandler() override
Definition: Log.cpp:399
llvm::raw_fd_ostream m_stream
Definition: Log.h:73
StreamLogHandler(int fd, bool should_close, size_t buffer_size=0)
Definition: Log.cpp:392
void Emit(llvm::StringRef message) override
Definition: Log.cpp:406
A stream class that can stream formatted output to a file.
Definition: Stream.h:28
void Emit(llvm::StringRef message) override
Definition: Log.cpp:463
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:455
std::shared_ptr< LogHandler > m_second_log_handler
Definition: Log.h:128
#define UNUSED_IF_ASSERT_DISABLED(x)
Definition: lldb-defines.h:140
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:468
Log * GetLLDBErrorLog()
Definition: Log.cpp:470
void(* LogOutputCallback)(const char *, void *baton)
Definition: lldb-types.h:73