Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-05-10 08:42:57

0001 //===-- Log.h ---------------------------------------------------*- C++ -*-===//
0002 //
0003 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
0004 // See https://llvm.org/LICENSE.txt for license information.
0005 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
0006 //
0007 //===----------------------------------------------------------------------===//
0008 
0009 #ifndef LLDB_UTILITY_LOG_H
0010 #define LLDB_UTILITY_LOG_H
0011 
0012 #include "lldb/Utility/Flags.h"
0013 #include "lldb/lldb-defines.h"
0014 
0015 #include "llvm/ADT/ArrayRef.h"
0016 #include "llvm/ADT/STLExtras.h"
0017 #include "llvm/ADT/StringMap.h"
0018 #include "llvm/ADT/StringRef.h"
0019 #include "llvm/Support/Error.h"
0020 #include "llvm/Support/FormatVariadic.h"
0021 #include "llvm/Support/ManagedStatic.h"
0022 #include "llvm/Support/RWMutex.h"
0023 
0024 #include <atomic>
0025 #include <cstdarg>
0026 #include <cstdint>
0027 #include <memory>
0028 #include <mutex>
0029 #include <string>
0030 #include <type_traits>
0031 
0032 namespace llvm {
0033 class raw_ostream;
0034 }
0035 // Logging Options
0036 #define LLDB_LOG_OPTION_VERBOSE (1u << 1)
0037 #define LLDB_LOG_OPTION_PREPEND_SEQUENCE (1u << 3)
0038 #define LLDB_LOG_OPTION_PREPEND_TIMESTAMP (1u << 4)
0039 #define LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD (1u << 5)
0040 #define LLDB_LOG_OPTION_PREPEND_THREAD_NAME (1U << 6)
0041 #define LLDB_LOG_OPTION_BACKTRACE (1U << 7)
0042 #define LLDB_LOG_OPTION_APPEND (1U << 8)
0043 #define LLDB_LOG_OPTION_PREPEND_FILE_FUNCTION (1U << 9)
0044 
0045 // Logging Functions
0046 namespace lldb_private {
0047 
0048 class LogHandler {
0049 public:
0050   virtual ~LogHandler() = default;
0051   virtual void Emit(llvm::StringRef message) = 0;
0052 
0053   virtual bool isA(const void *ClassID) const { return ClassID == &ID; }
0054   static bool classof(const LogHandler *obj) { return obj->isA(&ID); }
0055 
0056 private:
0057   static char ID;
0058 };
0059 
0060 class StreamLogHandler : public LogHandler {
0061 public:
0062   StreamLogHandler(int fd, bool should_close, size_t buffer_size = 0);
0063   ~StreamLogHandler() override;
0064 
0065   void Emit(llvm::StringRef message) override;
0066   void Flush();
0067 
0068   bool isA(const void *ClassID) const override { return ClassID == &ID; }
0069   static bool classof(const LogHandler *obj) { return obj->isA(&ID); }
0070 
0071 private:
0072   std::mutex m_mutex;
0073   llvm::raw_fd_ostream m_stream;
0074   static char ID;
0075 };
0076 
0077 class CallbackLogHandler : public LogHandler {
0078 public:
0079   CallbackLogHandler(lldb::LogOutputCallback callback, void *baton);
0080 
0081   void Emit(llvm::StringRef message) override;
0082 
0083   bool isA(const void *ClassID) const override { return ClassID == &ID; }
0084   static bool classof(const LogHandler *obj) { return obj->isA(&ID); }
0085 
0086 private:
0087   lldb::LogOutputCallback m_callback;
0088   void *m_baton;
0089   static char ID;
0090 };
0091 
0092 class RotatingLogHandler : public LogHandler {
0093 public:
0094   RotatingLogHandler(size_t size);
0095 
0096   void Emit(llvm::StringRef message) override;
0097   void Dump(llvm::raw_ostream &stream) const;
0098 
0099   bool isA(const void *ClassID) const override { return ClassID == &ID; }
0100   static bool classof(const LogHandler *obj) { return obj->isA(&ID); }
0101 
0102 private:
0103   size_t NormalizeIndex(size_t i) const;
0104   size_t GetNumMessages() const;
0105   size_t GetFirstMessageIndex() const;
0106 
0107   mutable std::mutex m_mutex;
0108   std::unique_ptr<std::string[]> m_messages;
0109   const size_t m_size = 0;
0110   size_t m_next_index = 0;
0111   size_t m_total_count = 0;
0112   static char ID;
0113 };
0114 
0115 /// A T-style log handler that multiplexes messages to two log handlers.
0116 class TeeLogHandler : public LogHandler {
0117 public:
0118   TeeLogHandler(std::shared_ptr<LogHandler> first_log_handler,
0119                 std::shared_ptr<LogHandler> second_log_handler);
0120 
0121   void Emit(llvm::StringRef message) override;
0122 
0123   bool isA(const void *ClassID) const override { return ClassID == &ID; }
0124   static bool classof(const LogHandler *obj) { return obj->isA(&ID); }
0125 
0126 private:
0127   std::shared_ptr<LogHandler> m_first_log_handler;
0128   std::shared_ptr<LogHandler> m_second_log_handler;
0129   static char ID;
0130 };
0131 
0132 class Log final {
0133 public:
0134   /// The underlying type of all log channel enums. Declare them as:
0135   /// enum class MyLog : MaskType {
0136   ///   Channel0 = Log::ChannelFlag<0>,
0137   ///   Channel1 = Log::ChannelFlag<1>,
0138   ///   ...,
0139   ///   LLVM_MARK_AS_BITMASK_ENUM(LastChannel),
0140   /// };
0141   using MaskType = uint64_t;
0142 
0143   template <MaskType Bit>
0144   static constexpr MaskType ChannelFlag = MaskType(1) << Bit;
0145 
0146   // Description of a log channel category.
0147   struct Category {
0148     llvm::StringLiteral name;
0149     llvm::StringLiteral description;
0150     MaskType flag;
0151 
0152     template <typename Cat>
0153     constexpr Category(llvm::StringLiteral name,
0154                        llvm::StringLiteral description, Cat mask)
0155         : name(name), description(description), flag(MaskType(mask)) {
0156       static_assert(
0157           std::is_same<Log::MaskType, std::underlying_type_t<Cat>>::value);
0158     }
0159   };
0160 
0161   // This class describes a log channel. It also encapsulates the behavior
0162   // necessary to enable a log channel in an atomic manner.
0163   class Channel {
0164     std::atomic<Log *> log_ptr;
0165     friend class Log;
0166 
0167   public:
0168     const llvm::ArrayRef<Category> categories;
0169     const MaskType default_flags;
0170 
0171     template <typename Cat>
0172     constexpr Channel(llvm::ArrayRef<Log::Category> categories,
0173                       Cat default_flags)
0174         : log_ptr(nullptr), categories(categories),
0175           default_flags(MaskType(default_flags)) {
0176       static_assert(
0177           std::is_same<Log::MaskType, std::underlying_type_t<Cat>>::value);
0178     }
0179 
0180     // This function is safe to call at any time. If the channel is disabled
0181     // after (or concurrently with) this function returning a non-null Log
0182     // pointer, it is still safe to attempt to write to the Log object -- the
0183     // output will be discarded.
0184     Log *GetLog(MaskType mask) {
0185       Log *log = log_ptr.load(std::memory_order_relaxed);
0186       if (log && ((log->GetMask() & mask) != 0))
0187         return log;
0188       return nullptr;
0189     }
0190   };
0191 
0192 
0193   // Static accessors for logging channels
0194   static void Register(llvm::StringRef name, Channel &channel);
0195   static void Unregister(llvm::StringRef name);
0196 
0197   static bool
0198   EnableLogChannel(const std::shared_ptr<LogHandler> &log_handler_sp,
0199                    uint32_t log_options, llvm::StringRef channel,
0200                    llvm::ArrayRef<const char *> categories,
0201                    llvm::raw_ostream &error_stream);
0202 
0203   static bool DisableLogChannel(llvm::StringRef channel,
0204                                 llvm::ArrayRef<const char *> categories,
0205                                 llvm::raw_ostream &error_stream);
0206 
0207   static bool DumpLogChannel(llvm::StringRef channel,
0208                              llvm::raw_ostream &output_stream,
0209                              llvm::raw_ostream &error_stream);
0210 
0211   static bool ListChannelCategories(llvm::StringRef channel,
0212                                     llvm::raw_ostream &stream);
0213 
0214   /// Returns the list of log channels.
0215   static std::vector<llvm::StringRef> ListChannels();
0216   /// Calls the given lambda for every category in the given channel.
0217   /// If no channel with the given name exists, lambda is never called.
0218   static void ForEachChannelCategory(
0219       llvm::StringRef channel,
0220       llvm::function_ref<void(llvm::StringRef, llvm::StringRef)> lambda);
0221 
0222   static void DisableAllLogChannels();
0223 
0224   static void ListAllLogChannels(llvm::raw_ostream &stream);
0225 
0226   // Member functions
0227   //
0228   // These functions are safe to call at any time you have a Log* obtained from
0229   // the Channel class. If logging is disabled between you obtaining the Log
0230   // object and writing to it, the output will be silently discarded.
0231   Log(Channel &channel) : m_channel(channel) {}
0232   ~Log() = default;
0233 
0234   void PutCString(const char *cstr);
0235   void PutString(llvm::StringRef str);
0236 
0237   template <typename... Args>
0238   void Format(llvm::StringRef file, llvm::StringRef function,
0239               const char *format, Args &&... args) {
0240     Format(file, function, llvm::formatv(format, std::forward<Args>(args)...));
0241   }
0242 
0243   template <typename... Args>
0244   void FormatError(llvm::Error error, llvm::StringRef file,
0245                    llvm::StringRef function, const char *format,
0246                    Args &&... args) {
0247     Format(file, function,
0248            llvm::formatv(format, llvm::toString(std::move(error)),
0249                          std::forward<Args>(args)...));
0250   }
0251 
0252   void Formatf(llvm::StringRef file, llvm::StringRef function,
0253                const char *format, ...) __attribute__((format(printf, 4, 5)));
0254 
0255   /// Prefer using LLDB_LOGF whenever possible.
0256   void Printf(const char *format, ...) __attribute__((format(printf, 2, 3)));
0257 
0258   void Error(const char *fmt, ...) __attribute__((format(printf, 2, 3)));
0259 
0260   void Verbose(const char *fmt, ...) __attribute__((format(printf, 2, 3)));
0261 
0262   void Warning(const char *fmt, ...) __attribute__((format(printf, 2, 3)));
0263 
0264   const Flags GetOptions() const;
0265 
0266   MaskType GetMask() const;
0267 
0268   bool GetVerbose() const;
0269 
0270   void VAPrintf(const char *format, va_list args);
0271   void VAError(const char *format, va_list args);
0272   void VAFormatf(llvm::StringRef file, llvm::StringRef function,
0273                  const char *format, va_list args);
0274 
0275   void Enable(const std::shared_ptr<LogHandler> &handler_sp,
0276               std::optional<MaskType> flags = std::nullopt,
0277               uint32_t options = 0);
0278 
0279   void Disable(std::optional<MaskType> flags = std::nullopt);
0280 
0281 private:
0282   Channel &m_channel;
0283 
0284   // The mutex makes sure enable/disable operations are thread-safe. The
0285   // options and mask variables are atomic to enable their reading in
0286   // Channel::GetLogIfAny without taking the mutex to speed up the fast path.
0287   // Their modification however, is still protected by this mutex.
0288   llvm::sys::RWMutex m_mutex;
0289 
0290   std::shared_ptr<LogHandler> m_handler;
0291   std::atomic<uint32_t> m_options{0};
0292   std::atomic<MaskType> m_mask{0};
0293 
0294   void WriteHeader(llvm::raw_ostream &OS, llvm::StringRef file,
0295                    llvm::StringRef function);
0296   void WriteMessage(llvm::StringRef message);
0297 
0298   void Format(llvm::StringRef file, llvm::StringRef function,
0299               const llvm::formatv_object_base &payload);
0300 
0301   std::shared_ptr<LogHandler> GetHandler() {
0302     llvm::sys::ScopedReader lock(m_mutex);
0303     return m_handler;
0304   }
0305 
0306   bool Dump(llvm::raw_ostream &stream);
0307 
0308   typedef llvm::StringMap<Log> ChannelMap;
0309   static llvm::ManagedStatic<ChannelMap> g_channel_map;
0310 
0311   static void ForEachCategory(
0312       const Log::ChannelMap::value_type &entry,
0313       llvm::function_ref<void(llvm::StringRef, llvm::StringRef)> lambda);
0314 
0315   static void ListCategories(llvm::raw_ostream &stream,
0316                              const ChannelMap::value_type &entry);
0317   static Log::MaskType GetFlags(llvm::raw_ostream &stream,
0318                                 const ChannelMap::value_type &entry,
0319                                 llvm::ArrayRef<const char *> categories);
0320 
0321   Log(const Log &) = delete;
0322   void operator=(const Log &) = delete;
0323 };
0324 
0325 // Must be specialized for a particular log type.
0326 template <typename Cat> Log::Channel &LogChannelFor() = delete;
0327 
0328 /// Retrieve the Log object for the channel associated with the given log enum.
0329 ///
0330 /// Returns a valid Log object if any of the provided categories are enabled.
0331 /// Otherwise, returns nullptr.
0332 template <typename Cat> Log *GetLog(Cat mask) {
0333   static_assert(
0334       std::is_same<Log::MaskType, std::underlying_type_t<Cat>>::value);
0335   return LogChannelFor<Cat>().GetLog(Log::MaskType(mask));
0336 }
0337 
0338 /// Getter and setter for the error log (see g_error_log).
0339 /// The error log is set to the system log in SystemInitializerFull. We can't
0340 /// use the system log directly because that would violate the layering between
0341 /// Utility and Host.
0342 /// @{
0343 void SetLLDBErrorLog(Log *log);
0344 Log *GetLLDBErrorLog();
0345 /// @}
0346 
0347 } // namespace lldb_private
0348 
0349 /// The LLDB_LOG* macros defined below are the way to emit log messages.
0350 ///
0351 /// Note that the macros surround the arguments in a check for the log
0352 /// being on, so you can freely call methods in arguments without affecting
0353 /// the non-log execution flow.
0354 ///
0355 /// If you need to do more complex computations to prepare the log message
0356 /// be sure to add your own if (log) check, since we don't want logging to
0357 /// have any effect when not on.
0358 ///
0359 /// However, the LLDB_LOG macro uses the llvm::formatv system (see the
0360 /// ProgrammersManual page in the llvm docs for more details).  This allows
0361 /// the use of "format_providers" to auto-format datatypes, and there are
0362 /// already formatters for some of the llvm and lldb datatypes.
0363 ///
0364 /// So if you need to do non-trivial formatting of one of these types, be
0365 /// sure to grep the lldb and llvm sources for "format_provider" to see if
0366 /// there is already a formatter before doing in situ formatting, and if
0367 /// possible add a provider if one does not already exist.
0368 
0369 #define LLDB_LOG(log, ...)                                                     \
0370   do {                                                                         \
0371     ::lldb_private::Log *log_private = (log);                                  \
0372     if (log_private)                                                           \
0373       log_private->Format(__FILE__, __func__, __VA_ARGS__);                    \
0374   } while (0)
0375 
0376 #define LLDB_LOGF(log, ...)                                                    \
0377   do {                                                                         \
0378     ::lldb_private::Log *log_private = (log);                                  \
0379     if (log_private)                                                           \
0380       log_private->Formatf(__FILE__, __func__, __VA_ARGS__);                   \
0381   } while (0)
0382 
0383 #define LLDB_LOGV(log, ...)                                                    \
0384   do {                                                                         \
0385     ::lldb_private::Log *log_private = (log);                                  \
0386     if (log_private && log_private->GetVerbose())                              \
0387       log_private->Format(__FILE__, __func__, __VA_ARGS__);                    \
0388   } while (0)
0389 
0390 // Write message to log, if error is set. In the log message refer to the error
0391 // with {0}. Error is cleared regardless of whether logging is enabled.
0392 #define LLDB_LOG_ERROR(log, error, ...)                                        \
0393   do {                                                                         \
0394     ::lldb_private::Log *log_private = (log);                                  \
0395     ::llvm::Error error_private = (error);                                     \
0396     if (!log_private)                                                          \
0397       log_private = lldb_private::GetLLDBErrorLog();                           \
0398     if (log_private && error_private) {                                        \
0399       log_private->FormatError(::std::move(error_private), __FILE__, __func__, \
0400                                __VA_ARGS__);                                   \
0401     } else                                                                     \
0402       ::llvm::consumeError(::std::move(error_private));                        \
0403   } while (0)
0404 
0405 // Write message to the verbose log, if error is set. In the log
0406 // message refer to the error with {0}. Error is cleared regardless of
0407 // whether logging is enabled.
0408 #define LLDB_LOG_ERRORV(log, error, ...)                                       \
0409   do {                                                                         \
0410     ::lldb_private::Log *log_private = (log);                                  \
0411     ::llvm::Error error_private = (error);                                     \
0412     if (log_private && log_private->GetVerbose() && error_private) {           \
0413       log_private->FormatError(::std::move(error_private), __FILE__, __func__, \
0414                                __VA_ARGS__);                                   \
0415     } else                                                                     \
0416       ::llvm::consumeError(::std::move(error_private));                        \
0417   } while (0)
0418 
0419 #endif // LLDB_UTILITY_LOG_H