1 /*
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  */
10 #include "rtc_base/event_tracer.h"
11 
12 #include <inttypes.h>
13 #include <stdint.h>
14 #include <stdio.h>
15 #include <string.h>
16 
17 #include <string>
18 #include <vector>
19 
20 #include "rtc_base/atomic_ops.h"
21 #include "rtc_base/checks.h"
22 #include "rtc_base/event.h"
23 #include "rtc_base/logging.h"
24 #include "rtc_base/platform_thread.h"
25 #include "rtc_base/platform_thread_types.h"
26 #include "rtc_base/synchronization/mutex.h"
27 #include "rtc_base/thread_annotations.h"
28 #include "rtc_base/thread_checker.h"
29 #include "rtc_base/time_utils.h"
30 #include "rtc_base/trace_event.h"
31 
32 // This is a guesstimate that should be enough in most cases.
33 static const size_t kEventLoggerArgsStrBufferInitialSize = 256;
34 static const size_t kTraceArgBufferLength = 32;
35 
36 namespace webrtc {
37 
38 namespace {
39 
40 GetCategoryEnabledPtr g_get_category_enabled_ptr = nullptr;
41 AddTraceEventPtr g_add_trace_event_ptr = nullptr;
42 
43 }  // namespace
44 
SetupEventTracer(GetCategoryEnabledPtr get_category_enabled_ptr,AddTraceEventPtr add_trace_event_ptr)45 void SetupEventTracer(GetCategoryEnabledPtr get_category_enabled_ptr,
46                       AddTraceEventPtr add_trace_event_ptr) {
47   g_get_category_enabled_ptr = get_category_enabled_ptr;
48   g_add_trace_event_ptr = add_trace_event_ptr;
49 }
50 
GetCategoryEnabled(const char * name)51 const unsigned char* EventTracer::GetCategoryEnabled(const char* name) {
52   if (g_get_category_enabled_ptr)
53     return g_get_category_enabled_ptr(name);
54 
55   // A string with null terminator means category is disabled.
56   return reinterpret_cast<const unsigned char*>("\0");
57 }
58 
59 // Arguments to this function (phase, etc.) are as defined in
60 // webrtc/rtc_base/trace_event.h.
AddTraceEvent(char phase,const unsigned char * category_enabled,const char * name,unsigned long long id,int num_args,const char ** arg_names,const unsigned char * arg_types,const unsigned long long * arg_values,unsigned char flags)61 void EventTracer::AddTraceEvent(char phase,
62                                 const unsigned char* category_enabled,
63                                 const char* name,
64                                 unsigned long long id,
65                                 int num_args,
66                                 const char** arg_names,
67                                 const unsigned char* arg_types,
68                                 const unsigned long long* arg_values,
69                                 unsigned char flags) {
70   if (g_add_trace_event_ptr) {
71     g_add_trace_event_ptr(phase, category_enabled, name, id, num_args,
72                           arg_names, arg_types, arg_values, flags);
73   }
74 }
75 
76 }  // namespace webrtc
77 
78 namespace rtc {
79 namespace tracing {
80 namespace {
81 
82 static void EventTracingThreadFunc(void* params);
83 
84 // Atomic-int fast path for avoiding logging when disabled.
85 static volatile int g_event_logging_active = 0;
86 
87 // TODO(pbos): Log metadata for all threads, etc.
88 class EventLogger final {
89  public:
EventLogger()90   EventLogger()
91       : logging_thread_(EventTracingThreadFunc,
92                         this,
93                         "EventTracingThread",
94                         kLowPriority) {}
~EventLogger()95   ~EventLogger() { RTC_DCHECK(thread_checker_.IsCurrent()); }
96 
AddTraceEvent(const char * name,const unsigned char * category_enabled,char phase,int num_args,const char ** arg_names,const unsigned char * arg_types,const unsigned long long * arg_values,uint64_t timestamp,int pid,rtc::PlatformThreadId thread_id)97   void AddTraceEvent(const char* name,
98                      const unsigned char* category_enabled,
99                      char phase,
100                      int num_args,
101                      const char** arg_names,
102                      const unsigned char* arg_types,
103                      const unsigned long long* arg_values,
104                      uint64_t timestamp,
105                      int pid,
106                      rtc::PlatformThreadId thread_id) {
107     std::vector<TraceArg> args(num_args);
108     for (int i = 0; i < num_args; ++i) {
109       TraceArg& arg = args[i];
110       arg.name = arg_names[i];
111       arg.type = arg_types[i];
112       arg.value.as_uint = arg_values[i];
113 
114       // Value is a pointer to a temporary string, so we have to make a copy.
115       if (arg.type == TRACE_VALUE_TYPE_COPY_STRING) {
116         // Space for the string and for the terminating null character.
117         size_t str_length = strlen(arg.value.as_string) + 1;
118         char* str_copy = new char[str_length];
119         memcpy(str_copy, arg.value.as_string, str_length);
120         arg.value.as_string = str_copy;
121       }
122     }
123     webrtc::MutexLock lock(&mutex_);
124     trace_events_.push_back(
125         {name, category_enabled, phase, args, timestamp, 1, thread_id});
126   }
127 
128   // The TraceEvent format is documented here:
129   // https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/preview
Log()130   void Log() {
131     RTC_DCHECK(output_file_);
132     static const int kLoggingIntervalMs = 100;
133     fprintf(output_file_, "{ \"traceEvents\": [\n");
134     bool has_logged_event = false;
135     while (true) {
136       bool shutting_down = shutdown_event_.Wait(kLoggingIntervalMs);
137       std::vector<TraceEvent> events;
138       {
139         webrtc::MutexLock lock(&mutex_);
140         trace_events_.swap(events);
141       }
142       std::string args_str;
143       args_str.reserve(kEventLoggerArgsStrBufferInitialSize);
144       for (TraceEvent& e : events) {
145         args_str.clear();
146         if (!e.args.empty()) {
147           args_str += ", \"args\": {";
148           bool is_first_argument = true;
149           for (TraceArg& arg : e.args) {
150             if (!is_first_argument)
151               args_str += ",";
152             is_first_argument = false;
153             args_str += " \"";
154             args_str += arg.name;
155             args_str += "\": ";
156             args_str += TraceArgValueAsString(arg);
157 
158             // Delete our copy of the string.
159             if (arg.type == TRACE_VALUE_TYPE_COPY_STRING) {
160               delete[] arg.value.as_string;
161               arg.value.as_string = nullptr;
162             }
163           }
164           args_str += " }";
165         }
166         fprintf(output_file_,
167                 "%s{ \"name\": \"%s\""
168                 ", \"cat\": \"%s\""
169                 ", \"ph\": \"%c\""
170                 ", \"ts\": %" PRIu64
171                 ", \"pid\": %d"
172 #if defined(WEBRTC_WIN)
173                 ", \"tid\": %lu"
174 #else
175                 ", \"tid\": %d"
176 #endif  // defined(WEBRTC_WIN)
177                 "%s"
178                 "}\n",
179                 has_logged_event ? "," : " ", e.name, e.category_enabled,
180                 e.phase, e.timestamp, e.pid, e.tid, args_str.c_str());
181         has_logged_event = true;
182       }
183       if (shutting_down)
184         break;
185     }
186     fprintf(output_file_, "]}\n");
187     if (output_file_owned_)
188       fclose(output_file_);
189     output_file_ = nullptr;
190   }
191 
Start(FILE * file,bool owned)192   void Start(FILE* file, bool owned) {
193     RTC_DCHECK(thread_checker_.IsCurrent());
194     RTC_DCHECK(file);
195     RTC_DCHECK(!output_file_);
196     output_file_ = file;
197     output_file_owned_ = owned;
198     {
199       webrtc::MutexLock lock(&mutex_);
200       // Since the atomic fast-path for adding events to the queue can be
201       // bypassed while the logging thread is shutting down there may be some
202       // stale events in the queue, hence the vector needs to be cleared to not
203       // log events from a previous logging session (which may be days old).
204       trace_events_.clear();
205     }
206     // Enable event logging (fast-path). This should be disabled since starting
207     // shouldn't be done twice.
208     RTC_CHECK_EQ(0,
209                  rtc::AtomicOps::CompareAndSwap(&g_event_logging_active, 0, 1));
210 
211     // Finally start, everything should be set up now.
212     logging_thread_.Start();
213     TRACE_EVENT_INSTANT0("webrtc", "EventLogger::Start");
214   }
215 
Stop()216   void Stop() {
217     RTC_DCHECK(thread_checker_.IsCurrent());
218     TRACE_EVENT_INSTANT0("webrtc", "EventLogger::Stop");
219     // 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:
230   struct TraceArg {
231     const char* name;
232     unsigned char type;
233     // Copied from webrtc/rtc_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 
250   struct TraceEvent {
251     const char* name;
252     const unsigned char* category_enabled;
253     char phase;
254     std::vector<TraceArg> args;
255     uint64_t timestamp;
256     int pid;
257     rtc::PlatformThreadId tid;
258   };
259 
TraceArgValueAsString(TraceArg arg)260   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 = snprintf(&output[0], kTraceArgBufferLength, "%llu",
294                                   arg.value.as_uint);
295           break;
296         case TRACE_VALUE_TYPE_INT:
297           print_length = snprintf(&output[0], kTraceArgBufferLength, "%lld",
298                                   arg.value.as_int);
299           break;
300         case TRACE_VALUE_TYPE_DOUBLE:
301           print_length = snprintf(&output[0], kTraceArgBufferLength, "%f",
302                                   arg.value.as_double);
303           break;
304         case TRACE_VALUE_TYPE_POINTER:
305           print_length = snprintf(&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 
320   webrtc::Mutex mutex_;
321   std::vector<TraceEvent> trace_events_ RTC_GUARDED_BY(mutex_);
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 
EventTracingThreadFunc(void * params)329 static void EventTracingThreadFunc(void* params) {
330   static_cast<EventLogger*>(params)->Log();
331 }
332 
333 static EventLogger* volatile g_event_logger = nullptr;
334 static const char* const kDisabledTracePrefix = TRACE_DISABLED_BY_DEFAULT("");
InternalGetCategoryEnabled(const char * name)335 const unsigned char* InternalGetCategoryEnabled(const char* name) {
336   const char* prefix_ptr = &kDisabledTracePrefix[0];
337   const char* name_ptr = name;
338   // Check whether name contains the default-disabled prefix.
339   while (*prefix_ptr == *name_ptr && *prefix_ptr != '\0') {
340     ++prefix_ptr;
341     ++name_ptr;
342   }
343   return reinterpret_cast<const unsigned char*>(*prefix_ptr == '\0' ? ""
344                                                                     : name);
345 }
346 
InternalAddTraceEvent(char phase,const unsigned char * category_enabled,const char * name,unsigned long long id,int num_args,const char ** arg_names,const unsigned char * arg_types,const unsigned long long * arg_values,unsigned char flags)347 void InternalAddTraceEvent(char phase,
348                            const unsigned char* category_enabled,
349                            const char* name,
350                            unsigned long long id,
351                            int num_args,
352                            const char** arg_names,
353                            const unsigned char* arg_types,
354                            const unsigned long long* arg_values,
355                            unsigned char flags) {
356   // Fast path for when event tracing is inactive.
357   if (rtc::AtomicOps::AcquireLoad(&g_event_logging_active) == 0)
358     return;
359 
360   g_event_logger->AddTraceEvent(name, category_enabled, phase, num_args,
361                                 arg_names, arg_types, arg_values,
362                                 rtc::TimeMicros(), 1, rtc::CurrentThreadId());
363 }
364 
365 }  // namespace
366 
SetupInternalTracer()367 void SetupInternalTracer() {
368   RTC_CHECK(rtc::AtomicOps::CompareAndSwapPtr(
369                 &g_event_logger, static_cast<EventLogger*>(nullptr),
370                 new EventLogger()) == nullptr);
371   webrtc::SetupEventTracer(InternalGetCategoryEnabled, InternalAddTraceEvent);
372 }
373 
StartInternalCaptureToFile(FILE * file)374 void StartInternalCaptureToFile(FILE* file) {
375   if (g_event_logger) {
376     g_event_logger->Start(file, false);
377   }
378 }
379 
StartInternalCapture(const char * filename)380 bool StartInternalCapture(const char* filename) {
381   if (!g_event_logger)
382     return false;
383 
384   FILE* file = fopen(filename, "w");
385   if (!file) {
386     RTC_LOG(LS_ERROR) << "Failed to open trace file '" << filename
387                       << "' for writing.";
388     return false;
389   }
390   g_event_logger->Start(file, true);
391   return true;
392 }
393 
StopInternalCapture()394 void StopInternalCapture() {
395   if (g_event_logger) {
396     g_event_logger->Stop();
397   }
398 }
399 
ShutdownInternalTracer()400 void ShutdownInternalTracer() {
401   StopInternalCapture();
402   EventLogger* old_logger = rtc::AtomicOps::AcquireLoadPtr(&g_event_logger);
403   RTC_DCHECK(old_logger);
404   RTC_CHECK(rtc::AtomicOps::CompareAndSwapPtr(
405                 &g_event_logger, old_logger,
406                 static_cast<EventLogger*>(nullptr)) == old_logger);
407   delete old_logger;
408   webrtc::SetupEventTracer(nullptr, nullptr);
409 }
410 
411 }  // namespace tracing
412 }  // namespace rtc
413