blob: 31f4271d31e2a39db7b88413dc1868ea37cb7f2b [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>
13
sakalf4433ef2016-08-08 04:10:13 -070014#include <string>
Peter Boström6f28cf02015-12-07 23:17:15 +010015#include <vector>
16
Tommi8d2c5a82018-03-19 11:12:48 +010017#include "rtc_base/atomicops.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020018#include "rtc_base/checks.h"
19#include "rtc_base/criticalsection.h"
20#include "rtc_base/event.h"
21#include "rtc_base/logging.h"
22#include "rtc_base/platform_thread.h"
23#include "rtc_base/stringutils.h"
24#include "rtc_base/timeutils.h"
25#include "rtc_base/trace_event.h"
Peter Boström6f28cf02015-12-07 23:17:15 +010026
sakalf4433ef2016-08-08 04:10:13 -070027// This is a guesstimate that should be enough in most cases.
28static const size_t kEventLoggerArgsStrBufferInitialSize = 256;
29static const size_t kTraceArgBufferLength = 32;
30
tommi@webrtc.org7c64ed22015-03-17 14:25:37 +000031namespace webrtc {
32
33namespace {
34
Peter Boström6f28cf02015-12-07 23:17:15 +010035GetCategoryEnabledPtr g_get_category_enabled_ptr = nullptr;
36AddTraceEventPtr g_add_trace_event_ptr = nullptr;
tommi@webrtc.org7c64ed22015-03-17 14:25:37 +000037
38} // namespace
39
40void SetupEventTracer(GetCategoryEnabledPtr get_category_enabled_ptr,
41 AddTraceEventPtr add_trace_event_ptr) {
42 g_get_category_enabled_ptr = get_category_enabled_ptr;
43 g_add_trace_event_ptr = add_trace_event_ptr;
44}
45
tommi@webrtc.org7c64ed22015-03-17 14:25:37 +000046const unsigned char* EventTracer::GetCategoryEnabled(const char* name) {
47 if (g_get_category_enabled_ptr)
48 return g_get_category_enabled_ptr(name);
49
50 // A string with null terminator means category is disabled.
51 return reinterpret_cast<const unsigned char*>("\0");
52}
53
Peter Boström6f28cf02015-12-07 23:17:15 +010054// Arguments to this function (phase, etc.) are as defined in
kjellandere96c45b2017-06-30 10:45:21 -070055// webrtc/rtc_base/trace_event.h.
tommi@webrtc.org7c64ed22015-03-17 14:25:37 +000056void EventTracer::AddTraceEvent(char phase,
57 const unsigned char* category_enabled,
58 const char* name,
59 unsigned long long id,
60 int num_args,
61 const char** arg_names,
62 const unsigned char* arg_types,
63 const unsigned long long* arg_values,
64 unsigned char flags) {
65 if (g_add_trace_event_ptr) {
Yves Gerey665174f2018-06-19 15:03:05 +020066 g_add_trace_event_ptr(phase, category_enabled, name, id, num_args,
67 arg_names, arg_types, arg_values, flags);
tommi@webrtc.org7c64ed22015-03-17 14:25:37 +000068 }
69}
70
71} // namespace webrtc
Peter Boström6f28cf02015-12-07 23:17:15 +010072
73namespace rtc {
74namespace tracing {
75namespace {
76
tommi0f8b4032017-02-22 11:22:05 -080077static void EventTracingThreadFunc(void* params);
Peter Boström6f28cf02015-12-07 23:17:15 +010078
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()
tommi0f8b4032017-02-22 11:22:05 -080086 : logging_thread_(EventTracingThreadFunc,
87 this,
88 "EventTracingThread",
89 kLowPriority),
Peter Boström6f28cf02015-12-07 23:17:15 +010090 shutdown_event_(false, false) {}
91 ~EventLogger() { RTC_DCHECK(thread_checker_.CalledOnValidThread()); }
92
93 void AddTraceEvent(const char* name,
94 const unsigned char* category_enabled,
95 char phase,
sakalf4433ef2016-08-08 04:10:13 -070096 int num_args,
97 const char** arg_names,
98 const unsigned char* arg_types,
99 const unsigned long long* arg_values,
Peter Boström6f28cf02015-12-07 23:17:15 +0100100 uint64_t timestamp,
101 int pid,
102 rtc::PlatformThreadId thread_id) {
sakalf4433ef2016-08-08 04:10:13 -0700103 std::vector<TraceArg> args(num_args);
104 for (int i = 0; i < num_args; ++i) {
105 TraceArg& arg = args[i];
106 arg.name = arg_names[i];
107 arg.type = arg_types[i];
108 arg.value.as_uint = arg_values[i];
109
110 // Value is a pointer to a temporary string, so we have to make a copy.
111 if (arg.type == TRACE_VALUE_TYPE_COPY_STRING) {
112 // Space for the string and for the terminating null character.
113 size_t str_length = strlen(arg.value.as_string) + 1;
114 char* str_copy = new char[str_length];
115 memcpy(str_copy, arg.value.as_string, str_length);
116 arg.value.as_string = str_copy;
117 }
118 }
Peter Boström6f28cf02015-12-07 23:17:15 +0100119 rtc::CritScope lock(&crit_);
120 trace_events_.push_back(
sakalf4433ef2016-08-08 04:10:13 -0700121 {name, category_enabled, phase, args, timestamp, 1, thread_id});
Peter Boström6f28cf02015-12-07 23:17:15 +0100122 }
123
Yves Gerey665174f2018-06-19 15:03:05 +0200124 // The TraceEvent format is documented here:
125 // https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/preview
Peter Boström6f28cf02015-12-07 23:17:15 +0100126 void Log() {
127 RTC_DCHECK(output_file_);
128 static const int kLoggingIntervalMs = 100;
129 fprintf(output_file_, "{ \"traceEvents\": [\n");
130 bool has_logged_event = false;
131 while (true) {
132 bool shutting_down = shutdown_event_.Wait(kLoggingIntervalMs);
133 std::vector<TraceEvent> events;
134 {
135 rtc::CritScope lock(&crit_);
136 trace_events_.swap(events);
137 }
sakalf4433ef2016-08-08 04:10:13 -0700138 std::string args_str;
139 args_str.reserve(kEventLoggerArgsStrBufferInitialSize);
140 for (TraceEvent& e : events) {
141 args_str.clear();
142 if (!e.args.empty()) {
143 args_str += ", \"args\": {";
144 bool is_first_argument = true;
145 for (TraceArg& arg : e.args) {
146 if (!is_first_argument)
147 args_str += ",";
148 is_first_argument = false;
149 args_str += " \"";
150 args_str += arg.name;
151 args_str += "\": ";
152 args_str += TraceArgValueAsString(arg);
153
154 // Delete our copy of the string.
155 if (arg.type == TRACE_VALUE_TYPE_COPY_STRING) {
156 delete[] arg.value.as_string;
157 arg.value.as_string = nullptr;
158 }
159 }
160 args_str += " }";
161 }
Peter Boström6f28cf02015-12-07 23:17:15 +0100162 fprintf(output_file_,
163 "%s{ \"name\": \"%s\""
164 ", \"cat\": \"%s\""
165 ", \"ph\": \"%c\""
166 ", \"ts\": %" PRIu64
167 ", \"pid\": %d"
Peter Boström43e4e232015-12-11 20:29:35 +0100168#if defined(WEBRTC_WIN)
169 ", \"tid\": %lu"
170#else
171 ", \"tid\": %d"
172#endif // defined(WEBRTC_WIN)
sakalf4433ef2016-08-08 04:10:13 -0700173 "%s"
Peter Boström43e4e232015-12-11 20:29:35 +0100174 "}\n",
Peter Boström6f28cf02015-12-07 23:17:15 +0100175 has_logged_event ? "," : " ", e.name, e.category_enabled,
sakalf4433ef2016-08-08 04:10:13 -0700176 e.phase, e.timestamp, e.pid, e.tid, args_str.c_str());
Peter Boström6f28cf02015-12-07 23:17:15 +0100177 has_logged_event = true;
178 }
179 if (shutting_down)
180 break;
181 }
182 fprintf(output_file_, "]}\n");
183 if (output_file_owned_)
184 fclose(output_file_);
185 output_file_ = nullptr;
186 }
187
188 void Start(FILE* file, bool owned) {
Peter Boströmdda8a832016-02-29 14:54:04 +0100189 RTC_DCHECK(thread_checker_.CalledOnValidThread());
Peter Boström6f28cf02015-12-07 23:17:15 +0100190 RTC_DCHECK(file);
191 RTC_DCHECK(!output_file_);
192 output_file_ = file;
193 output_file_owned_ = owned;
194 {
195 rtc::CritScope lock(&crit_);
196 // Since the atomic fast-path for adding events to the queue can be
197 // bypassed while the logging thread is shutting down there may be some
198 // stale events in the queue, hence the vector needs to be cleared to not
199 // log events from a previous logging session (which may be days old).
200 trace_events_.clear();
201 }
202 // Enable event logging (fast-path). This should be disabled since starting
203 // shouldn't be done twice.
204 RTC_CHECK_EQ(0,
205 rtc::AtomicOps::CompareAndSwap(&g_event_logging_active, 0, 1));
206
207 // Finally start, everything should be set up now.
208 logging_thread_.Start();
Peter Boströmdda8a832016-02-29 14:54:04 +0100209 TRACE_EVENT_INSTANT0("webrtc", "EventLogger::Start");
Peter Boström6f28cf02015-12-07 23:17:15 +0100210 }
211
212 void Stop() {
Peter Boströmdda8a832016-02-29 14:54:04 +0100213 RTC_DCHECK(thread_checker_.CalledOnValidThread());
214 TRACE_EVENT_INSTANT0("webrtc", "EventLogger::Stop");
Peter Boström6f28cf02015-12-07 23:17:15 +0100215 // Try to stop. Abort if we're not currently logging.
216 if (rtc::AtomicOps::CompareAndSwap(&g_event_logging_active, 1, 0) == 0)
217 return;
218
219 // Wake up logging thread to finish writing.
220 shutdown_event_.Set();
221 // Join the logging thread.
222 logging_thread_.Stop();
223 }
224
225 private:
sakalf4433ef2016-08-08 04:10:13 -0700226 struct TraceArg {
227 const char* name;
228 unsigned char type;
kjellandere96c45b2017-06-30 10:45:21 -0700229 // Copied from webrtc/rtc_base/trace_event.h TraceValueUnion.
sakalf4433ef2016-08-08 04:10:13 -0700230 union TraceArgValue {
231 bool as_bool;
232 unsigned long long as_uint;
233 long long as_int;
234 double as_double;
235 const void* as_pointer;
236 const char* as_string;
237 } value;
238
239 // Assert that the size of the union is equal to the size of the as_uint
240 // field since we are assigning to arbitrary types using it.
241 static_assert(sizeof(TraceArgValue) == sizeof(unsigned long long),
242 "Size of TraceArg value union is not equal to the size of "
243 "the uint field of that union.");
244 };
245
Peter Boström6f28cf02015-12-07 23:17:15 +0100246 struct TraceEvent {
247 const char* name;
248 const unsigned char* category_enabled;
249 char phase;
sakalf4433ef2016-08-08 04:10:13 -0700250 std::vector<TraceArg> args;
Peter Boström6f28cf02015-12-07 23:17:15 +0100251 uint64_t timestamp;
252 int pid;
253 rtc::PlatformThreadId tid;
254 };
255
sakalf4433ef2016-08-08 04:10:13 -0700256 static std::string TraceArgValueAsString(TraceArg arg) {
257 std::string output;
258
259 if (arg.type == TRACE_VALUE_TYPE_STRING ||
260 arg.type == TRACE_VALUE_TYPE_COPY_STRING) {
261 // Space for every character to be an espaced character + two for
262 // quatation marks.
263 output.reserve(strlen(arg.value.as_string) * 2 + 2);
264 output += '\"';
265 const char* c = arg.value.as_string;
266 do {
267 if (*c == '"' || *c == '\\') {
268 output += '\\';
269 output += *c;
270 } else {
271 output += *c;
272 }
273 } while (*++c);
274 output += '\"';
275 } else {
276 output.resize(kTraceArgBufferLength);
277 size_t print_length = 0;
278 switch (arg.type) {
279 case TRACE_VALUE_TYPE_BOOL:
280 if (arg.value.as_bool) {
281 strcpy(&output[0], "true");
282 print_length = 4;
283 } else {
284 strcpy(&output[0], "false");
285 print_length = 5;
286 }
287 break;
288 case TRACE_VALUE_TYPE_UINT:
289 print_length = sprintfn(&output[0], kTraceArgBufferLength, "%llu",
290 arg.value.as_uint);
291 break;
292 case TRACE_VALUE_TYPE_INT:
293 print_length = sprintfn(&output[0], kTraceArgBufferLength, "%lld",
294 arg.value.as_int);
295 break;
296 case TRACE_VALUE_TYPE_DOUBLE:
297 print_length = sprintfn(&output[0], kTraceArgBufferLength, "%f",
298 arg.value.as_double);
299 break;
300 case TRACE_VALUE_TYPE_POINTER:
301 print_length = sprintfn(&output[0], kTraceArgBufferLength, "\"%p\"",
302 arg.value.as_pointer);
303 break;
304 }
305 size_t output_length = print_length < kTraceArgBufferLength
306 ? print_length
307 : kTraceArgBufferLength - 1;
308 // This will hopefully be very close to nop. On most implementations, it
309 // just writes null byte and sets the length field of the string.
310 output.resize(output_length);
311 }
312
313 return output;
314 }
315
Peter Boström6f28cf02015-12-07 23:17:15 +0100316 rtc::CriticalSection crit_;
danilchap3c6abd22017-09-06 05:46:29 -0700317 std::vector<TraceEvent> trace_events_ RTC_GUARDED_BY(crit_);
Peter Boström6f28cf02015-12-07 23:17:15 +0100318 rtc::PlatformThread logging_thread_;
319 rtc::Event shutdown_event_;
320 rtc::ThreadChecker thread_checker_;
321 FILE* output_file_ = nullptr;
322 bool output_file_owned_ = false;
323};
324
tommi0f8b4032017-02-22 11:22:05 -0800325static void EventTracingThreadFunc(void* params) {
Peter Boström6f28cf02015-12-07 23:17:15 +0100326 static_cast<EventLogger*>(params)->Log();
Peter Boström6f28cf02015-12-07 23:17:15 +0100327}
328
329static EventLogger* volatile g_event_logger = nullptr;
330static const char* const kDisabledTracePrefix = TRACE_DISABLED_BY_DEFAULT("");
331const unsigned char* InternalGetCategoryEnabled(const char* name) {
332 const char* prefix_ptr = &kDisabledTracePrefix[0];
333 const char* name_ptr = name;
334 // Check whether name contains the default-disabled prefix.
335 while (*prefix_ptr == *name_ptr && *prefix_ptr != '\0') {
336 ++prefix_ptr;
337 ++name_ptr;
338 }
339 return reinterpret_cast<const unsigned char*>(*prefix_ptr == '\0' ? ""
340 : name);
341}
342
343void InternalAddTraceEvent(char phase,
344 const unsigned char* category_enabled,
345 const char* name,
346 unsigned long long id,
347 int num_args,
348 const char** arg_names,
349 const unsigned char* arg_types,
350 const unsigned long long* arg_values,
351 unsigned char flags) {
352 // Fast path for when event tracing is inactive.
353 if (rtc::AtomicOps::AcquireLoad(&g_event_logging_active) == 0)
354 return;
355
sakalf4433ef2016-08-08 04:10:13 -0700356 g_event_logger->AddTraceEvent(name, category_enabled, phase, num_args,
357 arg_names, arg_types, arg_values,
Peter Boström6f28cf02015-12-07 23:17:15 +0100358 rtc::TimeMicros(), 1, rtc::CurrentThreadId());
359}
360
361} // namespace
362
363void SetupInternalTracer() {
364 RTC_CHECK(rtc::AtomicOps::CompareAndSwapPtr(
365 &g_event_logger, static_cast<EventLogger*>(nullptr),
366 new EventLogger()) == nullptr);
Peter Boström6f28cf02015-12-07 23:17:15 +0100367 webrtc::SetupEventTracer(InternalGetCategoryEnabled, InternalAddTraceEvent);
368}
369
370void StartInternalCaptureToFile(FILE* file) {
jtteh7480da42017-07-07 11:02:15 -0700371 if (g_event_logger) {
372 g_event_logger->Start(file, false);
373 }
Peter Boström6f28cf02015-12-07 23:17:15 +0100374}
375
376bool StartInternalCapture(const char* filename) {
jtteh7480da42017-07-07 11:02:15 -0700377 if (!g_event_logger)
378 return false;
379
Peter Boström6f28cf02015-12-07 23:17:15 +0100380 FILE* file = fopen(filename, "w");
381 if (!file) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100382 RTC_LOG(LS_ERROR) << "Failed to open trace file '" << filename
383 << "' for writing.";
Peter Boström6f28cf02015-12-07 23:17:15 +0100384 return false;
385 }
386 g_event_logger->Start(file, true);
387 return true;
388}
389
390void StopInternalCapture() {
jtteh7480da42017-07-07 11:02:15 -0700391 if (g_event_logger) {
392 g_event_logger->Stop();
393 }
Peter Boström6f28cf02015-12-07 23:17:15 +0100394}
395
396void ShutdownInternalTracer() {
397 StopInternalCapture();
Peter Boström455a2522015-12-18 17:00:25 +0100398 EventLogger* old_logger = rtc::AtomicOps::AcquireLoadPtr(&g_event_logger);
Peter Boström6f28cf02015-12-07 23:17:15 +0100399 RTC_DCHECK(old_logger);
400 RTC_CHECK(rtc::AtomicOps::CompareAndSwapPtr(
401 &g_event_logger, old_logger,
402 static_cast<EventLogger*>(nullptr)) == old_logger);
403 delete old_logger;
404 webrtc::SetupEventTracer(nullptr, nullptr);
405}
406
407} // namespace tracing
408} // namespace rtc