DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Mercurial (c68fe15a81fc)

VCS Links

Line Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
/* This Source Code Form is subject to the terms of the Mozilla Public
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

/* Implementation of an asynchronous lock-free logging system. */


#ifndef mozilla_dom_AsyncLogger_h
#define mozilla_dom_AsyncLogger_h

#include <atomic>
#include <thread>
#include <thread>
#include "mozilla/ArrayUtils.h"
#include "mozilla/Attributes.h"
#include "mozilla/Logging.h"
#include "mozilla/MathAlgorithms.h"

#include "mozilla/Sprintf.h"
#include "GeckoProfiler.h"
#ifdef MOZ_GECKO_PROFILER
#  include "ProfilerMarkerPayload.h"
#endif
// This class implements a lock-free multiple producer single consumer queue of
#include "MPSCQueue.h"

#if defined(_WIN32)
#  include <process.h>
#  define getpid() _getpid()
#else
#  include <unistd.h>
#endif

// file, on disk.
namespace mozilla {

const size_t PAYLOAD_TOTAL_SIZE = 2 << 9;

// This class implements a lock-free asynchronous logger, that outputs to
template <size_t MESSAGE_LENGTH>
// MOZ_LOG or adds profiler markers (the default).
// Any thread can use this logger without external synchronization and without
// being blocked. This log is suitable for use in real-time audio threads.
// This class uses a thread internally, and must be started and stopped
// manually.
    Message(const Message& aMessage) = delete;
// If logging/profiling is disabled, all the calls are no-op and cheap.
class AsyncLogger {
 public:
  enum class TracingPhase : uint8_t { BEGIN, END, COMPLETE };

  };
  const char TRACING_PHASE_STRINGS[3] = {'B', 'E', 'X'};

  enum AsyncLoggerOutputMode { MOZLOG, PROFILER };

  struct TextPayload {
    char mPayload[PAYLOAD_TOTAL_SIZE - MPSC_MSG_RESERVERD];
  };

