1 //===-- Log.cpp -------------------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "lldb/Utility/Log.h"
11 #include "lldb/Utility/VASPrintf.h"
13 #include "llvm/ADT/STLExtras.h"
14 #include "llvm/ADT/SmallString.h"
15 #include "llvm/ADT/Twine.h" // for operator+, Twine
16 #include "llvm/ADT/iterator.h" // for iterator_facade_base
18 #include "llvm/Support/Chrono.h"
19 #include "llvm/Support/ManagedStatic.h" // for ManagedStatic
20 #include "llvm/Support/Path.h"
21 #include "llvm/Support/Signals.h"
22 #include "llvm/Support/Threading.h"
23 #include "llvm/Support/raw_ostream.h"
25 #include <chrono> // for duration, system_clock, syst...
28 #include <utility> // for pair
30 #include <assert.h> // for assert
32 #include <process.h> // for getpid
38 using namespace lldb_private;
40 llvm::ManagedStatic<Log::ChannelMap> Log::g_channel_map;
42 void Log::ListCategories(llvm::raw_ostream &stream, const ChannelMap::value_type &entry) {
43 stream << llvm::formatv("Logging categories for '{0}':\n", entry.first());
44 stream << " all - all available logging categories\n";
45 stream << " default - default set of logging categories\n";
46 for (const auto &category : entry.second.m_channel.categories)
47 stream << llvm::formatv(" {0} - {1}\n", category.name,
48 category.description);
51 uint32_t Log::GetFlags(llvm::raw_ostream &stream, const ChannelMap::value_type &entry,
52 llvm::ArrayRef<const char *> categories) {
53 bool list_categories = false;
55 for (const char *category : categories) {
56 if (llvm::StringRef("all").equals_lower(category)) {
60 if (llvm::StringRef("default").equals_lower(category)) {
61 flags |= entry.second.m_channel.default_flags;
64 auto cat = llvm::find_if(
65 entry.second.m_channel.categories,
66 [&](const Log::Category &c) { return c.name.equals_lower(category); });
67 if (cat != entry.second.m_channel.categories.end()) {
71 stream << llvm::formatv("error: unrecognized log category '{0}'\n",
73 list_categories = true;
76 ListCategories(stream, entry);
80 void Log::Enable(const std::shared_ptr<llvm::raw_ostream> &stream_sp,
81 uint32_t options, uint32_t flags) {
82 llvm::sys::ScopedWriter lock(m_mutex);
84 uint32_t mask = m_mask.fetch_or(flags, std::memory_order_relaxed);
86 m_options.store(options, std::memory_order_relaxed);
87 m_stream_sp = stream_sp;
88 m_channel.log_ptr.store(this, std::memory_order_relaxed);
92 void Log::Disable(uint32_t flags) {
93 llvm::sys::ScopedWriter lock(m_mutex);
95 uint32_t mask = m_mask.fetch_and(~flags, std::memory_order_relaxed);
96 if (!(mask & ~flags)) {
98 m_channel.log_ptr.store(nullptr, std::memory_order_relaxed);
102 const Flags Log::GetOptions() const {
103 return m_options.load(std::memory_order_relaxed);
106 const Flags Log::GetMask() const {
107 return m_mask.load(std::memory_order_relaxed);
110 void Log::PutCString(const char *cstr) { Printf("%s", cstr); }
111 void Log::PutString(llvm::StringRef str) { PutCString(str.str().c_str()); }
113 //----------------------------------------------------------------------
114 // Simple variable argument logging with flags.
115 //----------------------------------------------------------------------
116 void Log::Printf(const char *format, ...) {
118 va_start(args, format);
119 VAPrintf(format, args);
123 //----------------------------------------------------------------------
124 // All logging eventually boils down to this function call. If we have a
125 // callback registered, then we call the logging callback. If we have a valid
126 // file handle, we also log to the file.
127 //----------------------------------------------------------------------
128 void Log::VAPrintf(const char *format, va_list args) {
129 llvm::SmallString<64> FinalMessage;
130 llvm::raw_svector_ostream Stream(FinalMessage);
131 WriteHeader(Stream, "", "");
133 llvm::SmallString<64> Content;
134 lldb_private::VASprintf(Content, format, args);
136 Stream << Content << "\n";
138 WriteMessage(FinalMessage.str());
141 //----------------------------------------------------------------------
142 // Printing of errors that are not fatal.
143 //----------------------------------------------------------------------
144 void Log::Error(const char *format, ...) {
146 va_start(args, format);
147 VAError(format, args);
151 void Log::VAError(const char *format, va_list args) {
152 llvm::SmallString<64> Content;
153 VASprintf(Content, format, args);
155 Printf("error: %s", Content.c_str());
158 //----------------------------------------------------------------------
159 // Printing of warnings that are not fatal only if verbose mode is enabled.
160 //----------------------------------------------------------------------
161 void Log::Verbose(const char *format, ...) {
166 va_start(args, format);
167 VAPrintf(format, args);
171 //----------------------------------------------------------------------
172 // Printing of warnings that are not fatal.
173 //----------------------------------------------------------------------
174 void Log::Warning(const char *format, ...) {
175 llvm::SmallString<64> Content;
177 va_start(args, format);
178 VASprintf(Content, format, args);
181 Printf("warning: %s", Content.c_str());
184 void Log::Initialize() {
186 pthread_atfork(nullptr, nullptr, &Log::DisableLoggingChild);
188 InitializeLldbChannel();
191 void Log::Register(llvm::StringRef name, Channel &channel) {
192 auto iter = g_channel_map->try_emplace(name, channel);
193 assert(iter.second == true);
197 void Log::Unregister(llvm::StringRef name) {
198 auto iter = g_channel_map->find(name);
199 assert(iter != g_channel_map->end());
200 iter->second.Disable(UINT32_MAX);
201 g_channel_map->erase(iter);
204 bool Log::EnableLogChannel(
205 const std::shared_ptr<llvm::raw_ostream> &log_stream_sp,
206 uint32_t log_options, llvm::StringRef channel,
207 llvm::ArrayRef<const char *> categories, llvm::raw_ostream &error_stream) {
208 auto iter = g_channel_map->find(channel);
209 if (iter == g_channel_map->end()) {
210 error_stream << llvm::formatv("Invalid log channel '{0}'.\n", channel);
213 uint32_t flags = categories.empty()
214 ? iter->second.m_channel.default_flags
215 : GetFlags(error_stream, *iter, categories);
216 iter->second.Enable(log_stream_sp, log_options, flags);
220 bool Log::DisableLogChannel(llvm::StringRef channel,
221 llvm::ArrayRef<const char *> categories,
222 llvm::raw_ostream &error_stream) {
223 auto iter = g_channel_map->find(channel);
224 if (iter == g_channel_map->end()) {
225 error_stream << llvm::formatv("Invalid log channel '{0}'.\n", channel);
228 uint32_t flags = categories.empty()
230 : GetFlags(error_stream, *iter, categories);
231 iter->second.Disable(flags);
235 bool Log::ListChannelCategories(llvm::StringRef channel,
236 llvm::raw_ostream &stream) {
237 auto ch = g_channel_map->find(channel);
238 if (ch == g_channel_map->end()) {
239 stream << llvm::formatv("Invalid log channel '{0}'.\n", channel);
242 ListCategories(stream, *ch);
246 void Log::DisableAllLogChannels() {
247 for (auto &entry : *g_channel_map)
248 entry.second.Disable(UINT32_MAX);
251 void Log::ListAllLogChannels(llvm::raw_ostream &stream) {
252 if (g_channel_map->empty()) {
253 stream << "No logging channels are currently registered.\n";
257 for (const auto &channel : *g_channel_map)
258 ListCategories(stream, channel);
261 bool Log::GetVerbose() const {
262 return m_options.load(std::memory_order_relaxed) & LLDB_LOG_OPTION_VERBOSE;
265 void Log::WriteHeader(llvm::raw_ostream &OS, llvm::StringRef file,
266 llvm::StringRef function) {
267 Flags options = GetOptions();
268 static uint32_t g_sequence_id = 0;
269 // Add a sequence ID if requested
270 if (options.Test(LLDB_LOG_OPTION_PREPEND_SEQUENCE))
271 OS << ++g_sequence_id << " ";
273 // Timestamp if requested
274 if (options.Test(LLDB_LOG_OPTION_PREPEND_TIMESTAMP)) {
275 auto now = std::chrono::duration<double>(
276 std::chrono::system_clock::now().time_since_epoch());
277 OS << llvm::formatv("{0:f9} ", now.count());
280 // Add the process and thread if requested
281 if (options.Test(LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD))
282 OS << llvm::formatv("[{0,0+4}/{1,0+4}] ", getpid(),
283 llvm::get_threadid());
285 // Add the thread name if requested
286 if (options.Test(LLDB_LOG_OPTION_PREPEND_THREAD_NAME)) {
287 llvm::SmallString<32> thread_name;
288 llvm::get_thread_name(thread_name);
290 llvm::SmallString<12> format_str;
291 llvm::raw_svector_ostream format_os(format_str);
292 format_os << "{0,-" << llvm::alignTo<16>(thread_name.size()) << "} ";
293 OS << llvm::formatv(format_str.c_str(), thread_name);
296 if (options.Test(LLDB_LOG_OPTION_BACKTRACE))
297 llvm::sys::PrintStackTrace(OS);
299 if (options.Test(LLDB_LOG_OPTION_PREPEND_FILE_FUNCTION) &&
300 (!file.empty() || !function.empty())) {
301 file = llvm::sys::path::filename(file).take_front(40);
302 function = function.take_front(40);
303 OS << llvm::formatv("{0,-60:60} ", (file + ":" + function).str());
307 void Log::WriteMessage(const std::string &message) {
308 // Make a copy of our stream shared pointer in case someone disables our log
309 // while we are logging and releases the stream
310 auto stream_sp = GetStream();
314 Flags options = GetOptions();
315 if (options.Test(LLDB_LOG_OPTION_THREADSAFE)) {
316 static std::recursive_mutex g_LogThreadedMutex;
317 std::lock_guard<std::recursive_mutex> guard(g_LogThreadedMutex);
318 *stream_sp << message;
321 *stream_sp << message;
326 void Log::Format(llvm::StringRef file, llvm::StringRef function,
327 const llvm::formatv_object_base &payload) {
328 std::string message_string;
329 llvm::raw_string_ostream message(message_string);
330 WriteHeader(message, file, function);
331 message << payload << "\n";
332 WriteMessage(message.str());
335 void Log::DisableLoggingChild() {
336 // Disable logging by clearing out the atomic variable after forking -- if we
337 // forked while another thread held the channel mutex, we would deadlock when
338 // trying to write to the log.
339 for (auto &c: *g_channel_map)
340 c.second.m_channel.log_ptr.store(nullptr, std::memory_order_relaxed);