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