You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

412 lines
14 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  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. #include <inttypes.h>
  12. #include <stdint.h>
  13. #include <stdio.h>
  14. #include <string.h>
  15. #include <string>
  16. #include <vector>
  17. #include "rtc_base/atomic_ops.h"
  18. #include "rtc_base/checks.h"
  19. #include "rtc_base/critical_section.h"
  20. #include "rtc_base/event.h"
  21. #include "rtc_base/logging.h"
  22. #include "rtc_base/platform_thread.h"
  23. #include "rtc_base/platform_thread_types.h"
  24. #include "rtc_base/thread_annotations.h"
  25. #include "rtc_base/thread_checker.h"
  26. #include "rtc_base/time_utils.h"
  27. #include "rtc_base/trace_event.h"
  28. // This is a guesstimate that should be enough in most cases.
  29. static const size_t kEventLoggerArgsStrBufferInitialSize = 256;
  30. static const size_t kTraceArgBufferLength = 32;
  31. namespace webrtc {
  32. namespace {
  33. GetCategoryEnabledPtr g_get_category_enabled_ptr = nullptr;
  34. AddTraceEventPtr g_add_trace_event_ptr = nullptr;
  35. } // namespace
  36. void SetupEventTracer(GetCategoryEnabledPtr get_category_enabled_ptr,
  37. AddTraceEventPtr add_trace_event_ptr) {
  38. g_get_category_enabled_ptr = get_category_enabled_ptr;
  39. g_add_trace_event_ptr = add_trace_event_ptr;
  40. }
  41. const unsigned char* EventTracer::GetCategoryEnabled(const char* name) {
  42. if (g_get_category_enabled_ptr)
  43. return g_get_category_enabled_ptr(name);
  44. // A string with null terminator means category is disabled.
  45. return reinterpret_cast<const unsigned char*>("\0");
  46. }
  47. // Arguments to this function (phase, etc.) are as defined in
  48. // webrtc/rtc_base/trace_event.h.
  49. void EventTracer::AddTraceEvent(char phase,
  50. const unsigned char* category_enabled,
  51. const char* name,
  52. unsigned long long id,
  53. int num_args,
  54. const char** arg_names,
  55. const unsigned char* arg_types,
  56. const unsigned long long* arg_values,
  57. unsigned char flags) {
  58. if (g_add_trace_event_ptr) {
  59. g_add_trace_event_ptr(phase, category_enabled, name, id, num_args,
  60. arg_names, arg_types, arg_values, flags);
  61. }
  62. }
  63. } // namespace webrtc
  64. namespace rtc {
  65. namespace tracing {
  66. namespace {
  67. static void EventTracingThreadFunc(void* params);
  68. // Atomic-int fast path for avoiding logging when disabled.
  69. static volatile int g_event_logging_active = 0;
  70. // TODO(pbos): Log metadata for all threads, etc.
  71. class EventLogger final {
  72. public:
  73. EventLogger()
  74. : logging_thread_(EventTracingThreadFunc,
  75. this,
  76. "EventTracingThread",
  77. kLowPriority) {}
  78. ~EventLogger() { RTC_DCHECK(thread_checker_.IsCurrent()); }
  79. void AddTraceEvent(const char* name,
  80. const unsigned char* category_enabled,
  81. char phase,
  82. int num_args,
  83. const char** arg_names,
  84. const unsigned char* arg_types,
  85. const unsigned long long* arg_values,
  86. uint64_t timestamp,
  87. int pid,
  88. rtc::PlatformThreadId thread_id) {
  89. std::vector<TraceArg> args(num_args);
  90. for (int i = 0; i < num_args; ++i) {
  91. TraceArg& arg = args[i];
  92. arg.name = arg_names[i];
  93. arg.type = arg_types[i];
  94. arg.value.as_uint = arg_values[i];
  95. // Value is a pointer to a temporary string, so we have to make a copy.
  96. if (arg.type == TRACE_VALUE_TYPE_COPY_STRING) {
  97. // Space for the string and for the terminating null character.
  98. size_t str_length = strlen(arg.value.as_string) + 1;
  99. char* str_copy = new char[str_length];
  100. memcpy(str_copy, arg.value.as_string, str_length);
  101. arg.value.as_string = str_copy;
  102. }
  103. }
  104. rtc::CritScope lock(&crit_);
  105. trace_events_.push_back(
  106. {name, category_enabled, phase, args, timestamp, 1, thread_id});
  107. }
  108. // The TraceEvent format is documented here:
  109. // https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/preview
  110. void Log() {
  111. RTC_DCHECK(output_file_);
  112. static const int kLoggingIntervalMs = 100;
  113. fprintf(output_file_, "{ \"traceEvents\": [\n");
  114. bool has_logged_event = false;
  115. while (true) {
  116. bool shutting_down = shutdown_event_.Wait(kLoggingIntervalMs);
  117. std::vector<TraceEvent> events;
  118. {
  119. rtc::CritScope lock(&crit_);
  120. trace_events_.swap(events);
  121. }
  122. std::string args_str;
  123. args_str.reserve(kEventLoggerArgsStrBufferInitialSize);
  124. for (TraceEvent& e : events) {
  125. args_str.clear();
  126. if (!e.args.empty()) {
  127. args_str += ", \"args\": {";
  128. bool is_first_argument = true;
  129. for (TraceArg& arg : e.args) {
  130. if (!is_first_argument)
  131. args_str += ",";
  132. is_first_argument = false;
  133. args_str += " \"";
  134. args_str += arg.name;
  135. args_str += "\": ";
  136. args_str += TraceArgValueAsString(arg);
  137. // Delete our copy of the string.
  138. if (arg.type == TRACE_VALUE_TYPE_COPY_STRING) {
  139. delete[] arg.value.as_string;
  140. arg.value.as_string = nullptr;
  141. }
  142. }
  143. args_str += " }";
  144. }
  145. fprintf(output_file_,
  146. "%s{ \"name\": \"%s\""
  147. ", \"cat\": \"%s\""
  148. ", \"ph\": \"%c\""
  149. ", \"ts\": %" PRIu64
  150. ", \"pid\": %d"
  151. #if defined(WEBRTC_WIN)
  152. ", \"tid\": %lu"
  153. #else
  154. ", \"tid\": %d"
  155. #endif // defined(WEBRTC_WIN)
  156. "%s"
  157. "}\n",
  158. has_logged_event ? "," : " ", e.name, e.category_enabled,
  159. e.phase, e.timestamp, e.pid, e.tid, args_str.c_str());
  160. has_logged_event = true;
  161. }
  162. if (shutting_down)
  163. break;
  164. }
  165. fprintf(output_file_, "]}\n");
  166. if (output_file_owned_)
  167. fclose(output_file_);
  168. output_file_ = nullptr;
  169. }
  170. void Start(FILE* file, bool owned) {
  171. RTC_DCHECK(thread_checker_.IsCurrent());
  172. RTC_DCHECK(file);
  173. RTC_DCHECK(!output_file_);
  174. output_file_ = file;
  175. output_file_owned_ = owned;
  176. {
  177. rtc::CritScope lock(&crit_);
  178. // Since the atomic fast-path for adding events to the queue can be
  179. // bypassed while the logging thread is shutting down there may be some
  180. // stale events in the queue, hence the vector needs to be cleared to not
  181. // log events from a previous logging session (which may be days old).
  182. trace_events_.clear();
  183. }
  184. // Enable event logging (fast-path). This should be disabled since starting
  185. // shouldn't be done twice.
  186. RTC_CHECK_EQ(0,
  187. rtc::AtomicOps::CompareAndSwap(&g_event_logging_active, 0, 1));
  188. // Finally start, everything should be set up now.
  189. logging_thread_.Start();
  190. TRACE_EVENT_INSTANT0("webrtc", "EventLogger::Start");
  191. }
  192. void Stop() {
  193. RTC_DCHECK(thread_checker_.IsCurrent());
  194. TRACE_EVENT_INSTANT0("webrtc", "EventLogger::Stop");
  195. // Try to stop. Abort if we're not currently logging.
  196. if (rtc::AtomicOps::CompareAndSwap(&g_event_logging_active, 1, 0) == 0)
  197. return;
  198. // Wake up logging thread to finish writing.
  199. shutdown_event_.Set();
  200. // Join the logging thread.
  201. logging_thread_.Stop();
  202. }
  203. private:
  204. struct TraceArg {
  205. const char* name;
  206. unsigned char type;
  207. // Copied from webrtc/rtc_base/trace_event.h TraceValueUnion.
  208. union TraceArgValue {
  209. bool as_bool;
  210. unsigned long long as_uint;
  211. long long as_int;
  212. double as_double;
  213. const void* as_pointer;
  214. const char* as_string;
  215. } value;
  216. // Assert that the size of the union is equal to the size of the as_uint
  217. // field since we are assigning to arbitrary types using it.
  218. static_assert(sizeof(TraceArgValue) == sizeof(unsigned long long),
  219. "Size of TraceArg value union is not equal to the size of "
  220. "the uint field of that union.");
  221. };
  222. struct TraceEvent {
  223. const char* name;
  224. const unsigned char* category_enabled;
  225. char phase;
  226. std::vector<TraceArg> args;
  227. uint64_t timestamp;
  228. int pid;
  229. rtc::PlatformThreadId tid;
  230. };
  231. static std::string TraceArgValueAsString(TraceArg arg) {
  232. std::string output;
  233. if (arg.type == TRACE_VALUE_TYPE_STRING ||
  234. arg.type == TRACE_VALUE_TYPE_COPY_STRING) {
  235. // Space for every character to be an espaced character + two for
  236. // quatation marks.
  237. output.reserve(strlen(arg.value.as_string) * 2 + 2);
  238. output += '\"';
  239. const char* c = arg.value.as_string;
  240. do {
  241. if (*c == '"' || *c == '\\') {
  242. output += '\\';
  243. output += *c;
  244. } else {
  245. output += *c;
  246. }
  247. } while (*++c);
  248. output += '\"';
  249. } else {
  250. output.resize(kTraceArgBufferLength);
  251. size_t print_length = 0;
  252. switch (arg.type) {
  253. case TRACE_VALUE_TYPE_BOOL:
  254. if (arg.value.as_bool) {
  255. strcpy(&output[0], "true");
  256. print_length = 4;
  257. } else {
  258. strcpy(&output[0], "false");
  259. print_length = 5;
  260. }
  261. break;
  262. case TRACE_VALUE_TYPE_UINT:
  263. print_length = snprintf(&output[0], kTraceArgBufferLength, "%llu",
  264. arg.value.as_uint);
  265. break;
  266. case TRACE_VALUE_TYPE_INT:
  267. print_length = snprintf(&output[0], kTraceArgBufferLength, "%lld",
  268. arg.value.as_int);
  269. break;
  270. case TRACE_VALUE_TYPE_DOUBLE:
  271. print_length = snprintf(&output[0], kTraceArgBufferLength, "%f",
  272. arg.value.as_double);
  273. break;
  274. case TRACE_VALUE_TYPE_POINTER:
  275. print_length = snprintf(&output[0], kTraceArgBufferLength, "\"%p\"",
  276. arg.value.as_pointer);
  277. break;
  278. }
  279. size_t output_length = print_length < kTraceArgBufferLength
  280. ? print_length
  281. : kTraceArgBufferLength - 1;
  282. // This will hopefully be very close to nop. On most implementations, it
  283. // just writes null byte and sets the length field of the string.
  284. output.resize(output_length);
  285. }
  286. return output;
  287. }
  288. rtc::CriticalSection crit_;
  289. std::vector<TraceEvent> trace_events_ RTC_GUARDED_BY(crit_);
  290. rtc::PlatformThread logging_thread_;
  291. rtc::Event shutdown_event_;
  292. rtc::ThreadChecker thread_checker_;
  293. FILE* output_file_ = nullptr;
  294. bool output_file_owned_ = false;
  295. };
  296. static void EventTracingThreadFunc(void* params) {
  297. static_cast<EventLogger*>(params)->Log();
  298. }
  299. static EventLogger* volatile g_event_logger = nullptr;
  300. static const char* const kDisabledTracePrefix = TRACE_DISABLED_BY_DEFAULT("");
  301. const unsigned char* InternalGetCategoryEnabled(const char* name) {
  302. const char* prefix_ptr = &kDisabledTracePrefix[0];
  303. const char* name_ptr = name;
  304. // Check whether name contains the default-disabled prefix.
  305. while (*prefix_ptr == *name_ptr && *prefix_ptr != '\0') {
  306. ++prefix_ptr;
  307. ++name_ptr;
  308. }
  309. return reinterpret_cast<const unsigned char*>(*prefix_ptr == '\0' ? ""
  310. : name);
  311. }
  312. void InternalAddTraceEvent(char phase,
  313. const unsigned char* category_enabled,
  314. const char* name,
  315. unsigned long long id,
  316. int num_args,
  317. const char** arg_names,
  318. const unsigned char* arg_types,
  319. const unsigned long long* arg_values,
  320. unsigned char flags) {
  321. // Fast path for when event tracing is inactive.
  322. if (rtc::AtomicOps::AcquireLoad(&g_event_logging_active) == 0)
  323. return;
  324. g_event_logger->AddTraceEvent(name, category_enabled, phase, num_args,
  325. arg_names, arg_types, arg_values,
  326. rtc::TimeMicros(), 1, rtc::CurrentThreadId());
  327. }
  328. } // namespace
  329. void SetupInternalTracer() {
  330. RTC_CHECK(rtc::AtomicOps::CompareAndSwapPtr(
  331. &g_event_logger, static_cast<EventLogger*>(nullptr),
  332. new EventLogger()) == nullptr);
  333. webrtc::SetupEventTracer(InternalGetCategoryEnabled, InternalAddTraceEvent);
  334. }
  335. void StartInternalCaptureToFile(FILE* file) {
  336. if (g_event_logger) {
  337. g_event_logger->Start(file, false);
  338. }
  339. }
  340. bool StartInternalCapture(const char* filename) {
  341. if (!g_event_logger)
  342. return false;
  343. FILE* file = fopen(filename, "w");
  344. if (!file) {
  345. RTC_LOG(LS_ERROR) << "Failed to open trace file '" << filename
  346. << "' for writing.";
  347. return false;
  348. }
  349. g_event_logger->Start(file, true);
  350. return true;
  351. }
  352. void StopInternalCapture() {
  353. if (g_event_logger) {
  354. g_event_logger->Stop();
  355. }
  356. }
  357. void ShutdownInternalTracer() {
  358. StopInternalCapture();
  359. EventLogger* old_logger = rtc::AtomicOps::AcquireLoadPtr(&g_event_logger);
  360. RTC_DCHECK(old_logger);
  361. RTC_CHECK(rtc::AtomicOps::CompareAndSwapPtr(
  362. &g_event_logger, old_logger,
  363. static_cast<EventLogger*>(nullptr)) == old_logger);
  364. delete old_logger;
  365. webrtc::SetupEventTracer(nullptr, nullptr);
  366. }
  367. } // namespace tracing
  368. } // namespace rtc