• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2018 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "tools/trace_to_text/trace_to_systrace.h"
18 
19 #include <stdio.h>
20 
21 #include <algorithm>
22 #include <cinttypes>
23 #include <functional>
24 #include <map>
25 #include <memory>
26 #include <utility>
27 
28 #include "perfetto/base/build_config.h"
29 #include "perfetto/base/logging.h"
30 #include "perfetto/ext/base/string_writer.h"
31 #include "perfetto/ext/base/utils.h"
32 #include "perfetto/trace_processor/trace_processor.h"
33 #include "tools/trace_to_text/utils.h"
34 
35 #define FILTER_RAW_EVENTS \
36   " where not (name like \"chrome_event.%\" or name like \"track_event.%\")"
37 
38 namespace perfetto {
39 namespace trace_to_text {
40 
41 namespace {
42 
43 const char kProcessDumpHeader[] =
44     "\"androidProcessDump\": "
45     "\"PROCESS DUMP\\nUSER           PID  PPID     VSZ    RSS WCHAN  "
46     "PC S NAME                        COMM                       \\n";
47 
48 const char kThreadHeader[] = "USER           PID   TID CMD \\n";
49 
50 const char kProcessDumpFooter[] = "\"";
51 
52 const char kSystemTraceEvents[] = "  \"systemTraceEvents\": \"";
53 
54 const char kFtraceHeader[] =
55     "# tracer: nop\n"
56     "#\n"
57     "# entries-in-buffer/entries-written: 30624/30624   #P:4\n"
58     "#\n"
59     "#                                      _-----=> irqs-off\n"
60     "#                                     / _----=> need-resched\n"
61     "#                                    | / _---=> hardirq/softirq\n"
62     "#                                    || / _--=> preempt-depth\n"
63     "#                                    ||| /     delay\n"
64     "#           TASK-PID    TGID   CPU#  ||||    TIMESTAMP  FUNCTION\n"
65     "#              | |        |      |   ||||       |         |\n";
66 
67 const char kFtraceJsonHeader[] =
68     "# tracer: nop\\n"
69     "#\\n"
70     "# entries-in-buffer/entries-written: 30624/30624   #P:4\\n"
71     "#\\n"
72     "#                                      _-----=> irqs-off\\n"
73     "#                                     / _----=> need-resched\\n"
74     "#                                    | / _---=> hardirq/softirq\\n"
75     "#                                    || / _--=> preempt-depth\\n"
76     "#                                    ||| /     delay\\n"
77     "#           TASK-PID    TGID   CPU#  ||||    TIMESTAMP  FUNCTION\\n"
78     "#              | |        |      |   ||||       |         |\\n";
79 
80 // The legacy trace viewer requires a clock sync marker to tie ftrace and
81 // userspace clocks together. Trace processor already aligned these clocks, so
82 // we just emit a clock sync for an equality mapping.
83 const char kSystemTraceEventsFooter[] =
84     "\\n<...>-12345 (-----) [000] ...1 0.000000: tracing_mark_write: "
85     "trace_event_clock_sync: parent_ts=0\\n\"";
86 
FormatProcess(uint32_t pid,uint32_t ppid,const base::StringView & name,base::StringWriter * writer)87 inline void FormatProcess(uint32_t pid,
88                           uint32_t ppid,
89                           const base::StringView& name,
90                           base::StringWriter* writer) {
91   writer->AppendLiteral("root             ");
92   writer->AppendInt(pid);
93   writer->AppendLiteral("     ");
94   writer->AppendInt(ppid);
95   writer->AppendLiteral("   00000   000 null 0000000000 S ");
96   writer->AppendString(name);
97   writer->AppendLiteral("         null");
98 }
99 
FormatThread(uint32_t tid,uint32_t tgid,const base::StringView & name,base::StringWriter * writer)100 inline void FormatThread(uint32_t tid,
101                          uint32_t tgid,
102                          const base::StringView& name,
103                          base::StringWriter* writer) {
104   writer->AppendLiteral("root         ");
105   writer->AppendInt(tgid);
106   writer->AppendChar(' ');
107   writer->AppendInt(tid);
108   writer->AppendChar(' ');
109   if (name.empty()) {
110     writer->AppendLiteral("<...>");
111   } else {
112     writer->AppendString(name);
113   }
114 }
115 
116 class QueryWriter {
117  public:
QueryWriter(trace_processor::TraceProcessor * tp,TraceWriter * trace_writer)118   QueryWriter(trace_processor::TraceProcessor* tp, TraceWriter* trace_writer)
119       : tp_(tp),
120         buffer_(base::PagedMemory::Allocate(kBufferSize)),
121         global_writer_(static_cast<char*>(buffer_.Get()), kBufferSize),
122         trace_writer_(trace_writer) {}
123 
124   template <typename Callback>
RunQuery(const std::string & sql,Callback callback)125   bool RunQuery(const std::string& sql, Callback callback) {
126     char buffer[2048];
127     auto iterator = tp_->ExecuteQuery(sql);
128     for (uint32_t rows = 0; iterator.Next(); rows++) {
129       base::StringWriter line_writer(buffer, base::ArraySize(buffer));
130       callback(&iterator, &line_writer);
131 
132       if (global_writer_.pos() + line_writer.pos() >= global_writer_.size()) {
133         fprintf(stderr, "Writing row %" PRIu32 "%c", rows, kProgressChar);
134         auto str = global_writer_.GetStringView();
135         trace_writer_->Write(str.data(), str.size());
136         global_writer_.reset();
137       }
138       global_writer_.AppendStringView(line_writer.GetStringView());
139     }
140 
141     // Check if we have an error in the iterator and print if so.
142     auto status = iterator.Status();
143     if (!status.ok()) {
144       PERFETTO_ELOG("Error while writing systrace %s", status.c_message());
145       return false;
146     }
147 
148     // Flush any dangling pieces in the global writer.
149     auto str = global_writer_.GetStringView();
150     trace_writer_->Write(str.data(), str.size());
151     global_writer_.reset();
152     return true;
153   }
154 
155  private:
156   static constexpr uint32_t kBufferSize = 1024u * 1024u * 16u;
157 
158   trace_processor::TraceProcessor* tp_ = nullptr;
159   base::PagedMemory buffer_;
160   base::StringWriter global_writer_;
161   TraceWriter* trace_writer_;
162 };
163 
ExtractRawEvents(TraceWriter * trace_writer,QueryWriter & q_writer,bool wrapped_in_json,Keep truncate_keep)164 int ExtractRawEvents(TraceWriter* trace_writer,
165                      QueryWriter& q_writer,
166                      bool wrapped_in_json,
167                      Keep truncate_keep) {
168   using trace_processor::Iterator;
169 
170   static const char kRawEventsCountSql[] =
171       "select count(1) from raw" FILTER_RAW_EVENTS;
172   uint32_t raw_events = 0;
173   auto e_callback = [&raw_events](Iterator* it, base::StringWriter*) {
174     raw_events = static_cast<uint32_t>(it->Get(0).long_value);
175   };
176   if (!q_writer.RunQuery(kRawEventsCountSql, e_callback))
177     return 1;
178 
179   if (raw_events == 0) {
180     if (!wrapped_in_json) {
181       // Write out the normal header even if we won't actually have
182       // any events under it.
183       trace_writer->Write(kFtraceHeader);
184     }
185     return 0;
186   }
187 
188   fprintf(stderr, "Converting ftrace events%c", kProgressChar);
189   fflush(stderr);
190 
191   auto raw_callback = [wrapped_in_json](Iterator* it,
192                                         base::StringWriter* writer) {
193     const char* line = it->Get(0 /* col */).string_value;
194     if (wrapped_in_json) {
195       for (uint32_t i = 0; line[i] != '\0'; i++) {
196         char c = line[i];
197         switch (c) {
198           case '\n':
199             writer->AppendLiteral("\\n");
200             break;
201           case '\f':
202             writer->AppendLiteral("\\f");
203             break;
204           case '\b':
205             writer->AppendLiteral("\\b");
206             break;
207           case '\r':
208             writer->AppendLiteral("\\r");
209             break;
210           case '\t':
211             writer->AppendLiteral("\\t");
212             break;
213           case '\\':
214             writer->AppendLiteral("\\\\");
215             break;
216           case '"':
217             writer->AppendLiteral("\\\"");
218             break;
219           default:
220             writer->AppendChar(c);
221             break;
222         }
223       }
224       writer->AppendChar('\\');
225       writer->AppendChar('n');
226     } else {
227       writer->AppendString(line);
228       writer->AppendChar('\n');
229     }
230   };
231 
232   // An estimate of 130b per ftrace event, allowing some space for the processes
233   // and threads.
234   const uint32_t max_ftrace_events = (140 * 1024 * 1024) / 130;
235 
236   static const char kRawEventsQuery[] =
237       "select to_ftrace(id) from raw" FILTER_RAW_EVENTS;
238 
239   // 1. Write the appropriate header for the file type.
240   if (wrapped_in_json) {
241     trace_writer->Write(",\n");
242     trace_writer->Write(kSystemTraceEvents);
243     trace_writer->Write(kFtraceJsonHeader);
244   } else {
245     trace_writer->Write(kFtraceHeader);
246   }
247 
248   // 2. Write the actual events.
249   if (truncate_keep == Keep::kEnd && raw_events > max_ftrace_events) {
250     char end_truncate[150];
251     sprintf(end_truncate, "%s limit %d offset %d", kRawEventsQuery,
252             max_ftrace_events, raw_events - max_ftrace_events);
253     if (!q_writer.RunQuery(end_truncate, raw_callback))
254       return 1;
255   } else if (truncate_keep == Keep::kStart) {
256     char start_truncate[150];
257     sprintf(start_truncate, "%s limit %d", kRawEventsQuery, max_ftrace_events);
258     if (!q_writer.RunQuery(start_truncate, raw_callback))
259       return 1;
260   } else {
261     if (!q_writer.RunQuery(kRawEventsQuery, raw_callback))
262       return 1;
263   }
264 
265   // 3. Write the footer for JSON.
266   if (wrapped_in_json)
267     trace_writer->Write(kSystemTraceEventsFooter);
268 
269   return 0;
270 }
271 
272 }  // namespace
273 
TraceToSystrace(std::istream * input,std::ostream * output,bool ctrace,Keep truncate_keep,bool full_sort)274 int TraceToSystrace(std::istream* input,
275                     std::ostream* output,
276                     bool ctrace,
277                     Keep truncate_keep,
278                     bool full_sort) {
279   std::unique_ptr<TraceWriter> trace_writer(
280       ctrace ? new DeflateTraceWriter(output) : new TraceWriter(output));
281 
282   trace_processor::Config config;
283   config.sorting_mode = full_sort
284                             ? trace_processor::SortingMode::kForceFullSort
285                             : trace_processor::SortingMode::kDefaultHeuristics;
286   std::unique_ptr<trace_processor::TraceProcessor> tp =
287       trace_processor::TraceProcessor::CreateInstance(config);
288 
289   if (!ReadTrace(tp.get(), input))
290     return 1;
291   tp->NotifyEndOfFile();
292 
293   if (ctrace)
294     *output << "TRACE:\n";
295 
296   return ExtractSystrace(tp.get(), trace_writer.get(),
297                          /*wrapped_in_json=*/false, truncate_keep);
298 }
299 
ExtractSystrace(trace_processor::TraceProcessor * tp,TraceWriter * trace_writer,bool wrapped_in_json,Keep truncate_keep)300 int ExtractSystrace(trace_processor::TraceProcessor* tp,
301                     TraceWriter* trace_writer,
302                     bool wrapped_in_json,
303                     Keep truncate_keep) {
304   using trace_processor::Iterator;
305 
306   QueryWriter q_writer(tp, trace_writer);
307   if (wrapped_in_json) {
308     trace_writer->Write(kProcessDumpHeader);
309 
310     // Write out all the processes in the trace.
311     // TODO(lalitm): change this query to actually use ppid when it is exposed
312     // by the process table.
313     static const char kPSql[] = "select pid, 0 as ppid, name from process";
314     auto p_callback = [](Iterator* it, base::StringWriter* writer) {
315       uint32_t pid = static_cast<uint32_t>(it->Get(0 /* col */).long_value);
316       uint32_t ppid = static_cast<uint32_t>(it->Get(1 /* col */).long_value);
317       const auto& name_col = it->Get(2 /* col */);
318       auto name_view = name_col.type == trace_processor::SqlValue::kString
319                            ? base::StringView(name_col.string_value)
320                            : base::StringView();
321       FormatProcess(pid, ppid, name_view, writer);
322     };
323     if (!q_writer.RunQuery(kPSql, p_callback))
324       return 1;
325 
326     trace_writer->Write(kThreadHeader);
327 
328     // Write out all the threads in the trace.
329     static const char kTSql[] =
330         "select tid, COALESCE(upid, 0), thread.name "
331         "from thread left join process using (upid)";
332     auto t_callback = [](Iterator* it, base::StringWriter* writer) {
333       uint32_t tid = static_cast<uint32_t>(it->Get(0 /* col */).long_value);
334       uint32_t tgid = static_cast<uint32_t>(it->Get(1 /* col */).long_value);
335       const auto& name_col = it->Get(2 /* col */);
336       auto name_view = name_col.type == trace_processor::SqlValue::kString
337                            ? base::StringView(name_col.string_value)
338                            : base::StringView();
339       FormatThread(tid, tgid, name_view, writer);
340     };
341     if (!q_writer.RunQuery(kTSql, t_callback))
342       return 1;
343 
344     trace_writer->Write(kProcessDumpFooter);
345   }
346   return ExtractRawEvents(trace_writer, q_writer, wrapped_in_json,
347                           truncate_keep);
348 }
349 
350 }  // namespace trace_to_text
351 }  // namespace perfetto
352