blob: 4393bff2985884a746ad3a330d962294afc6e60f [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
sakalf4433ef2016-08-08 04:10:13 -070014#include <string>
Peter Boström6f28cf02015-12-07 23:17:15 +010015#include <vector>
16
17#include "webrtc/base/checks.h"
18#include "webrtc/base/criticalsection.h"
19#include "webrtc/base/event.h"
20#include "webrtc/base/logging.h"
21#include "webrtc/base/platform_thread.h"
sakalf4433ef2016-08-08 04:10:13 -070022#include "webrtc/base/stringutils.h"
Peter Boström6f28cf02015-12-07 23:17:15 +010023#include "webrtc/base/timeutils.h"
24#include "webrtc/base/trace_event.h"
25
sakalf4433ef2016-08-08 04:10:13 -070026// This is a guesstimate that should be enough in most cases.
27static const size_t kEventLoggerArgsStrBufferInitialSize = 256;
28static const size_t kTraceArgBufferLength = 32;
29
tommi@webrtc.org7c64ed22015-03-17 14:25:37 +000030namespace webrtc {
31
32namespace {
33
Peter Boström6f28cf02015-12-07 23:17:15 +010034GetCategoryEnabledPtr g_get_category_enabled_ptr = nullptr;
35AddTraceEventPtr g_add_trace_event_ptr = nullptr;
tommi@webrtc.org7c64ed22015-03-17 14:25:37 +000036
37} // namespace
38
39void SetupEventTracer(GetCategoryEnabledPtr get_category_enabled_ptr,
40 AddTraceEventPtr add_trace_event_ptr) {
41 g_get_category_enabled_ptr = get_category_enabled_ptr;
42 g_add_trace_event_ptr = add_trace_event_ptr;
43}
44
tommi@webrtc.org7c64ed22015-03-17 14:25:37 +000045const unsigned char* EventTracer::GetCategoryEnabled(const char* name) {
46 if (g_get_category_enabled_ptr)
47 return g_get_category_enabled_ptr(name);
48
49 // A string with null terminator means category is disabled.
50 return reinterpret_cast<const unsigned char*>("\0");
51}
52
Peter Boström6f28cf02015-12-07 23:17:15 +010053// Arguments to this function (phase, etc.) are as defined in
54// webrtc/base/trace_event.h.
tommi@webrtc.org7c64ed22015-03-17 14:25:37 +000055void EventTracer::AddTraceEvent(char phase,
56 const unsigned char* category_enabled,
57 const char* name,
58 unsigned long long id,
59 int num_args,
60 const char** arg_names,
61 const unsigned char* arg_types,
62 const unsigned long long* arg_values,
63 unsigned char flags) {
64 if (g_add_trace_event_ptr) {
65 g_add_trace_event_ptr(phase,
66 category_enabled,
67 name,
68 id,
69 num_args,
70 arg_names,
71 arg_types,
72 arg_values,
73 flags);
74 }
75}
76
77} // namespace webrtc
Peter Boström6f28cf02015-12-07 23:17:15 +010078
79namespace rtc {
80namespace tracing {
81namespace {
82
83static bool EventTracingThreadFunc(void* params);
84
85// Atomic-int fast path for avoiding logging when disabled.
86static volatile int g_event_logging_active = 0;
87
88// TODO(pbos): Log metadata for all threads, etc.
89class EventLogger final {
90 public:
91 EventLogger()
92 : logging_thread_(EventTracingThreadFunc, this, "EventTracingThread"),
93 shutdown_event_(false, false) {}
94 ~EventLogger() { RTC_DCHECK(thread_checker_.CalledOnValidThread()); }
95
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
127// The TraceEvent format is documented here:
128// https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/preview
129 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) {
Peter Boströmdda8a832016-02-29 14:54:04 +0100192 RTC_DCHECK(thread_checker_.CalledOnValidThread());
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öm0ec9a9b2016-05-27 11:11:45 +0200213 logging_thread_.SetPriority(kLowPriority);
Peter Boström6f28cf02015-12-07 23:17:15 +0100214 }
215
216 void Stop() {
Peter Boströmdda8a832016-02-29 14:54:04 +0100217 RTC_DCHECK(thread_checker_.CalledOnValidThread());
218 TRACE_EVENT_INSTANT0("webrtc", "EventLogger::Stop");
Peter Boström6f28cf02015-12-07 23:17:15 +0100219 // Try to stop. Abort if we're not currently logging.
220 if (rtc::AtomicOps::CompareAndSwap(&g_event_logging_active, 1, 0) == 0)
221 return;
222
223 // Wake up logging thread to finish writing.
224 shutdown_event_.Set();
225 // Join the logging thread.
226 logging_thread_.Stop();
227 }
228
229 private:
sakalf4433ef2016-08-08 04:10:13 -0700230 struct TraceArg {
231 const char* name;
232 unsigned char type;
233 // Copied from webrtc/base/trace_event.h TraceValueUnion.
234 union TraceArgValue {
235 bool as_bool;
236 unsigned long long as_uint;
237 long long as_int;
238 double as_double;
239 const void* as_pointer;
240 const char* as_string;
241 } value;
242
243 // Assert that the size of the union is equal to the size of the as_uint
244 // field since we are assigning to arbitrary types using it.
245 static_assert(sizeof(TraceArgValue) == sizeof(unsigned long long),
246 "Size of TraceArg value union is not equal to the size of "
247 "the uint field of that union.");
248 };
249
Peter Boström6f28cf02015-12-07 23:17:15 +0100250 struct TraceEvent {
251 const char* name;
252 const unsigned char* category_enabled;
253 char phase;
sakalf4433ef2016-08-08 04:10:13 -0700254 std::vector<TraceArg> args;
Peter Boström6f28cf02015-12-07 23:17:15 +0100255 uint64_t timestamp;
256 int pid;
257 rtc::PlatformThreadId tid;
258 };
259
sakalf4433ef2016-08-08 04:10:13 -0700260 static std::string TraceArgValueAsString(TraceArg arg) {
261 std::string output;
262
263 if (arg.type == TRACE_VALUE_TYPE_STRING ||
264 arg.type == TRACE_VALUE_TYPE_COPY_STRING) {
265 // Space for every character to be an espaced character + two for
266 // quatation marks.
267 output.reserve(strlen(arg.value.as_string) * 2 + 2);
268 output += '\"';
269 const char* c = arg.value.as_string;
270 do {
271 if (*c == '"' || *c == '\\') {
272 output += '\\';
273 output += *c;
274 } else {
275 output += *c;
276 }
277 } while (*++c);
278 output += '\"';
279 } else {
280 output.resize(kTraceArgBufferLength);
281 size_t print_length = 0;
282 switch (arg.type) {
283 case TRACE_VALUE_TYPE_BOOL:
284 if (arg.value.as_bool) {
285 strcpy(&output[0], "true");
286 print_length = 4;
287 } else {
288 strcpy(&output[0], "false");
289 print_length = 5;
290 }
291 break;
292 case TRACE_VALUE_TYPE_UINT:
293 print_length = sprintfn(&output[0], kTraceArgBufferLength, "%llu",
294 arg.value.as_uint);
295 break;
296 case TRACE_VALUE_TYPE_INT:
297 print_length = sprintfn(&output[0], kTraceArgBufferLength, "%lld",
298 arg.value.as_int);
299 break;
300 case TRACE_VALUE_TYPE_DOUBLE:
301 print_length = sprintfn(&output[0], kTraceArgBufferLength, "%f",
302 arg.value.as_double);
303 break;
304 case TRACE_VALUE_TYPE_POINTER:
305 print_length = sprintfn(&output[0], kTraceArgBufferLength, "\"%p\"",
306 arg.value.as_pointer);
307 break;
308 }
309 size_t output_length = print_length < kTraceArgBufferLength
310 ? print_length
311 : kTraceArgBufferLength - 1;
312 // This will hopefully be very close to nop. On most implementations, it
313 // just writes null byte and sets the length field of the string.
314 output.resize(output_length);
315 }
316
317 return output;
318 }
319
Peter Boström6f28cf02015-12-07 23:17:15 +0100320 rtc::CriticalSection crit_;
321 std::vector<TraceEvent> trace_events_ GUARDED_BY(crit_);
322 rtc::PlatformThread logging_thread_;
323 rtc::Event shutdown_event_;
324 rtc::ThreadChecker thread_checker_;
325 FILE* output_file_ = nullptr;
326 bool output_file_owned_ = false;
327};
328
329static bool EventTracingThreadFunc(void* params) {
330 static_cast<EventLogger*>(params)->Log();
skvlad843b6f52016-07-22 21:45:35 -0700331 // False indicates that the thread function has done its job and doesn't need
332 // to be restarted again. Log() runs its own internal loop.
333 return false;
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) {
378 g_event_logger->Start(file, false);
379}
380
381bool StartInternalCapture(const char* filename) {
382 FILE* file = fopen(filename, "w");
383 if (!file) {
384 LOG(LS_ERROR) << "Failed to open trace file '" << filename
385 << "' for writing.";
386 return false;
387 }
388 g_event_logger->Start(file, true);
389 return true;
390}
391
392void StopInternalCapture() {
393 g_event_logger->Stop();
394}
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