1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "base/trace_event/trace_event_impl.h"
6 
7 #include <fcntl.h>
8 #include <stddef.h>
9 #include <stdint.h>
10 
11 #include "base/bind.h"
12 #include "base/format_macros.h"
13 #include "base/logging.h"
14 #include "base/posix/eintr_wrapper.h"
15 #include "base/strings/stringprintf.h"
16 #include "base/synchronization/waitable_event.h"
17 #include "base/threading/thread.h"
18 #include "base/trace_event/trace_event.h"
19 
20 namespace base {
21 namespace trace_event {
22 
23 namespace {
24 
25 int g_atrace_fd = -1;
26 const char kATraceMarkerFile[] = "/sys/kernel/debug/tracing/trace_marker";
27 
WriteToATrace(int fd,const char * buffer,size_t size)28 void WriteToATrace(int fd, const char* buffer, size_t size) {
29   size_t total_written = 0;
30   while (total_written < size) {
31     ssize_t written = HANDLE_EINTR(write(
32         fd, buffer + total_written, size - total_written));
33     if (written <= 0)
34       break;
35     total_written += written;
36   }
37   if (total_written < size) {
38     PLOG(WARNING) << "Failed to write buffer '" << std::string(buffer, size)
39                   << "' to " << kATraceMarkerFile;
40   }
41 }
42 
WriteEvent(char phase,const char * category_group,const char * name,unsigned long long id,const TraceArguments & args,unsigned int flags)43 void WriteEvent(char phase,
44                 const char* category_group,
45                 const char* name,
46                 unsigned long long id,
47                 const TraceArguments& args,
48                 unsigned int flags) {
49   std::string out = StringPrintf("%c|%d|%s", phase, getpid(), name);
50   if (flags & TRACE_EVENT_FLAG_HAS_ID)
51     StringAppendF(&out, "-%" PRIx64, static_cast<uint64_t>(id));
52   out += '|';
53 
54   const char* const* arg_names = args.names();
55   for (size_t i = 0; i < args.size() && arg_names[i]; ++i) {
56     if (i)
57       out += ';';
58     out += arg_names[i];
59     out += '=';
60     std::string::size_type value_start = out.length();
61     args.values()[i].AppendAsJSON(args.types()[i], &out);
62 
63     // Remove the quotes which may confuse the atrace script.
64     ReplaceSubstringsAfterOffset(&out, value_start, "\\\"", "'");
65     ReplaceSubstringsAfterOffset(&out, value_start, "\"", "");
66     // Replace chars used for separators with similar chars in the value.
67     std::replace(out.begin() + value_start, out.end(), ';', ',');
68     std::replace(out.begin() + value_start, out.end(), '|', '!');
69   }
70 
71   out += '|';
72   out += category_group;
73   WriteToATrace(g_atrace_fd, out.c_str(), out.size());
74 }
75 
NoOpOutputCallback(WaitableEvent * complete_event,const scoped_refptr<RefCountedString> &,bool has_more_events)76 void NoOpOutputCallback(WaitableEvent* complete_event,
77                         const scoped_refptr<RefCountedString>&,
78                         bool has_more_events) {
79   if (!has_more_events)
80     complete_event->Signal();
81 }
82 
EndChromeTracing(TraceLog * trace_log,WaitableEvent * complete_event)83 void EndChromeTracing(TraceLog* trace_log,
84                       WaitableEvent* complete_event) {
85   trace_log->SetDisabled();
86   // Delete the buffered trace events as they have been sent to atrace.
87   trace_log->Flush(BindRepeating(&NoOpOutputCallback, complete_event));
88 }
89 
90 }  // namespace
91 
92 // These functions support Android systrace.py when 'webview' category is
93 // traced. With the new adb_profile_chrome, we may have two phases:
94 // - before WebView is ready for combined tracing, we can use adb_profile_chrome
95 //   to trace android categories other than 'webview' and chromium categories.
96 //   In this way we can avoid the conflict between StartATrace/StopATrace and
97 //   the intents.
98 // - TODO(wangxianzhu): after WebView is ready for combined tracing, remove
99 //   StartATrace, StopATrace and SendToATrace, and perhaps send Java traces
100 //   directly to atrace in trace_event_binding.cc.
101 
StartATrace()102 void TraceLog::StartATrace() {
103   if (g_atrace_fd != -1)
104     return;
105 
106   g_atrace_fd = HANDLE_EINTR(open(kATraceMarkerFile, O_WRONLY));
107   if (g_atrace_fd == -1) {
108     PLOG(WARNING) << "Couldn't open " << kATraceMarkerFile;
109     return;
110   }
111   TraceConfig trace_config;
112   trace_config.SetTraceRecordMode(RECORD_CONTINUOUSLY);
113   SetEnabled(trace_config, TraceLog::RECORDING_MODE);
114 }
115 
StopATrace()116 void TraceLog::StopATrace() {
117   if (g_atrace_fd == -1)
118     return;
119 
120   close(g_atrace_fd);
121   g_atrace_fd = -1;
122 
123   // TraceLog::Flush() requires the current thread to have a message loop, but
124   // this thread called from Java may not have one, so flush in another thread.
125   Thread end_chrome_tracing_thread("end_chrome_tracing");
126   WaitableEvent complete_event(WaitableEvent::ResetPolicy::AUTOMATIC,
127                                WaitableEvent::InitialState::NOT_SIGNALED);
128   end_chrome_tracing_thread.Start();
129   end_chrome_tracing_thread.task_runner()->PostTask(
130       FROM_HERE, base::BindOnce(&EndChromeTracing, Unretained(this),
131                                 Unretained(&complete_event)));
132   complete_event.Wait();
133 }
134 
SendToATrace()135 void TraceEvent::SendToATrace() {
136   if (g_atrace_fd == -1)
137     return;
138 
139   const char* category_group =
140       TraceLog::GetCategoryGroupName(category_group_enabled_);
141 
142   switch (phase_) {
143     case TRACE_EVENT_PHASE_BEGIN:
144       WriteEvent('B', category_group, name_, id_, args_, flags_);
145       break;
146 
147     case TRACE_EVENT_PHASE_COMPLETE:
148       WriteEvent(duration_.ToInternalValue() == -1 ? 'B' : 'E', category_group,
149                  name_, id_, args_, flags_);
150       break;
151 
152     case TRACE_EVENT_PHASE_END:
153       // Though a single 'E' is enough, here append pid, name and
154       // category_group etc. So that unpaired events can be found easily.
155       WriteEvent('E', category_group, name_, id_, args_, flags_);
156       break;
157 
158     case TRACE_EVENT_PHASE_INSTANT:
159       // Simulate an instance event with a pair of begin/end events.
160       WriteEvent('B', category_group, name_, id_, args_, flags_);
161       WriteToATrace(g_atrace_fd, "E", 1);
162       break;
163 
164     case TRACE_EVENT_PHASE_COUNTER:
165       for (size_t i = 0; i < arg_size() && arg_name(i); ++i) {
166         DCHECK(arg_type(i) == TRACE_VALUE_TYPE_INT);
167         std::string out =
168             base::StringPrintf("C|%d|%s-%s", getpid(), name_, arg_name(i));
169         if (flags_ & TRACE_EVENT_FLAG_HAS_ID)
170           StringAppendF(&out, "-%" PRIx64, static_cast<uint64_t>(id_));
171         StringAppendF(&out, "|%d|%s", static_cast<int>(arg_value(i).as_int),
172                       category_group);
173         WriteToATrace(g_atrace_fd, out.c_str(), out.size());
174       }
175       break;
176 
177     default:
178       // Do nothing.
179       break;
180   }
181 }
182 
AddClockSyncMetadataEvent()183 void TraceLog::AddClockSyncMetadataEvent() {
184   int atrace_fd = HANDLE_EINTR(open(kATraceMarkerFile, O_WRONLY | O_APPEND));
185   if (atrace_fd == -1) {
186     PLOG(WARNING) << "Couldn't open " << kATraceMarkerFile;
187     return;
188   }
189 
190   // Android's kernel trace system has a trace_marker feature: this is a file on
191   // debugfs that takes the written data and pushes it onto the trace
192   // buffer. So, to establish clock sync, we write our monotonic clock into that
193   // trace buffer.
194   double now_in_seconds = (TRACE_TIME_TICKS_NOW() - TimeTicks()).InSecondsF();
195   std::string marker = StringPrintf(
196       "trace_event_clock_sync: parent_ts=%f\n", now_in_seconds);
197   WriteToATrace(atrace_fd, marker.c_str(), marker.size());
198   close(atrace_fd);
199 }
200 
201 }  // namespace trace_event
202 }  // namespace base
203