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
31 #if defined(LLVM_ON_WIN32)
32 #include <process.h> // for getpid
37 using namespace lldb_private;
39 llvm::ManagedStatic<Log::ChannelMap> Log::g_channel_map;
41 void Log::ListCategories(llvm::raw_ostream &stream, const ChannelMap::value_type &entry) {
42 stream << llvm::formatv("Logging categories for '{0}':\n", entry.first());
43 stream << " all - all available logging categories\n";
44 stream << " default - default set of logging categories\n";
45 for (const auto &category : entry.second.m_channel.categories)
46 stream << llvm::formatv(" {0} - {1}\n", category.name,
47 category.description);
50 uint32_t Log::GetFlags(llvm::raw_ostream &stream, const ChannelMap::value_type &entry,
51 llvm::ArrayRef<const char *> categories) {
52 bool list_categories = false;
54 for (const char *category : categories) {
55 if (llvm::StringRef("all").equals_lower(category)) {
59 if (llvm::StringRef("default").equals_lower(category)) {
60 flags |= entry.second.m_channel.default_flags;
63 auto cat = llvm::find_if(
64 entry.second.m_channel.categories,
65 [&](const Log::Category &c) { return c.name.equals_lower(category); });
66 if (cat != entry.second.m_channel.categories.end()) {
70 stream << llvm::formatv("error: unrecognized log category '{0}'\n",
72 list_categories = true;
75 ListCategories(stream, entry);
79 void Log::Enable(const std::shared_ptr<llvm::raw_ostream> &stream_sp,
80 uint32_t options, uint32_t flags) {
81 llvm::sys::ScopedWriter lock(m_mutex);
83 uint32_t mask = m_mask.fetch_or(flags, std::memory_order_relaxed);
85 m_options.store(options, std::memory_order_relaxed);
86 m_stream_sp = stream_sp;
87 m_channel.log_ptr.store(this, std::memory_order_relaxed);
91 void Log::Disable(uint32_t flags) {
92 llvm::sys::ScopedWriter lock(m_mutex);
94 uint32_t mask = m_mask.fetch_and(~flags, std::memory_order_relaxed);
95 if (!(mask & ~flags)) {
97 m_channel.log_ptr.store(nullptr, std::memory_order_relaxed);
101 const Flags Log::GetOptions() const {
102 return m_options.load(std::memory_order_relaxed);
105 const Flags Log::GetMask() const {
106 return m_mask.load(std::memory_order_relaxed);
109 void Log::PutCString(const char *cstr) { Printf("%s", cstr); }
110 void Log::PutString(llvm::StringRef str) { PutCString(str.str().c_str()); }
112 //----------------------------------------------------------------------
113 // Simple variable argument logging with flags.
114 //----------------------------------------------------------------------
115 void Log::Printf(const char *format, ...) {
117 va_start(args, format);
118 VAPrintf(format, args);
122 //----------------------------------------------------------------------
123 // All logging eventually boils down to this function call. If we have
124 // a callback registered, then we call the logging callback. If we have
125 // a valid file handle, we also log to the file.
126 //----------------------------------------------------------------------
127 void Log::VAPrintf(const char *format, va_list args) {
128 llvm::SmallString<64> FinalMessage;
129 llvm::raw_svector_ostream Stream(FinalMessage);
130 WriteHeader(Stream, "", "");
132 llvm::SmallString<64> Content;
133 lldb_private::VASprintf(Content, format, args);
135 Stream << Content << "\n";
137 WriteMessage(FinalMessage.str());
140 //----------------------------------------------------------------------
141 // Printing of errors that are not fatal.
142 //----------------------------------------------------------------------
143 void Log::Error(const char *format, ...) {
145 va_start(args, format);
146 VAError(format, args);
150 void Log::VAError(const char *format, va_list args) {
151 llvm::SmallString<64> Content;
152 VASprintf(Content, format, args);
154 Printf("error: %s", Content.c_str());
157 //----------------------------------------------------------------------
158 // Printing of warnings that are not fatal only if verbose mode is
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::Register(llvm::StringRef name, Channel &channel) {
185 auto iter = g_channel_map->try_emplace(name, channel);
186 assert(iter.second == true);
190 void Log::Unregister(llvm::StringRef name) {
191 auto iter = g_channel_map->find(name);
192 assert(iter != g_channel_map->end());
193 iter->second.Disable(UINT32_MAX);
194 g_channel_map->erase(iter);
197 bool Log::EnableLogChannel(
198 const std::shared_ptr<llvm::raw_ostream> &log_stream_sp,
199 uint32_t log_options, llvm::StringRef channel,
200 llvm::ArrayRef<const char *> categories, llvm::raw_ostream &error_stream) {
201 auto iter = g_channel_map->find(channel);
202 if (iter == g_channel_map->end()) {
203 error_stream << llvm::formatv("Invalid log channel '{0}'.\n", channel);
206 uint32_t flags = categories.empty()
207 ? iter->second.m_channel.default_flags
208 : GetFlags(error_stream, *iter, categories);
209 iter->second.Enable(log_stream_sp, log_options, flags);
213 bool Log::DisableLogChannel(llvm::StringRef channel,
214 llvm::ArrayRef<const char *> categories,
215 llvm::raw_ostream &error_stream) {
216 auto iter = g_channel_map->find(channel);
217 if (iter == g_channel_map->end()) {
218 error_stream << llvm::formatv("Invalid log channel '{0}'.\n", channel);
221 uint32_t flags = categories.empty()
223 : GetFlags(error_stream, *iter, categories);
224 iter->second.Disable(flags);
228 bool Log::ListChannelCategories(llvm::StringRef channel,
229 llvm::raw_ostream &stream) {
230 auto ch = g_channel_map->find(channel);
231 if (ch == g_channel_map->end()) {
232 stream << llvm::formatv("Invalid log channel '{0}'.\n", channel);
235 ListCategories(stream, *ch);
239 void Log::DisableAllLogChannels() {
240 for (auto &entry : *g_channel_map)
241 entry.second.Disable(UINT32_MAX);
244 void Log::ListAllLogChannels(llvm::raw_ostream &stream) {
245 if (g_channel_map->empty()) {
246 stream << "No logging channels are currently registered.\n";
250 for (const auto &channel : *g_channel_map)
251 ListCategories(stream, channel);
254 bool Log::GetVerbose() const {
255 return m_options.load(std::memory_order_relaxed) & LLDB_LOG_OPTION_VERBOSE;
258 void Log::WriteHeader(llvm::raw_ostream &OS, llvm::StringRef file,
259 llvm::StringRef function) {
260 Flags options = GetOptions();
261 static uint32_t g_sequence_id = 0;
262 // Add a sequence ID if requested
263 if (options.Test(LLDB_LOG_OPTION_PREPEND_SEQUENCE))
264 OS << ++g_sequence_id << " ";
266 // Timestamp if requested
267 if (options.Test(LLDB_LOG_OPTION_PREPEND_TIMESTAMP)) {
268 auto now = std::chrono::duration<double>(
269 std::chrono::system_clock::now().time_since_epoch());
270 OS << llvm::formatv("{0:f9} ", now.count());
273 // Add the process and thread if requested
274 if (options.Test(LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD))
275 OS << llvm::formatv("[{0,0+4}/{1,0+4}] ", getpid(),
276 llvm::get_threadid());
278 // Add the thread name if requested
279 if (options.Test(LLDB_LOG_OPTION_PREPEND_THREAD_NAME)) {
280 llvm::SmallString<32> thread_name;
281 llvm::get_thread_name(thread_name);
282 if (!thread_name.empty())
286 if (options.Test(LLDB_LOG_OPTION_BACKTRACE))
287 llvm::sys::PrintStackTrace(OS);
289 if (options.Test(LLDB_LOG_OPTION_PREPEND_FILE_FUNCTION) &&
290 (!file.empty() || !function.empty())) {
291 file = llvm::sys::path::filename(file).take_front(40);
292 function = function.take_front(40);
293 OS << llvm::formatv("{0,-60:60} ", (file + ":" + function).str());
297 void Log::WriteMessage(const std::string &message) {
298 // Make a copy of our stream shared pointer in case someone disables our
299 // log while we are logging and releases the stream
300 auto stream_sp = GetStream();
304 Flags options = GetOptions();
305 if (options.Test(LLDB_LOG_OPTION_THREADSAFE)) {
306 static std::recursive_mutex g_LogThreadedMutex;
307 std::lock_guard<std::recursive_mutex> guard(g_LogThreadedMutex);
308 *stream_sp << message;
311 *stream_sp << message;
316 void Log::Format(llvm::StringRef file, llvm::StringRef function,
317 const llvm::formatv_object_base &payload) {
318 std::string message_string;
319 llvm::raw_string_ostream message(message_string);
320 WriteHeader(message, file, function);
321 message << payload << "\n";
322 WriteMessage(message.str());