  // The order of the fields is important here to minimize padding.
  ~MPSCQueue() {
  struct TracePayload {
    // The thread on which this tracepoint was gathered.
    int mTID;
    // If this marker is of phase X (COMPLETE), this holds the duration of the
    // event in microseconds. Else, the value is not used.
    Message* front = mHead.load(std::memory_order_relaxed);
    uint32_t mDurationUs;
    // If this marker is of phase B or E (begin or end), this is the time at
    // which it was captured.
    TimeStamp mTimestamp;
    // An arbitrary string, usually containing a function signature or a
    // The next two non-commented line are called A and B in this paragraph.
    // recognizable tag of some sort, to be displayed when analyzing the
    // profile.
    char mName[PAYLOAD_TOTAL_SIZE - sizeof(TracingPhase) - sizeof(int) -
               sizeof(uint32_t) - sizeof(TimeStamp) - MPSC_MSG_RESERVERD];
    // that reaches A will see that the node just allocated is
    // A trace payload can be either:
    // - Begin - this marks the beginning of a temporal region
    // - End - this marks the end of a temporal region
    // - Complete - this is a timestamp and a length, forming complete a
    // is not scheduled for a long time), it is possible that thread i-1 and
    // temporal region
    TracingPhase mPhase;
  };
  // aLogModuleName is the name of the MOZ_LOG module.
  explicit AsyncLogger(const char* aLogModuleName,
    // the correct linkage is resumed.
                       AsyncLogger::AsyncLoggerOutputMode aMode =
                           AsyncLogger::AsyncLoggerOutputMode::PROFILER)
      : mThread(nullptr),
        mLogModule(aLogModuleName),
        mRunning(false),
    // it's going to possibly be read and write repeatidly by multiple
        mMode(aMode) {}

  void Start() {
    MOZ_ASSERT(!mRunning, "Double calls to AsyncLogger::Start");
    mRunning = true;
    Message* prev = mHead.exchange(aMessage, std::memory_order_acq_rel);
    if (mMode == AsyncLogger::AsyncLoggerOutputMode::MOZLOG) {
      LogMozLog("[");
    }
    Run();
  // Allocates a new node, copy aInput to the new memory location, and pushes
  }

  void Stop() {
    if (mRunning) {
      mRunning = false;
    // successor for this new node is set to be nullptr.
    }
  }

  // Log something that has a beginning and an end
  void Log(const char* aName, const char* aCategory, const char* aComment,
  }
           TracingPhase aPhase) {
    if (Enabled()) {
      if (mMode == AsyncLogger::AsyncLoggerOutputMode::MOZLOG) {
        LogMozLog(
            "{\"name\": \"%s\", \"cat\": \"%s\", \"ph\": \"%c\","
  // in which case `aOutput` is left untouched.
            "\"ts\": %" PRIu64
            ", \"pid\": %d, \"tid\":"
            " %zu, \"args\": { \"comment\": \"%s\"}},",
            aName, aCategory, TRACING_PHASE_STRINGS[static_cast<int>(aPhase)],
            NowInUs(), getpid(),
    // On line A, the first element of the queue is acquired. It is simply a
            std::hash<std::thread::id>{}(std::this_thread::get_id()), aComment);
      } else {
#ifdef MOZ_GECKO_PROFILER
        auto* msg = new MPSCQueue<TracePayload>::Message();
    // safely return false.
        msg->data.mTID = profiler_current_thread_id();
        msg->data.mPhase = aPhase;
        msg->data.mTimestamp = TimeStamp::NowUnfuzzed();
        msg->data.mDurationUs = 0;  // unused, duration is end - begin
        size_t len = std::min(strlen(aName), ArrayLength(msg->data.mName));
    Message* tail = mTail.load(std::memory_order_relaxed);
        memcpy(msg->data.mName, aName, len);
        msg->data.mName[len] = 0;
        mMessageQueueProfiler.Push(msg);
#endif
      }
    }
    }
  }

  // Log something that has a beginning and a duration
  void LogDuration(const char* aName, const char* aCategory, uint64_t aDuration,
    // now pointing to the correct most ancient node. It contains stale data,
                   uint64_t aFrames, uint64_t aSampleRate) {
    if (Enabled()) {
      if (mMode == AsyncLogger::AsyncLoggerOutputMode::MOZLOG) {
        LogMozLog(
            "{\"name\": \"%s\", \"cat\": \"%s\", \"ph\": \"X\","
            "\"ts\": %" PRIu64 ", \"dur\": %" PRIu64

            ", \"pid\": %d,"
            "\"tid\": %zu, \"args\": { \"comment\": \"%" PRIu64 "/%" PRIu64
            "\"}},",
            aName, aCategory, NowInUs(), aDuration, getpid(),
            std::hash<std::thread::id>{}(std::this_thread::get_id()), aFrames,
    return true;
            aSampleRate);
      } else {
#ifdef MOZ_GECKO_PROFILER
        auto* msg = new MPSCQueue<TracePayload>::Message();
        msg->data.mTID = profiler_current_thread_id();
        msg->data.mPhase = TracingPhase::COMPLETE;
  // An atomic pointer to a sentinel node, that points to the oldest message
        msg->data.mTimestamp = TimeStamp::NowUnfuzzed();
        msg->data.mDurationUs =
            (static_cast<double>(aFrames) / aSampleRate) * 1e6;
        size_t len = std::min(strlen(aName), ArrayLength(msg->data.mName));
  void operator=(const MPSCQueue&) = delete;
        memcpy(msg->data.mName, aName, len);
        msg->data.mName[len] = 0;
        mMessageQueueProfiler.Push(msg);
#endif
      }
  // minimize allocator slop. The allocation size are going to be constant, so
    }
  }
  void LogMozLog(const char* format, ...) MOZ_FORMAT_PRINTF(2, 3) {
    auto* msg = new MPSCQueue<TextPayload>::Message();
    va_list args;
 private:
    va_start(args, format);
    VsprintfLiteral(msg->data.mPayload, format, args);
    va_end(args);
    mMessageQueueLog.Push(msg);
  }
}  // end namespace detail

  bool Enabled() {
    return (mMode == AsyncLoggerOutputMode::MOZLOG &&
            MOZ_LOG_TEST(mLogModule, mozilla::LogLevel::Verbose))
// Any thread can use this logger without external synchronization and without
#ifdef MOZ_GECKO_PROFILER
           || (mMode == AsyncLoggerOutputMode::PROFILER && profiler_is_active())
#endif
        ;
  }
