blob: d3f6ebf258c5a281dd3ebedd586ed0c99375df65 [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 */
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020010#include "rtc_base/event_tracer.h"
tommi@webrtc.org7c64ed22015-03-17 14:25:37 +000011
Peter Boström6f28cf02015-12-07 23:17:15 +010012#include <inttypes.h>
Yves Gerey988cc082018-10-23 12:03:01 +020013#include <stdint.h>
14#include <stdio.h>
15#include <string.h>
sakalf4433ef2016-08-08 04:10:13 -070016#include <string>
Peter Boström6f28cf02015-12-07 23:17:15 +010017#include <vector>
18
Steve Anton10542f22019-01-11 09:11:00 -080019#include "rtc_base/atomic_ops.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020020#include "rtc_base/checks.h"
Steve Anton10542f22019-01-11 09:11:00 -080021#include "rtc_base/critical_section.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020022#include "rtc_base/event.h"
23#include "rtc_base/logging.h"
24#include "rtc_base/platform_thread.h"
Yves Gerey988cc082018-10-23 12:03:01 +020025#include "rtc_base/platform_thread_types.h"
26#include "rtc_base/thread_annotations.h"
27#include "rtc_base/thread_checker.h"
Steve Anton10542f22019-01-11 09:11:00 -080028#include "rtc_base/time_utils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020029#include "rtc_base/trace_event.h"
Peter Boström6f28cf02015-12-07 23:17:15 +010030
sakalf4433ef2016-08-08 04:10:13 -070031// This is a guesstimate that should be enough in most cases.
32static const size_t kEventLoggerArgsStrBufferInitialSize = 256;
33static const size_t kTraceArgBufferLength = 32;
34
tommi@webrtc.org7c64ed22015-03-17 14:25:37 +000035namespace webrtc {
36
37namespace {
38
Peter Boström6f28cf02015-12-07 23:17:15 +010039GetCategoryEnabledPtr g_get_category_enabled_ptr = nullptr;
40AddTraceEventPtr g_add_trace_event_ptr = nullptr;
tommi@webrtc.org7c64ed22015-03-17 14:25:37 +000041
42} // namespace
43
44void SetupEventTracer(GetCategoryEnabledPtr get_category_enabled_ptr,
45 AddTraceEventPtr add_trace_event_ptr) {
46 g_get_category_enabled_ptr = get_category_enabled_ptr;
47 g_add_trace_event_ptr = add_trace_event_ptr;
48}
49
tommi@webrtc.org7c64ed22015-03-17 14:25:37 +000050const unsigned char* EventTracer::GetCategoryEnabled(const char* name) {
51 if (g_get_category_enabled_ptr)
52 return g_get_category_enabled_ptr(name);
53
54 // A string with null terminator means category is disabled.
55 return reinterpret_cast<const unsigned char*>("\0");
56}
57
Peter Boström6f28cf02015-12-07 23:17:15 +010058// Arguments to this function (phase, etc.) are as defined in
kjellandere96c45b2017-06-30 10:45:21 -070059// webrtc/rtc_base/trace_event.h.
tommi@webrtc.org7c64ed22015-03-17 14:25:37 +000060void EventTracer::AddTraceEvent(char phase,
61 const unsigned char* category_enabled,
62 const char* name,
63 unsigned long long id,
64 int num_args,
65 const char** arg_names,
66 const unsigned char* arg_types,
67 const unsigned long long* arg_values,
68 unsigned char flags) {
69 if (g_add_trace_event_ptr) {
Yves Gerey665174f2018-06-19 15:03:05 +020070 g_add_trace_event_ptr(phase, category_enabled, name, id, num_args,
71 arg_names, arg_types, arg_values, flags);
tommi@webrtc.org7c64ed22015-03-17 14:25:37 +000072 }
73}
74
75} // namespace webrtc
Peter Boström6f28cf02015-12-07 23:17:15 +010076
77namespace rtc {
78namespace tracing {
79namespace {
80
tommi0f8b4032017-02-22 11:22:05 -080081static void EventTracingThreadFunc(void* params);
Peter Boström6f28cf02015-12-07 23:17:15 +010082
83// Atomic-int fast path for avoiding logging when disabled.
84static volatile int g_event_logging_active = 0;
85
86// TODO(pbos): Log metadata for all threads, etc.
87class EventLogger final {
88 public:
89 EventLogger()
tommi0f8b4032017-02-22 11:22:05 -080090 : logging_thread_(EventTracingThreadFunc,
91 this,
92 "EventTracingThread",
Niels Möllerc572ff32018-11-07 08:43:50 +010093 kLowPriority) {}
Sebastian Janssonc01367d2019-04-08 15:20:44 +020094 ~EventLogger() { RTC_DCHECK(thread_checker_.IsCurrent()); }
Peter Boström6f28cf02015-12-07 23:17:15 +010095
96 void AddTraceEvent(const char* name,
97 const unsigned char* category_enabled,
98 char phase,
sakalf4433ef2016-08-08 04:10:13 -070099 int num_args,
100 const char** arg_names,
101 const unsigned char* arg_types,
102 const unsigned long long* arg_values,
Peter Boström6f28cf02015-12-07 23:17:15 +0100103 uint64_t timestamp,
104 int pid,
105 rtc::PlatformThreadId thread_id) {
sakalf4433ef2016-08-08 04:10:13 -0700106 std::vector<TraceArg> args(num_args);
107 for (int i = 0; i < num_args; ++i) {
108 TraceArg& arg = args[i];
109 arg.name = arg_names[i];
110 arg.type = arg_types[i];
111 arg.value.as_uint = arg_values[i];
112
113 // Value is a pointer to a temporary string, so we have to make a copy.
114 if (arg.type == TRACE_VALUE_TYPE_COPY_STRING) {
115 // Space for the string and for the terminating null character.
116 size_t str_length = strlen(arg.value.as_string) + 1;
117 char* str_copy = new char[str_length];
118 memcpy(str_copy, arg.value.as_string, str_length);
119 arg.value.as_string = str_copy;
120 }
121 }
Peter Boström6f28cf02015-12-07 23:17:15 +0100122 rtc::CritScope lock(&crit_);
123 trace_events_.push_back(
sakalf4433ef2016-08-08 04:10:13 -0700124 {name, category_enabled, phase, args, timestamp, 1, thread_id});
Peter Boström6f28cf02015-12-07 23:17:15 +0100125 }
126
Yves Gerey665174f2018-06-19 15:03:05 +0200127 // The TraceEvent format is documented here:
128 // https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/preview
Peter Boström6f28cf02015-12-07 23:17:15 +0100129 void Log() {
130 RTC_DCHECK(output_file_);
131 static const int kLoggingIntervalMs = 100;
132 fprintf(output_file_, "{ \"traceEvents\": [\n");
133 bool has_logged_event = false;
134 while (true) {
135 bool shutting_down = shutdown_event_.Wait(kLoggingIntervalMs);
136 std::vector<TraceEvent> events;
137 {
138 rtc::CritScope lock(&crit_);
139 trace_events_.swap(events);
140 }
sakalf4433ef2016-08-08 04:10:13 -0700141 std::string args_str;
142 args_str.reserve(kEventLoggerArgsStrBufferInitialSize);
143 for (TraceEvent& e : events) {
144 args_str.clear();
145 if (!e.args.empty()) {
146 args_str += ", \"args\": {";
147 bool is_first_argument = true;
148 for (TraceArg& arg : e.args) {
149 if (!is_first_argument)
150 args_str += ",";
151 is_first_argument = false;
152 args_str += " \"";
153 args_str += arg.name;
154 args_str += "\": ";
155 args_str += TraceArgValueAsString(arg);
156
157 // Delete our copy of the string.
158 if (arg.type == TRACE_VALUE_TYPE_COPY_STRING) {
159 delete[] arg.value.as_string;
160 arg.value.as_string = nullptr;
161 }
162 }
163 args_str += " }";
164 }
Peter Boström6f28cf02015-12-07 23:17:15 +0100165 fprintf(output_file_,
166 "%s{ \"name\": \"%s\""
167 ", \"cat\": \"%s\""
168 ", \"ph\": \"%c\""
169 ", \"ts\": %" PRIu64
170 ", \"pid\": %d"
Peter Boström43e4e232015-12-11 20:29:35 +0100171#if defined(WEBRTC_WIN)
172 ", \"tid\": %lu"
173#else
174 ", \"tid\": %d"
175#endif // defined(WEBRTC_WIN)
sakalf4433ef2016-08-08 04:10:13 -0700176 "%s"
Peter Boström43e4e232015-12-11 20:29:35 +0100177 "}\n",
Peter Boström6f28cf02015-12-07 23:17:15 +0100178 has_logged_event ? "," : " ", e.name, e.category_enabled,
sakalf4433ef2016-08-08 04:10:13 -0700179 e.phase, e.timestamp, e.pid, e.tid, args_str.c_str());
Peter Boström6f28cf02015-12-07 23:17:15 +0100180 has_logged_event = true;
181 }
182 if (shutting_down)
183 break;
184 }
185 fprintf(output_file_, "]}\n");
186 if (output_file_owned_)
187 fclose(output_file_);
188 output_file_ = nullptr;
189 }
190
191 void Start(FILE* file, bool owned) {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200192 RTC_DCHECK(thread_checker_.IsCurrent());
Peter Boström6f28cf02015-12-07 23:17:15 +0100193 RTC_DCHECK(file);
194 RTC_DCHECK(!output_file_);
195 output_file_ = file;
196 output_file_owned_ = owned;
197 {
198 rtc::CritScope lock(&crit_);
199 // Since the atomic fast-path for adding events to the queue can be
200 // bypassed while the logging thread is shutting down there may be some
201 // stale events in the queue, hence the vector needs to be cleared to not
202 // log events from a previous logging session (which may be days old).
203 trace_events_.clear();
204 }
205 // Enable event logging (fast-path). This should be disabled since starting
206 // shouldn't be done twice.
207 RTC_CHECK_EQ(0,
208 rtc::AtomicOps::CompareAndSwap(&g_event_logging_active, 0, 1));
209
210 // Finally start, everything should be set up now.
211 logging_thread_.Start();
Peter Boströmdda8a832016-02-29 14:54:04 +0100212 TRACE_EVENT_INSTANT0("webrtc", "EventLogger::Start");
Peter Boström6f28cf02015-12-07 23:17:15 +0100213 }
214
215 void Stop() {
Sebastian Janssonc01367d2019-04-08 15:20:44 +0200216 RTC_DCHECK(thread_checker_.IsCurrent());
Peter Boströmdda8a832016-02-29 14:54:04 +0100217 TRACE_EVENT_INSTANT0("webrtc", "EventLogger::Stop");
Peter Boström6f28cf02015-12-07 23:17:15 +0100218 // Try to stop. Abort if we're not currently logging.
219 if (rtc::AtomicOps::CompareAndSwap(&g_event_logging_active, 1, 0) == 0)
220 return;
221
222 // Wake up logging thread to finish writing.
223 shutdown_event_.Set();
224 // Join the logging thread.
225 logging_thread_.Stop();
226 }
227
228 private:
sakalf4433ef2016-08-08 04:10:13 -0700229 struct TraceArg {
230 const char* name;
231 unsigned char type;
kjellandere96c45b2017-06-30 10:45:21 -0700232 // Copied from webrtc/rtc_base/trace_event.h TraceValueUnion.
sakalf4433ef2016-08-08 04:10:13 -0700233 union TraceArgValue {
234 bool as_bool;
235 unsigned long long as_uint;
236 long long as_int;
237 double as_double;
238 const void* as_pointer;
239 const char* as_string;
240 } value;
241
242 // Assert that the size of the union is equal to the size of the as_uint
243 // field since we are assigning to arbitrary types using it.
244 static_assert(sizeof(TraceArgValue) == sizeof(unsigned long long),
245 "Size of TraceArg value union is not equal to the size of "
246 "the uint field of that union.");
247 };
248
Peter Boström6f28cf02015-12-07 23:17:15 +0100249 struct TraceEvent {
250 const char* name;
251 const unsigned char* category_enabled;
252 char phase;
sakalf4433ef2016-08-08 04:10:13 -0700253 std::vector<TraceArg> args;
Peter Boström6f28cf02015-12-07 23:17:15 +0100254 uint64_t timestamp;
255 int pid;
256 rtc::PlatformThreadId tid;
257 };
258
sakalf4433ef2016-08-08 04:10:13 -0700259 static std::string TraceArgValueAsString(TraceArg arg) {
260 std::string output;
261
262 if (arg.type == TRACE_VALUE_TYPE_STRING ||
263 arg.type == TRACE_VALUE_TYPE_COPY_STRING) {
264 // Space for every character to be an espaced character + two for
265 // quatation marks.
266 output.reserve(strlen(arg.value.as_string) * 2 + 2);
267 output += '\"';
268 const char* c = arg.value.as_string;
269 do {
270 if (*c == '"' || *c == '\\') {
271 output += '\\';
272 output += *c;
273 } else {
274 output += *c;
275 }
276 } while (*++c);
277 output += '\"';
278 } else {
279 output.resize(kTraceArgBufferLength);
280 size_t print_length = 0;
281 switch (arg.type) {
282 case TRACE_VALUE_TYPE_BOOL:
283 if (arg.value.as_bool) {
284 strcpy(&output[0], "true");
285 print_length = 4;
286 } else {
287 strcpy(&output[0], "false");
288 print_length = 5;
289 }
290 break;
291 case TRACE_VALUE_TYPE_UINT:
Niels Mölleraba06332018-10-16 15:14:15 +0200292 print_length = snprintf(&output[0], kTraceArgBufferLength, "%llu",
sakalf4433ef2016-08-08 04:10:13 -0700293 arg.value.as_uint);
294 break;
295 case TRACE_VALUE_TYPE_INT:
Niels Mölleraba06332018-10-16 15:14:15 +0200296 print_length = snprintf(&output[0], kTraceArgBufferLength, "%lld",
sakalf4433ef2016-08-08 04:10:13 -0700297 arg.value.as_int);
298 break;
299 case TRACE_VALUE_TYPE_DOUBLE:
Niels Mölleraba06332018-10-16 15:14:15 +0200300 print_length = snprintf(&output[0], kTraceArgBufferLength, "%f",
sakalf4433ef2016-08-08 04:10:13 -0700301 arg.value.as_double);
302 break;
303 case TRACE_VALUE_TYPE_POINTER:
Niels Mölleraba06332018-10-16 15:14:15 +0200304 print_length = snprintf(&output[0], kTraceArgBufferLength, "\"%p\"",
sakalf4433ef2016-08-08 04:10:13 -0700305 arg.value.as_pointer);
306 break;
307 }
308 size_t output_length = print_length < kTraceArgBufferLength
309 ? print_length
310 : kTraceArgBufferLength - 1;
311 // This will hopefully be very close to nop. On most implementations, it
312 // just writes null byte and sets the length field of the string.
313 output.resize(output_length);
314 }
315
316 return output;
317 }
318
Peter Boström6f28cf02015-12-07 23:17:15 +0100319 rtc::CriticalSection crit_;
danilchap3c6abd22017-09-06 05:46:29 -0700320 std::vector<TraceEvent> trace_events_ RTC_GUARDED_BY(crit_);
Peter Boström6f28cf02015-12-07 23:17:15 +0100321 rtc::PlatformThread logging_thread_;
322 rtc::Event shutdown_event_;
323 rtc::ThreadChecker thread_checker_;
324 FILE* output_file_ = nullptr;
325 bool output_file_owned_ = false;
326};
327
tommi0f8b4032017-02-22 11:22:05 -0800328static void EventTracingThreadFunc(void* params) {
Peter Boström6f28cf02015-12-07 23:17:15 +0100329 static_cast<EventLogger*>(params)->Log();
Peter Boström6f28cf02015-12-07 23:17:15 +0100330}
331
332static EventLogger* volatile g_event_logger = nullptr;
333static const char* const kDisabledTracePrefix = TRACE_DISABLED_BY_DEFAULT("");
334const unsigned char* InternalGetCategoryEnabled(const char* name) {
335 const char* prefix_ptr = &kDisabledTracePrefix[0];
336 const char* name_ptr = name;
337 // Check whether name contains the default-disabled prefix.
338 while (*prefix_ptr == *name_ptr && *prefix_ptr != '\0') {
339 ++prefix_ptr;
340 ++name_ptr;
341 }
342 return reinterpret_cast<const unsigned char*>(*prefix_ptr == '\0' ? ""
343 : name);
344}
345
346void InternalAddTraceEvent(char phase,
347 const unsigned char* category_enabled,
348 const char* name,
349 unsigned long long id,
350 int num_args,
351 const char** arg_names,
352 const unsigned char* arg_types,
353 const unsigned long long* arg_values,
354 unsigned char flags) {
355 // Fast path for when event tracing is inactive.
356 if (rtc::AtomicOps::AcquireLoad(&g_event_logging_active) == 0)
357 return;
358
sakalf4433ef2016-08-08 04:10:13 -0700359 g_event_logger->AddTraceEvent(name, category_enabled, phase, num_args,
360 arg_names, arg_types, arg_values,
Peter Boström6f28cf02015-12-07 23:17:15 +0100361 rtc::TimeMicros(), 1, rtc::CurrentThreadId());
362}
363
364} // namespace
365
366void SetupInternalTracer() {
367 RTC_CHECK(rtc::AtomicOps::CompareAndSwapPtr(
368 &g_event_logger, static_cast<EventLogger*>(nullptr),
369 new EventLogger()) == nullptr);
Peter Boström6f28cf02015-12-07 23:17:15 +0100370 webrtc::SetupEventTracer(InternalGetCategoryEnabled, InternalAddTraceEvent);
371}
372
373void StartInternalCaptureToFile(FILE* file) {
jtteh7480da42017-07-07 11:02:15 -0700374 if (g_event_logger) {
375 g_event_logger->Start(file, false);
376 }
Peter Boström6f28cf02015-12-07 23:17:15 +0100377}
378
379bool StartInternalCapture(const char* filename) {
jtteh7480da42017-07-07 11:02:15 -0700380 if (!g_event_logger)
381 return false;
382
Peter Boström6f28cf02015-12-07 23:17:15 +0100383 FILE* file = fopen(filename, "w");
384 if (!file) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100385 RTC_LOG(LS_ERROR) << "Failed to open trace file '" << filename
386 << "' for writing.";
Peter Boström6f28cf02015-12-07 23:17:15 +0100387 return false;
388 }
389 g_event_logger->Start(file, true);
390 return true;
391}
392
393void StopInternalCapture() {
jtteh7480da42017-07-07 11:02:15 -0700394 if (g_event_logger) {
395 g_event_logger->Stop();
396 }
Peter Boström6f28cf02015-12-07 23:17:15 +0100397}
398
399void ShutdownInternalTracer() {
400 StopInternalCapture();
Peter Boström455a2522015-12-18 17:00:25 +0100401 EventLogger* old_logger = rtc::AtomicOps::AcquireLoadPtr(&g_event_logger);
Peter Boström6f28cf02015-12-07 23:17:15 +0100402 RTC_DCHECK(old_logger);
403 RTC_CHECK(rtc::AtomicOps::CompareAndSwapPtr(
404 &g_event_logger, old_logger,
405 static_cast<EventLogger*>(nullptr)) == old_logger);
406 delete old_logger;
407 webrtc::SetupEventTracer(nullptr, nullptr);
408}
409
410} // namespace tracing
411} // namespace rtc