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"
10 #include "lldb/Utility/VASPrintf.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/Chrono.h"
17 #include "llvm/Support/ManagedStatic.h"
18 #include "llvm/Support/Path.h"
19 #include "llvm/Support/Signals.h"
20 #include "llvm/Support/Threading.h"
21 #include "llvm/Support/raw_ostream.h"
22 
23 #include <chrono>
24 #include <cstdarg>
25 #include <mutex>
26 #include <utility>
27 
28 #include <cassert>
29 #if defined(_WIN32)
30 #include <process.h>
31 #else
32 #include <unistd.h>
33 #endif
34 
35 using namespace lldb_private;
36 
37 llvm::ManagedStatic<Log::ChannelMap> Log::g_channel_map;
38 
39 void Log::ForEachCategory(
40     const Log::ChannelMap::value_type &entry,
41     llvm::function_ref<void(llvm::StringRef, llvm::StringRef)> lambda) {
42   lambda("all", "all available logging categories");
43   lambda("default", "default set of logging categories");
44   for (const auto &category : entry.second.m_channel.categories)
45     lambda(category.name, category.description);
46 }
47 
48 void Log::ListCategories(llvm::raw_ostream &stream,
49                          const ChannelMap::value_type &entry) {
50   stream << llvm::formatv("Logging categories for '{0}':\n", entry.first());
51   ForEachCategory(entry,
52                   [&stream](llvm::StringRef name, llvm::StringRef description) {
53                     stream << llvm::formatv("  {0} - {1}\n", name, description);
54                   });
55 }
56 
57 uint32_t Log::GetFlags(llvm::raw_ostream &stream, const ChannelMap::value_type &entry,
58                          llvm::ArrayRef<const char *> categories) {
59   bool list_categories = false;
60   uint32_t flags = 0;
61   for (const char *category : categories) {
62     if (llvm::StringRef("all").equals_insensitive(category)) {
63       flags |= UINT32_MAX;
64       continue;
65     }
66     if (llvm::StringRef("default").equals_insensitive(category)) {
67       flags |= entry.second.m_channel.default_flags;
68       continue;
69     }
70     auto cat = llvm::find_if(entry.second.m_channel.categories,
71                              [&](const Log::Category &c) {
72                                return c.name.equals_insensitive(category);
73                              });
74     if (cat != entry.second.m_channel.categories.end()) {
75       flags |= cat->flag;
76       continue;
77     }
78     stream << llvm::formatv("error: unrecognized log category '{0}'\n",
79                             category);
80     list_categories = true;
81   }
82   if (list_categories)
83     ListCategories(stream, entry);
84   return flags;
85 }
86 
87 void Log::Enable(const std::shared_ptr<llvm::raw_ostream> &stream_sp,
88                  uint32_t options, uint32_t flags) {
89   llvm::sys::ScopedWriter lock(m_mutex);
90 
91   MaskType mask = m_mask.fetch_or(flags, std::memory_order_relaxed);
92   if (mask | flags) {
93     m_options.store(options, std::memory_order_relaxed);
94     m_stream_sp = stream_sp;
95     m_channel.log_ptr.store(this, std::memory_order_relaxed);
96   }
97 }
98 
99 void Log::Disable(uint32_t flags) {
100   llvm::sys::ScopedWriter lock(m_mutex);
101 
102   MaskType mask = m_mask.fetch_and(~flags, std::memory_order_relaxed);
103   if (!(mask & ~flags)) {
104     m_stream_sp.reset();
105     m_channel.log_ptr.store(nullptr, std::memory_order_relaxed);
106   }
107 }
108 
109 const Flags Log::GetOptions() const {
110   return m_options.load(std::memory_order_relaxed);
111 }
112 
113 const Flags Log::GetMask() const {
114   return m_mask.load(std::memory_order_relaxed);
115 }
116 
117 void Log::PutCString(const char *cstr) { Printf("%s", cstr); }
118 void Log::PutString(llvm::StringRef str) { PutCString(str.str().c_str()); }
119 
120 // Simple variable argument logging with flags.
121 void Log::Printf(const char *format, ...) {
122   va_list args;
123   va_start(args, format);
124   VAPrintf(format, args);
125   va_end(args);
126 }
127 
128 // All logging eventually boils down to this function call. If we have a
129 // callback registered, then we call the logging callback. If we have a valid
130 // file handle, we also log to the file.
131 void Log::VAPrintf(const char *format, va_list args) {
132   llvm::SmallString<64> FinalMessage;
133   llvm::raw_svector_ostream Stream(FinalMessage);
134   WriteHeader(Stream, "", "");
135 
136   llvm::SmallString<64> Content;
137   lldb_private::VASprintf(Content, format, args);
138 
139   Stream << Content << "\n";
140 
141   WriteMessage(std::string(FinalMessage.str()));
142 }
143 
144 // Printing of errors that are not fatal.
145 void Log::Error(const char *format, ...) {
146   va_list args;
147   va_start(args, format);
148   VAError(format, args);
149   va_end(args);
150 }
151 
152 void Log::VAError(const char *format, va_list args) {
153   llvm::SmallString<64> Content;
154   VASprintf(Content, format, args);
155 
156   Printf("error: %s", Content.c_str());
157 }
158 
159 // Printing of warnings that are not fatal only if verbose mode is enabled.
160 void Log::Verbose(const char *format, ...) {
161   if (!GetVerbose())
162     return;
163 
164   va_list args;
165   va_start(args, format);
166   VAPrintf(format, args);
167   va_end(args);
168 }
169 
170 // Printing of warnings that are not fatal.
171 void Log::Warning(const char *format, ...) {
172   llvm::SmallString<64> Content;
173   va_list args;
174   va_start(args, format);
175   VASprintf(Content, format, args);
176   va_end(args);
177 
178   Printf("warning: %s", Content.c_str());
179 }
180 
181 void Log::Initialize() {
182   InitializeLldbChannel();
183 }
184 
185 void Log::Register(llvm::StringRef name, Channel &channel) {
186   auto iter = g_channel_map->try_emplace(name, channel);
187   assert(iter.second == true);
188   (void)iter;
189 }
190 
191 void Log::Unregister(llvm::StringRef name) {
192   auto iter = g_channel_map->find(name);
193   assert(iter != g_channel_map->end());
194   iter->second.Disable(UINT32_MAX);
195   g_channel_map->erase(iter);
196 }
197 
198 bool Log::EnableLogChannel(
199     const std::shared_ptr<llvm::raw_ostream> &log_stream_sp,
200     uint32_t log_options, llvm::StringRef channel,
201     llvm::ArrayRef<const char *> categories, llvm::raw_ostream &error_stream) {
202   auto iter = g_channel_map->find(channel);
203   if (iter == g_channel_map->end()) {
204     error_stream << llvm::formatv("Invalid log channel '{0}'.\n", channel);
205     return false;
206   }
207   uint32_t flags = categories.empty()
208                        ? iter->second.m_channel.default_flags
209                        : GetFlags(error_stream, *iter, categories);
210   iter->second.Enable(log_stream_sp, log_options, flags);
211   return true;
212 }
213 
214 bool Log::DisableLogChannel(llvm::StringRef channel,
215                             llvm::ArrayRef<const char *> categories,
216                             llvm::raw_ostream &error_stream) {
217   auto iter = g_channel_map->find(channel);
218   if (iter == g_channel_map->end()) {
219     error_stream << llvm::formatv("Invalid log channel '{0}'.\n", channel);
220     return false;
221   }
222   uint32_t flags = categories.empty()
223                        ? UINT32_MAX
224                        : GetFlags(error_stream, *iter, categories);
225   iter->second.Disable(flags);
226   return true;
227 }
228 
229 bool Log::ListChannelCategories(llvm::StringRef channel,
230                                 llvm::raw_ostream &stream) {
231   auto ch = g_channel_map->find(channel);
232   if (ch == g_channel_map->end()) {
233     stream << llvm::formatv("Invalid log channel '{0}'.\n", channel);
234     return false;
235   }
236   ListCategories(stream, *ch);
237   return true;
238 }
239 
240 void Log::DisableAllLogChannels() {
241   for (auto &entry : *g_channel_map)
242     entry.second.Disable(UINT32_MAX);
243 }
244 
245 void Log::ForEachChannelCategory(
246     llvm::StringRef channel,
247     llvm::function_ref<void(llvm::StringRef, llvm::StringRef)> lambda) {
248   auto ch = g_channel_map->find(channel);
249   if (ch == g_channel_map->end())
250     return;
251 
252   ForEachCategory(*ch, lambda);
253 }
254 
255 std::vector<llvm::StringRef> Log::ListChannels() {
256   std::vector<llvm::StringRef> result;
257   for (const auto &channel : *g_channel_map)
258     result.push_back(channel.first());
259   return result;
260 }
261 
262 void Log::ListAllLogChannels(llvm::raw_ostream &stream) {
263   if (g_channel_map->empty()) {
264     stream << "No logging channels are currently registered.\n";
265     return;
266   }
267 
268   for (const auto &channel : *g_channel_map)
269     ListCategories(stream, channel);
270 }
271 
272 bool Log::GetVerbose() const {
273   return m_options.load(std::memory_order_relaxed) & LLDB_LOG_OPTION_VERBOSE;
274 }
275 
276 void Log::WriteHeader(llvm::raw_ostream &OS, llvm::StringRef file,
277                       llvm::StringRef function) {
278   Flags options = GetOptions();
279   static uint32_t g_sequence_id = 0;
280   // Add a sequence ID if requested
281   if (options.Test(LLDB_LOG_OPTION_PREPEND_SEQUENCE))
282     OS << ++g_sequence_id << " ";
283 
284   // Timestamp if requested
285   if (options.Test(LLDB_LOG_OPTION_PREPEND_TIMESTAMP)) {
286     auto now = std::chrono::duration<double>(
287         std::chrono::system_clock::now().time_since_epoch());
288     OS << llvm::formatv("{0:f9} ", now.count());
289   }
290 
291   // Add the process and thread if requested
292   if (options.Test(LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD))
293     OS << llvm::formatv("[{0,0+4}/{1,0+4}] ", getpid(),
294                         llvm::get_threadid());
295 
296   // Add the thread name if requested
297   if (options.Test(LLDB_LOG_OPTION_PREPEND_THREAD_NAME)) {
298     llvm::SmallString<32> thread_name;
299     llvm::get_thread_name(thread_name);
300 
301     llvm::SmallString<12> format_str;
302     llvm::raw_svector_ostream format_os(format_str);
303     format_os << "{0,-" << llvm::alignTo<16>(thread_name.size()) << "} ";
304     OS << llvm::formatv(format_str.c_str(), thread_name);
305   }
306 
307   if (options.Test(LLDB_LOG_OPTION_BACKTRACE))
308     llvm::sys::PrintStackTrace(OS);
309 
310   if (options.Test(LLDB_LOG_OPTION_PREPEND_FILE_FUNCTION) &&
311       (!file.empty() || !function.empty())) {
312     file = llvm::sys::path::filename(file).take_front(40);
313     function = function.take_front(40);
314     OS << llvm::formatv("{0,-60:60} ", (file + ":" + function).str());
315   }
316 }
317 
318 void Log::WriteMessage(const std::string &message) {
319   // Make a copy of our stream shared pointer in case someone disables our log
320   // while we are logging and releases the stream
321   auto stream_sp = GetStream();
322   if (!stream_sp)
323     return;
324 
325   Flags options = GetOptions();
326   if (options.Test(LLDB_LOG_OPTION_THREADSAFE)) {
327     static std::recursive_mutex g_LogThreadedMutex;
328     std::lock_guard<std::recursive_mutex> guard(g_LogThreadedMutex);
329     *stream_sp << message;
330     stream_sp->flush();
331   } else {
332     *stream_sp << message;
333     stream_sp->flush();
334   }
335 }
336 
337 void Log::Format(llvm::StringRef file, llvm::StringRef function,
338                  const llvm::formatv_object_base &payload) {
339   std::string message_string;
340   llvm::raw_string_ostream message(message_string);
341   WriteHeader(message, file, function);
342   message << payload << "\n";
343   WriteMessage(message.str());
344 }
345