blob: 9e777a85cef0a30fd62670ee82802a2ac87ce856 [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öm6f28cf02015-12-07 23:17:15 +0100163 }
164
165 void Stop() {
Peter Boströmdda8a832016-02-29 14:54:04 +0100166 RTC_DCHECK(thread_checker_.CalledOnValidThread());
167 TRACE_EVENT_INSTANT0("webrtc", "EventLogger::Stop");
Peter Boström6f28cf02015-12-07 23:17:15 +0100168 // Try to stop. Abort if we're not currently logging.
169 if (rtc::AtomicOps::CompareAndSwap(&g_event_logging_active, 1, 0) == 0)
170 return;
171
172 // Wake up logging thread to finish writing.
173 shutdown_event_.Set();
174 // Join the logging thread.
175 logging_thread_.Stop();
176 }
177
178 private:
179 struct TraceEvent {
180 const char* name;
181 const unsigned char* category_enabled;
182 char phase;
183 uint64_t timestamp;
184 int pid;
185 rtc::PlatformThreadId tid;
186 };
187
188 rtc::CriticalSection crit_;
189 std::vector<TraceEvent> trace_events_ GUARDED_BY(crit_);
190 rtc::PlatformThread logging_thread_;
191 rtc::Event shutdown_event_;
192 rtc::ThreadChecker thread_checker_;
193 FILE* output_file_ = nullptr;
194 bool output_file_owned_ = false;
195};
196
197static bool EventTracingThreadFunc(void* params) {
198 static_cast<EventLogger*>(params)->Log();
199 return true;
200}
201
202static EventLogger* volatile g_event_logger = nullptr;
203static const char* const kDisabledTracePrefix = TRACE_DISABLED_BY_DEFAULT("");
204const unsigned char* InternalGetCategoryEnabled(const char* name) {
205 const char* prefix_ptr = &kDisabledTracePrefix[0];
206 const char* name_ptr = name;
207 // Check whether name contains the default-disabled prefix.
208 while (*prefix_ptr == *name_ptr && *prefix_ptr != '\0') {
209 ++prefix_ptr;
210 ++name_ptr;
211 }
212 return reinterpret_cast<const unsigned char*>(*prefix_ptr == '\0' ? ""
213 : name);
214}
215
216void InternalAddTraceEvent(char phase,
217 const unsigned char* category_enabled,
218 const char* name,
219 unsigned long long id,
220 int num_args,
221 const char** arg_names,
222 const unsigned char* arg_types,
223 const unsigned long long* arg_values,
224 unsigned char flags) {
225 // Fast path for when event tracing is inactive.
226 if (rtc::AtomicOps::AcquireLoad(&g_event_logging_active) == 0)
227 return;
228
229 g_event_logger->AddTraceEvent(name, category_enabled, phase,
230 rtc::TimeMicros(), 1, rtc::CurrentThreadId());
231}
232
233} // namespace
234
235void SetupInternalTracer() {
236 RTC_CHECK(rtc::AtomicOps::CompareAndSwapPtr(
237 &g_event_logger, static_cast<EventLogger*>(nullptr),
238 new EventLogger()) == nullptr);
239 g_event_logger = new EventLogger();
240 webrtc::SetupEventTracer(InternalGetCategoryEnabled, InternalAddTraceEvent);
241}
242
243void StartInternalCaptureToFile(FILE* file) {
244 g_event_logger->Start(file, false);
245}
246
247bool StartInternalCapture(const char* filename) {
248 FILE* file = fopen(filename, "w");
249 if (!file) {
250 LOG(LS_ERROR) << "Failed to open trace file '" << filename
251 << "' for writing.";
252 return false;
253 }
254 g_event_logger->Start(file, true);
255 return true;
256}
257
258void StopInternalCapture() {
259 g_event_logger->Stop();
260}
261
262void ShutdownInternalTracer() {
263 StopInternalCapture();
Peter Boström455a2522015-12-18 17:00:25 +0100264 EventLogger* old_logger = rtc::AtomicOps::AcquireLoadPtr(&g_event_logger);
Peter Boström6f28cf02015-12-07 23:17:15 +0100265 RTC_DCHECK(old_logger);
266 RTC_CHECK(rtc::AtomicOps::CompareAndSwapPtr(
267 &g_event_logger, old_logger,
268 static_cast<EventLogger*>(nullptr)) == old_logger);
269 delete old_logger;
270 webrtc::SetupEventTracer(nullptr, nullptr);
271}
272
273} // namespace tracing
274} // namespace rtc