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