blob: 85d5c0b17b60a5531a2d1cb56803f97d0627e731 [file] [log] [blame]
tommi@webrtc.org7c64ed22015-03-17 14:25:37 +00001/*
2 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
tommi@webrtc.org7c64ed22015-03-17 14:25:37 +000010#include "webrtc/base/event_tracer.h"
11
Peter Boström6f28cf02015-12-07 23:17:15 +010012#include <inttypes.h>
13
14#include <vector>
15
16#include "webrtc/base/checks.h"
17#include "webrtc/base/criticalsection.h"
18#include "webrtc/base/event.h"
19#include "webrtc/base/logging.h"
20#include "webrtc/base/platform_thread.h"
21#include "webrtc/base/timeutils.h"
22#include "webrtc/base/trace_event.h"
23
tommi@webrtc.org7c64ed22015-03-17 14:25:37 +000024namespace webrtc {
25
26namespace {
27
Peter Boström6f28cf02015-12-07 23:17:15 +010028GetCategoryEnabledPtr g_get_category_enabled_ptr = nullptr;
29AddTraceEventPtr g_add_trace_event_ptr = nullptr;
tommi@webrtc.org7c64ed22015-03-17 14:25:37 +000030
31} // namespace
32
33void SetupEventTracer(GetCategoryEnabledPtr get_category_enabled_ptr,
34 AddTraceEventPtr add_trace_event_ptr) {
35 g_get_category_enabled_ptr = get_category_enabled_ptr;
36 g_add_trace_event_ptr = add_trace_event_ptr;
37}
38
tommi@webrtc.org7c64ed22015-03-17 14:25:37 +000039const unsigned char* EventTracer::GetCategoryEnabled(const char* name) {
40 if (g_get_category_enabled_ptr)
41 return g_get_category_enabled_ptr(name);
42
43 // A string with null terminator means category is disabled.
44 return reinterpret_cast<const unsigned char*>("\0");
45}
46
Peter Boström6f28cf02015-12-07 23:17:15 +010047// Arguments to this function (phase, etc.) are as defined in
48// webrtc/base/trace_event.h.
tommi@webrtc.org7c64ed22015-03-17 14:25:37 +000049void EventTracer::AddTraceEvent(char phase,
50 const unsigned char* category_enabled,
51 const char* name,
52 unsigned long long id,
53 int num_args,
54 const char** arg_names,
55 const unsigned char* arg_types,
56 const unsigned long long* arg_values,
57 unsigned char flags) {
58 if (g_add_trace_event_ptr) {
59 g_add_trace_event_ptr(phase,
60 category_enabled,
61 name,
62 id,
63 num_args,
64 arg_names,
65 arg_types,
66 arg_values,
67 flags);
68 }
69}
70
71} // namespace webrtc
Peter Boström6f28cf02015-12-07 23:17:15 +010072
73namespace rtc {
74namespace tracing {
75namespace {
76
77static bool EventTracingThreadFunc(void* params);
78
79// Atomic-int fast path for avoiding logging when disabled.
80static volatile int g_event_logging_active = 0;
81
82// TODO(pbos): Log metadata for all threads, etc.
83class EventLogger final {
84 public:
85 EventLogger()
86 : logging_thread_(EventTracingThreadFunc, this, "EventTracingThread"),
87 shutdown_event_(false, false) {}
88 ~EventLogger() { RTC_DCHECK(thread_checker_.CalledOnValidThread()); }
89
90 void AddTraceEvent(const char* name,
91 const unsigned char* category_enabled,
92 char phase,
93 uint64_t timestamp,
94 int pid,
95 rtc::PlatformThreadId thread_id) {
96 rtc::CritScope lock(&crit_);
97 trace_events_.push_back(
98 {name, category_enabled, phase, timestamp, 1, thread_id});
99 }
100
101// The TraceEvent format is documented here:
102// https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/preview
103 void Log() {
104 RTC_DCHECK(output_file_);
105 static const int kLoggingIntervalMs = 100;
106 fprintf(output_file_, "{ \"traceEvents\": [\n");
107 bool has_logged_event = false;
108 while (true) {
109 bool shutting_down = shutdown_event_.Wait(kLoggingIntervalMs);
110 std::vector<TraceEvent> events;
111 {
112 rtc::CritScope lock(&crit_);
113 trace_events_.swap(events);
114 }
115 for (const TraceEvent& e : events) {
116 fprintf(output_file_,
117 "%s{ \"name\": \"%s\""
118 ", \"cat\": \"%s\""
119 ", \"ph\": \"%c\""
120 ", \"ts\": %" PRIu64
121 ", \"pid\": %d"
Peter Boström43e4e232015-12-11 20:29:35 +0100122#if defined(WEBRTC_WIN)
123 ", \"tid\": %lu"
124#else
125 ", \"tid\": %d"
126#endif // defined(WEBRTC_WIN)
127 "}\n",
Peter Boström6f28cf02015-12-07 23:17:15 +0100128 has_logged_event ? "," : " ", e.name, e.category_enabled,
Peter Boström43e4e232015-12-11 20:29:35 +0100129 e.phase, e.timestamp, e.pid, e.tid);
Peter Boström6f28cf02015-12-07 23:17:15 +0100130 has_logged_event = true;
131 }
132 if (shutting_down)
133 break;
134 }
135 fprintf(output_file_, "]}\n");
136 if (output_file_owned_)
137 fclose(output_file_);
138 output_file_ = nullptr;
139 }
140
141 void Start(FILE* file, bool owned) {
Peter Boströmdda8a832016-02-29 14:54:04 +0100142 RTC_DCHECK(thread_checker_.CalledOnValidThread());
Peter Boström6f28cf02015-12-07 23:17:15 +0100143 RTC_DCHECK(file);
144 RTC_DCHECK(!output_file_);
145 output_file_ = file;
146 output_file_owned_ = owned;
147 {
148 rtc::CritScope lock(&crit_);
149 // Since the atomic fast-path for adding events to the queue can be
150 // bypassed while the logging thread is shutting down there may be some
151 // stale events in the queue, hence the vector needs to be cleared to not
152 // log events from a previous logging session (which may be days old).
153 trace_events_.clear();
154 }
155 // Enable event logging (fast-path). This should be disabled since starting
156 // shouldn't be done twice.
157 RTC_CHECK_EQ(0,
158 rtc::AtomicOps::CompareAndSwap(&g_event_logging_active, 0, 1));
159
160 // Finally start, everything should be set up now.
161 logging_thread_.Start();
Peter Boströmdda8a832016-02-29 14:54:04 +0100162 TRACE_EVENT_INSTANT0("webrtc", "EventLogger::Start");
Peter Boström0ec9a9b2016-05-27 11:11:45 +0200163 logging_thread_.SetPriority(kLowPriority);
Peter Boström6f28cf02015-12-07 23:17:15 +0100164 }
165
166 void Stop() {
Peter Boströmdda8a832016-02-29 14:54:04 +0100167 RTC_DCHECK(thread_checker_.CalledOnValidThread());
168 TRACE_EVENT_INSTANT0("webrtc", "EventLogger::Stop");
Peter Boström6f28cf02015-12-07 23:17:15 +0100169 // Try to stop. Abort if we're not currently logging.
170 if (rtc::AtomicOps::CompareAndSwap(&g_event_logging_active, 1, 0) == 0)
171 return;
172
173 // Wake up logging thread to finish writing.
174 shutdown_event_.Set();
175 // Join the logging thread.
176 logging_thread_.Stop();
177 }
178
179 private:
180 struct TraceEvent {
181 const char* name;
182 const unsigned char* category_enabled;
183 char phase;
184 uint64_t timestamp;
185 int pid;
186 rtc::PlatformThreadId tid;
187 };
188
189 rtc::CriticalSection crit_;
190 std::vector<TraceEvent> trace_events_ GUARDED_BY(crit_);
191 rtc::PlatformThread logging_thread_;
192 rtc::Event shutdown_event_;
193 rtc::ThreadChecker thread_checker_;
194 FILE* output_file_ = nullptr;
195 bool output_file_owned_ = false;
196};
197
198static bool EventTracingThreadFunc(void* params) {
199 static_cast<EventLogger*>(params)->Log();
skvlad843b6f52016-07-22 21:45:35 -0700200 // False indicates that the thread function has done its job and doesn't need
201 // to be restarted again. Log() runs its own internal loop.
202 return false;
Peter Boström6f28cf02015-12-07 23:17:15 +0100203}
204
205static EventLogger* volatile g_event_logger = nullptr;
206static const char* const kDisabledTracePrefix = TRACE_DISABLED_BY_DEFAULT("");
207const unsigned char* InternalGetCategoryEnabled(const char* name) {
208 const char* prefix_ptr = &kDisabledTracePrefix[0];
209 const char* name_ptr = name;
210 // Check whether name contains the default-disabled prefix.
211 while (*prefix_ptr == *name_ptr && *prefix_ptr != '\0') {
212 ++prefix_ptr;
213 ++name_ptr;
214 }
215 return reinterpret_cast<const unsigned char*>(*prefix_ptr == '\0' ? ""
216 : name);
217}
218
219void InternalAddTraceEvent(char phase,
220 const unsigned char* category_enabled,
221 const char* name,
222 unsigned long long id,
223 int num_args,
224 const char** arg_names,
225 const unsigned char* arg_types,
226 const unsigned long long* arg_values,
227 unsigned char flags) {
228 // Fast path for when event tracing is inactive.
229 if (rtc::AtomicOps::AcquireLoad(&g_event_logging_active) == 0)
230 return;
231
232 g_event_logger->AddTraceEvent(name, category_enabled, phase,
233 rtc::TimeMicros(), 1, rtc::CurrentThreadId());
234}
235
236} // namespace
237
238void SetupInternalTracer() {
239 RTC_CHECK(rtc::AtomicOps::CompareAndSwapPtr(
240 &g_event_logger, static_cast<EventLogger*>(nullptr),
241 new EventLogger()) == nullptr);
Peter Boström6f28cf02015-12-07 23:17:15 +0100242 webrtc::SetupEventTracer(InternalGetCategoryEnabled, InternalAddTraceEvent);
243}
244
245void StartInternalCaptureToFile(FILE* file) {
246 g_event_logger->Start(file, false);
247}
248
249bool StartInternalCapture(const char* filename) {
250 FILE* file = fopen(filename, "w");
251 if (!file) {
252 LOG(LS_ERROR) << "Failed to open trace file '" << filename
253 << "' for writing.";
254 return false;
255 }
256 g_event_logger->Start(file, true);
257 return true;
258}
259
260void StopInternalCapture() {
261 g_event_logger->Stop();
262}
263
264void ShutdownInternalTracer() {
265 StopInternalCapture();
Peter Boström455a2522015-12-18 17:00:25 +0100266 EventLogger* old_logger = rtc::AtomicOps::AcquireLoadPtr(&g_event_logger);
Peter Boström6f28cf02015-12-07 23:17:15 +0100267 RTC_DCHECK(old_logger);
268 RTC_CHECK(rtc::AtomicOps::CompareAndSwapPtr(
269 &g_event_logger, old_logger,
270 static_cast<EventLogger*>(nullptr)) == old_logger);
271 delete old_logger;
272 webrtc::SetupEventTracer(nullptr, nullptr);
273}
274
275} // namespace tracing
276} // namespace rtc