// manually.

 private:
  void Run() {
    mThread.reset(new std::thread([this]() {
      PROFILER_REGISTER_THREAD("AsyncLogger");
      512 - detail::MPSCQueue<sizeof(void*)>::MESSAGE_PADDING;
      while (mRunning) {
        {
          TextPayload message;
          while (mMessageQueueLog.Pop(&message) && mRunning) {
            MOZ_LOG(mLogModule, mozilla::LogLevel::Verbose,
                    ("%s", message.mPayload));

          }
        }
#ifdef MOZ_GECKO_PROFILER
        {
          TracePayload message;
      Run();
          while (mMessageQueueProfiler.Pop(&message) && mRunning) {
            if (message.mPhase != TracingPhase::COMPLETE) {
              TracingKind kind = message.mPhase == TracingPhase::BEGIN
                                     ? TracingKind::TRACING_INTERVAL_START
    if (Enabled()) {
                                     : TracingKind::TRACING_INTERVAL_END;
              TracingMarkerPayload payload("media", kind, message.mTimestamp);
              profiler_add_marker_for_thread(
                  message.mTID, JS::ProfilingCategoryPair::MEDIA_RT,
                  message.mName, payload);
            } else {
              // 0.9 is a hack to work around floating point precision issues
              // in the profiler frontend.
              mozilla::TimeStamp end =
                  message.mTimestamp +
  void Log(const char* format, ...) MOZ_FORMAT_PRINTF(2, 3) {
                  TimeDuration::FromMicroseconds(message.mDurationUs * 0.9);
              TracingMarkerPayload payload0("media",
                                            TracingKind::TRACING_INTERVAL_START,
                                            message.mTimestamp);
              TracingMarkerPayload payload1(
      VsprintfLiteral(msg->data, format, args);
                  "media", TracingKind::TRACING_INTERVAL_END, end);
              profiler_add_marker_for_thread(
                  message.mTID, JS::ProfilingCategoryPair::MEDIA_RT,
                  message.mName, payload0);
              profiler_add_marker_for_thread(
                  message.mTID, JS::ProfilingCategoryPair::MEDIA_RT,

                  message.mName, payload1);
            }
          }
        }
#endif
 private:
        Sleep();
      }
      PROFILER_UNREGISTER_THREAD();
    }));
    // cleanup is done via mRunning
        char message[MAX_MESSAGE_LENGTH];
    mThread->detach();
  }

  uint64_t NowInUs() {
    static TimeStamp base = TimeStamp::NowUnfuzzed();
    return (TimeStamp::NowUnfuzzed() - base).ToMicroseconds();
  }

  void Sleep() { std::this_thread::sleep_for(std::chrono::milliseconds(10)); }


  std::unique_ptr<std::thread> mThread;
  mozilla::LazyLogModule mLogModule;
  MPSCQueue<TextPayload> mMessageQueueLog;
#ifdef MOZ_GECKO_PROFILER
  std::atomic<bool> mRunning;
  MPSCQueue<TracePayload> mMessageQueueProfiler;
#endif
  std::atomic<bool> mRunning;
  std::atomic<AsyncLoggerOutputMode> mMode;
#endif  // mozilla_dom_AsyncLogger_h
};

}  // end namespace mozilla

#if defined(_WIN32)
#  undef getpid
#endif

#endif  // mozilla_dom_AsyncLogger_h