blob: 3461ec625afd4eab246975954b1a66ea6ade9582 [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) {
66 g_add_trace_event_ptr(phase,
67 category_enabled,
68 name,
69 id,
70 num_args,
71 arg_names,
72 arg_types,
73 arg_values,
74 flags);
75 }
76}
77
78} // namespace webrtc
Peter Boström6f28cf02015-12-07 23:17:15 +010079
80namespace rtc {
81namespace tracing {
82namespace {
83
tommi0f8b4032017-02-22 11:22:05 -080084static void EventTracingThreadFunc(void* params);
Peter Boström6f28cf02015-12-07 23:17:15 +010085
86// Atomic-int fast path for avoiding logging when disabled.
87static volatile int g_event_logging_active = 0;
88
89// TODO(pbos): Log metadata for all threads, etc.
90class EventLogger final {
91 public:
92 EventLogger()
tommi0f8b4032017-02-22 11:22:05 -080093 : logging_thread_(EventTracingThreadFunc,
94 this,
95 "EventTracingThread",
96 kLowPriority),
Peter Boström6f28cf02015-12-07 23:17:15 +010097 shutdown_event_(false, false) {}
98 ~EventLogger() { RTC_DCHECK(thread_checker_.CalledOnValidThread()); }
99
100 void AddTraceEvent(const char* name,
101 const unsigned char* category_enabled,
102 char phase,
sakalf4433ef2016-08-08 04:10:13 -0700103 int num_args,
104 const char** arg_names,
105 const unsigned char* arg_types,
106 const unsigned long long* arg_values,
Peter Boström6f28cf02015-12-07 23:17:15 +0100107 uint64_t timestamp,
108 int pid,
109 rtc::PlatformThreadId thread_id) {
sakalf4433ef2016-08-08 04:10:13 -0700110 std::vector<TraceArg> args(num_args);
111 for (int i = 0; i < num_args; ++i) {
112 TraceArg& arg = args[i];
113 arg.name = arg_names[i];
114 arg.type = arg_types[i];
115 arg.value.as_uint = arg_values[i];
116
117 // Value is a pointer to a temporary string, so we have to make a copy.
118 if (arg.type == TRACE_VALUE_TYPE_COPY_STRING) {
119 // Space for the string and for the terminating null character.
120 size_t str_length = strlen(arg.value.as_string) + 1;
121 char* str_copy = new char[str_length];
122 memcpy(str_copy, arg.value.as_string, str_length);
123 arg.value.as_string = str_copy;
124 }
125 }
Peter Boström6f28cf02015-12-07 23:17:15 +0100126 rtc::CritScope lock(&crit_);
127 trace_events_.push_back(
sakalf4433ef2016-08-08 04:10:13 -0700128 {name, category_enabled, phase, args, timestamp, 1, thread_id});
Peter Boström6f28cf02015-12-07 23:17:15 +0100129 }
130
131// The TraceEvent format is documented here:
132// https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/preview
133 void Log() {
134 RTC_DCHECK(output_file_);
135 static const int kLoggingIntervalMs = 100;
136 fprintf(output_file_, "{ \"traceEvents\": [\n");
137 bool has_logged_event = false;
138 while (true) {
139 bool shutting_down = shutdown_event_.Wait(kLoggingIntervalMs);
140 std::vector<TraceEvent> events;
141 {
142 rtc::CritScope lock(&crit_);
143 trace_events_.swap(events);
144 }
sakalf4433ef2016-08-08 04:10:13 -0700145 std::string args_str;
146 args_str.reserve(kEventLoggerArgsStrBufferInitialSize);
147 for (TraceEvent& e : events) {
148 args_str.clear();
149 if (!e.args.empty()) {
150 args_str += ", \"args\": {";
151 bool is_first_argument = true;
152 for (TraceArg& arg : e.args) {
153 if (!is_first_argument)
154 args_str += ",";
155 is_first_argument = false;
156 args_str += " \"";
157 args_str += arg.name;
158 args_str += "\": ";
159 args_str += TraceArgValueAsString(arg);
160
161 // Delete our copy of the string.
162 if (arg.type == TRACE_VALUE_TYPE_COPY_STRING) {
163 delete[] arg.value.as_string;
164 arg.value.as_string = nullptr;
165 }
166 }
167 args_str += " }";
168 }
Peter Boström6f28cf02015-12-07 23:17:15 +0100169 fprintf(output_file_,
170 "%s{ \"name\": \"%s\""
171 ", \"cat\": \"%s\""
172 ", \"ph\": \"%c\""
173 ", \"ts\": %" PRIu64
174 ", \"pid\": %d"
Peter Boström43e4e232015-12-11 20:29:35 +0100175#if defined(WEBRTC_WIN)
176 ", \"tid\": %lu"
177#else
178 ", \"tid\": %d"
179#endif // defined(WEBRTC_WIN)
sakalf4433ef2016-08-08 04:10:13 -0700180 "%s"
Peter Boström43e4e232015-12-11 20:29:35 +0100181 "}\n",
Peter Boström6f28cf02015-12-07 23:17:15 +0100182 has_logged_event ? "," : " ", e.name, e.category_enabled,
sakalf4433ef2016-08-08 04:10:13 -0700183 e.phase, e.timestamp, e.pid, e.tid, args_str.c_str());
Peter Boström6f28cf02015-12-07 23:17:15 +0100184 has_logged_event = true;
185 }
186 if (shutting_down)
187 break;
188 }
189 fprintf(output_file_, "]}\n");
190 if (output_file_owned_)
191 fclose(output_file_);
192 output_file_ = nullptr;
193 }
194
195 void Start(FILE* file, bool owned) {
Peter Boströmdda8a832016-02-29 14:54:04 +0100196 RTC_DCHECK(thread_checker_.CalledOnValidThread());
Peter Boström6f28cf02015-12-07 23:17:15 +0100197 RTC_DCHECK(file);
198 RTC_DCHECK(!output_file_);
199 output_file_ = file;
200 output_file_owned_ = owned;
201 {
202 rtc::CritScope lock(&crit_);
203 // Since the atomic fast-path for adding events to the queue can be
204 // bypassed while the logging thread is shutting down there may be some
205 // stale events in the queue, hence the vector needs to be cleared to not
206 // log events from a previous logging session (which may be days old).
207 trace_events_.clear();
208 }
209 // Enable event logging (fast-path). This should be disabled since starting
210 // shouldn't be done twice.
211 RTC_CHECK_EQ(0,
212 rtc::AtomicOps::CompareAndSwap(&g_event_logging_active, 0, 1));
213
214 // Finally start, everything should be set up now.
215 logging_thread_.Start();
Peter Boströmdda8a832016-02-29 14:54:04 +0100216 TRACE_EVENT_INSTANT0("webrtc", "EventLogger::Start");
Peter Boström6f28cf02015-12-07 23:17:15 +0100217 }
218
219 void Stop() {
Peter Boströmdda8a832016-02-29 14:54:04 +0100220 RTC_DCHECK(thread_checker_.CalledOnValidThread());
221 TRACE_EVENT_INSTANT0("webrtc", "EventLogger::Stop");
Peter Boström6f28cf02015-12-07 23:17:15 +0100222 // Try to stop. Abort if we're not currently logging.
223 if (rtc::AtomicOps::CompareAndSwap(&g_event_logging_active, 1, 0) == 0)
224 return;
225
226 // Wake up logging thread to finish writing.
227 shutdown_event_.Set();
228 // Join the logging thread.
229 logging_thread_.Stop();
230 }
231
232 private:
sakalf4433ef2016-08-08 04:10:13 -0700233 struct TraceArg {
234 const char* name;
235 unsigned char type;
kjellandere96c45b2017-06-30 10:45:21 -0700236 // Copied from webrtc/rtc_base/trace_event.h TraceValueUnion.
sakalf4433ef2016-08-08 04:10:13 -0700237 union TraceArgValue {
238 bool as_bool;
239 unsigned long long as_uint;
240 long long as_int;
241 double as_double;
242 const void* as_pointer;
243 const char* as_string;
244 } value;
245
246 // Assert that the size of the union is equal to the size of the as_uint
247 // field since we are assigning to arbitrary types using it.
248 static_assert(sizeof(TraceArgValue) == sizeof(unsigned long long),
249 "Size of TraceArg value union is not equal to the size of "
250 "the uint field of that union.");
251 };
252
Peter Boström6f28cf02015-12-07 23:17:15 +0100253 struct TraceEvent {
254 const char* name;
255 const unsigned char* category_enabled;
256 char phase;
sakalf4433ef2016-08-08 04:10:13 -0700257 std::vector<TraceArg> args;
Peter Boström6f28cf02015-12-07 23:17:15 +0100258 uint64_t timestamp;
259 int pid;
260 rtc::PlatformThreadId tid;
261 };
262
sakalf4433ef2016-08-08 04:10:13 -0700263 static std::string TraceArgValueAsString(TraceArg arg) {
264 std::string output;
265
266 if (arg.type == TRACE_VALUE_TYPE_STRING ||
267 arg.type == TRACE_VALUE_TYPE_COPY_STRING) {
268 // Space for every character to be an espaced character + two for
269 // quatation marks.
270 output.reserve(strlen(arg.value.as_string) * 2 + 2);
271 output += '\"';
272 const char* c = arg.value.as_string;
273 do {
274 if (*c == '"' || *c == '\\') {
275 output += '\\';
276 output += *c;
277 } else {
278 output += *c;
279 }
280 } while (*++c);
281 output += '\"';
282 } else {
283 output.resize(kTraceArgBufferLength);
284 size_t print_length = 0;
285 switch (arg.type) {
286 case TRACE_VALUE_TYPE_BOOL:
287 if (arg.value.as_bool) {
288 strcpy(&output[0], "true");
289 print_length = 4;
290 } else {
291 strcpy(&output[0], "false");
292 print_length = 5;
293 }
294 break;
295 case TRACE_VALUE_TYPE_UINT:
296 print_length = sprintfn(&output[0], kTraceArgBufferLength, "%llu",
297 arg.value.as_uint);
298 break;
299 case TRACE_VALUE_TYPE_INT:
300 print_length = sprintfn(&output[0], kTraceArgBufferLength, "%lld",
301 arg.value.as_int);
302 break;
303 case TRACE_VALUE_TYPE_DOUBLE:
304 print_length = sprintfn(&output[0], kTraceArgBufferLength, "%f",
305 arg.value.as_double);
306 break;
307 case TRACE_VALUE_TYPE_POINTER:
308 print_length = sprintfn(&output[0], kTraceArgBufferLength, "\"%p\"",
309 arg.value.as_pointer);
310 break;
311 }
312 size_t output_length = print_length < kTraceArgBufferLength
313 ? print_length
314 : kTraceArgBufferLength - 1;
315 // This will hopefully be very close to nop. On most implementations, it
316 // just writes null byte and sets the length field of the string.
317 output.resize(output_length);
318 }
319
320 return output;
321 }
322
Peter Boström6f28cf02015-12-07 23:17:15 +0100323 rtc::CriticalSection crit_;
danilchap3c6abd22017-09-06 05:46:29 -0700324 std::vector<TraceEvent> trace_events_ RTC_GUARDED_BY(crit_);
Peter Boström6f28cf02015-12-07 23:17:15 +0100325 rtc::PlatformThread logging_thread_;
326 rtc::Event shutdown_event_;
327 rtc::ThreadChecker thread_checker_;
328 FILE* output_file_ = nullptr;
329 bool output_file_owned_ = false;
330};
331
tommi0f8b4032017-02-22 11:22:05 -0800332static void EventTracingThreadFunc(void* params) {
Peter Boström6f28cf02015-12-07 23:17:15 +0100333 static_cast<EventLogger*>(params)->Log();
Peter Boström6f28cf02015-12-07 23:17:15 +0100334}
335
336static EventLogger* volatile g_event_logger = nullptr;
337static const char* const kDisabledTracePrefix = TRACE_DISABLED_BY_DEFAULT("");
338const unsigned char* InternalGetCategoryEnabled(const char* name) {
339 const char* prefix_ptr = &kDisabledTracePrefix[0];
340 const char* name_ptr = name;
341 // Check whether name contains the default-disabled prefix.
342 while (*prefix_ptr == *name_ptr && *prefix_ptr != '\0') {
343 ++prefix_ptr;
344 ++name_ptr;
345 }
346 return reinterpret_cast<const unsigned char*>(*prefix_ptr == '\0' ? ""
347 : name);
348}
349
350void InternalAddTraceEvent(char phase,
351 const unsigned char* category_enabled,
352 const char* name,
353 unsigned long long id,
354 int num_args,
355 const char** arg_names,
356 const unsigned char* arg_types,
357 const unsigned long long* arg_values,
358 unsigned char flags) {
359 // Fast path for when event tracing is inactive.
360 if (rtc::AtomicOps::AcquireLoad(&g_event_logging_active) == 0)
361 return;
362
sakalf4433ef2016-08-08 04:10:13 -0700363 g_event_logger->AddTraceEvent(name, category_enabled, phase, num_args,
364 arg_names, arg_types, arg_values,
Peter Boström6f28cf02015-12-07 23:17:15 +0100365 rtc::TimeMicros(), 1, rtc::CurrentThreadId());
366}
367
368} // namespace
369
370void SetupInternalTracer() {
371 RTC_CHECK(rtc::AtomicOps::CompareAndSwapPtr(
372 &g_event_logger, static_cast<EventLogger*>(nullptr),
373 new EventLogger()) == nullptr);
Peter Boström6f28cf02015-12-07 23:17:15 +0100374 webrtc::SetupEventTracer(InternalGetCategoryEnabled, InternalAddTraceEvent);
375}
376
377void StartInternalCaptureToFile(FILE* file) {
jtteh7480da42017-07-07 11:02:15 -0700378 if (g_event_logger) {
379 g_event_logger->Start(file, false);
380 }
Peter Boström6f28cf02015-12-07 23:17:15 +0100381}
382
383bool StartInternalCapture(const char* filename) {
jtteh7480da42017-07-07 11:02:15 -0700384 if (!g_event_logger)
385 return false;
386
Peter Boström6f28cf02015-12-07 23:17:15 +0100387 FILE* file = fopen(filename, "w");
388 if (!file) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100389 RTC_LOG(LS_ERROR) << "Failed to open trace file '" << filename
390 << "' for writing.";
Peter Boström6f28cf02015-12-07 23:17:15 +0100391 return false;
392 }
393 g_event_logger->Start(file, true);
394 return true;
395}
396
397void StopInternalCapture() {
jtteh7480da42017-07-07 11:02:15 -0700398 if (g_event_logger) {
399 g_event_logger->Stop();
400 }
Peter Boström6f28cf02015-12-07 23:17:15 +0100401}
402
403void ShutdownInternalTracer() {
404 StopInternalCapture();
Peter Boström455a2522015-12-18 17:00:25 +0100405 EventLogger* old_logger = rtc::AtomicOps::AcquireLoadPtr(&g_event_logger);
Peter Boström6f28cf02015-12-07 23:17:15 +0100406 RTC_DCHECK(old_logger);
407 RTC_CHECK(rtc::AtomicOps::CompareAndSwapPtr(
408 &g_event_logger, old_logger,
409 static_cast<EventLogger*>(nullptr)) == old_logger);
410 delete old_logger;
411 webrtc::SetupEventTracer(nullptr, nullptr);
412}
413
414} // namespace tracing
415} // namespace rtc