• 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/trace_event/trace_event_impl.h"
6 
7 #include <stddef.h>
8 
9 #include "base/format_macros.h"
10 #include "base/json/string_escape.h"
11 #include "base/memory/ptr_util.h"
12 #include "base/process/process_handle.h"
13 #include "base/stl_util.h"
14 #include "base/strings/string_number_conversions.h"
15 #include "base/strings/string_util.h"
16 #include "base/strings/stringprintf.h"
17 #include "base/strings/utf_string_conversions.h"
18 #include "base/trace_event/trace_event.h"
19 #include "base/trace_event/trace_event_argument.h"
20 #include "base/trace_event/trace_log.h"
21 
22 namespace base {
23 namespace trace_event {
24 
25 namespace {
26 
GetAllocLength(const char * str)27 size_t GetAllocLength(const char* str) { return str ? strlen(str) + 1 : 0; }
28 
29 // Copies |*member| into |*buffer|, sets |*member| to point to this new
30 // location, and then advances |*buffer| by the amount written.
CopyTraceEventParameter(char ** buffer,const char ** member,const char * end)31 void CopyTraceEventParameter(char** buffer,
32                              const char** member,
33                              const char* end) {
34   if (*member) {
35     size_t written = strlcpy(*buffer, *member, end - *buffer) + 1;
36     DCHECK_LE(static_cast<int>(written), end - *buffer);
37     *member = *buffer;
38     *buffer += written;
39   }
40 }
41 
42 }  // namespace
43 
TraceEvent()44 TraceEvent::TraceEvent()
45     : duration_(TimeDelta::FromInternalValue(-1)),
46       scope_(trace_event_internal::kGlobalScope),
47       id_(0u),
48       category_group_enabled_(nullptr),
49       name_(nullptr),
50       thread_id_(0),
51       flags_(0),
52       phase_(TRACE_EVENT_PHASE_BEGIN) {
53   for (int i = 0; i < kTraceMaxNumArgs; ++i)
54     arg_names_[i] = nullptr;
55   memset(arg_values_, 0, sizeof(arg_values_));
56 }
57 
58 TraceEvent::~TraceEvent() = default;
59 
MoveFrom(std::unique_ptr<TraceEvent> other)60 void TraceEvent::MoveFrom(std::unique_ptr<TraceEvent> other) {
61   timestamp_ = other->timestamp_;
62   thread_timestamp_ = other->thread_timestamp_;
63   duration_ = other->duration_;
64   scope_ = other->scope_;
65   id_ = other->id_;
66   category_group_enabled_ = other->category_group_enabled_;
67   name_ = other->name_;
68   if (other->flags_ & TRACE_EVENT_FLAG_HAS_PROCESS_ID)
69     process_id_ = other->process_id_;
70   else
71     thread_id_ = other->thread_id_;
72   phase_ = other->phase_;
73   flags_ = other->flags_;
74   parameter_copy_storage_ = std::move(other->parameter_copy_storage_);
75 
76   for (int i = 0; i < kTraceMaxNumArgs; ++i) {
77     arg_names_[i] = other->arg_names_[i];
78     arg_types_[i] = other->arg_types_[i];
79     arg_values_[i] = other->arg_values_[i];
80     convertable_values_[i] = std::move(other->convertable_values_[i]);
81   }
82 }
83 
Initialize(int thread_id,TimeTicks timestamp,ThreadTicks thread_timestamp,char phase,const unsigned char * category_group_enabled,const char * name,const char * scope,unsigned long long id,unsigned long long bind_id,int num_args,const char * const * arg_names,const unsigned char * arg_types,const unsigned long long * arg_values,std::unique_ptr<ConvertableToTraceFormat> * convertable_values,unsigned int flags)84 void TraceEvent::Initialize(
85     int thread_id,
86     TimeTicks timestamp,
87     ThreadTicks thread_timestamp,
88     char phase,
89     const unsigned char* category_group_enabled,
90     const char* name,
91     const char* scope,
92     unsigned long long id,
93     unsigned long long bind_id,
94     int num_args,
95     const char* const* arg_names,
96     const unsigned char* arg_types,
97     const unsigned long long* arg_values,
98     std::unique_ptr<ConvertableToTraceFormat>* convertable_values,
99     unsigned int flags) {
100   timestamp_ = timestamp;
101   thread_timestamp_ = thread_timestamp;
102   duration_ = TimeDelta::FromInternalValue(-1);
103   scope_ = scope;
104   id_ = id;
105   category_group_enabled_ = category_group_enabled;
106   name_ = name;
107   thread_id_ = thread_id;
108   phase_ = phase;
109   flags_ = flags;
110   bind_id_ = bind_id;
111 
112   // Clamp num_args since it may have been set by a third_party library.
113   num_args = (num_args > kTraceMaxNumArgs) ? kTraceMaxNumArgs : num_args;
114   int i = 0;
115   for (; i < num_args; ++i) {
116     arg_names_[i] = arg_names[i];
117     arg_types_[i] = arg_types[i];
118 
119     if (arg_types[i] == TRACE_VALUE_TYPE_CONVERTABLE) {
120       convertable_values_[i] = std::move(convertable_values[i]);
121     } else {
122       arg_values_[i].as_uint = arg_values[i];
123       convertable_values_[i].reset();
124     }
125   }
126   for (; i < kTraceMaxNumArgs; ++i) {
127     arg_names_[i] = nullptr;
128     arg_values_[i].as_uint = 0u;
129     convertable_values_[i].reset();
130     arg_types_[i] = TRACE_VALUE_TYPE_UINT;
131   }
132 
133   bool copy = !!(flags & TRACE_EVENT_FLAG_COPY);
134   size_t alloc_size = 0;
135   if (copy) {
136     alloc_size += GetAllocLength(name) + GetAllocLength(scope);
137     for (i = 0; i < num_args; ++i) {
138       alloc_size += GetAllocLength(arg_names_[i]);
139       if (arg_types_[i] == TRACE_VALUE_TYPE_STRING)
140         arg_types_[i] = TRACE_VALUE_TYPE_COPY_STRING;
141     }
142   }
143 
144   bool arg_is_copy[kTraceMaxNumArgs];
145   for (i = 0; i < num_args; ++i) {
146     // No copying of convertable types, we retain ownership.
147     if (arg_types_[i] == TRACE_VALUE_TYPE_CONVERTABLE)
148       continue;
149 
150     // We only take a copy of arg_vals if they are of type COPY_STRING.
151     arg_is_copy[i] = (arg_types_[i] == TRACE_VALUE_TYPE_COPY_STRING);
152     if (arg_is_copy[i])
153       alloc_size += GetAllocLength(arg_values_[i].as_string);
154   }
155 
156   if (alloc_size) {
157     parameter_copy_storage_.reset(new std::string);
158     parameter_copy_storage_->resize(alloc_size);
159     char* ptr = base::data(*parameter_copy_storage_);
160     const char* end = ptr + alloc_size;
161     if (copy) {
162       CopyTraceEventParameter(&ptr, &name_, end);
163       CopyTraceEventParameter(&ptr, &scope_, end);
164       for (i = 0; i < num_args; ++i) {
165         CopyTraceEventParameter(&ptr, &arg_names_[i], end);
166       }
167     }
168     for (i = 0; i < num_args; ++i) {
169       if (arg_types_[i] == TRACE_VALUE_TYPE_CONVERTABLE)
170         continue;
171       if (arg_is_copy[i])
172         CopyTraceEventParameter(&ptr, &arg_values_[i].as_string, end);
173     }
174     DCHECK_EQ(end, ptr) << "Overrun by " << ptr - end;
175   }
176 }
177 
Reset()178 void TraceEvent::Reset() {
179   // Only reset fields that won't be initialized in Initialize(), or that may
180   // hold references to other objects.
181   duration_ = TimeDelta::FromInternalValue(-1);
182   parameter_copy_storage_.reset();
183   for (int i = 0; i < kTraceMaxNumArgs; ++i)
184     convertable_values_[i].reset();
185 }
186 
UpdateDuration(const TimeTicks & now,const ThreadTicks & thread_now)187 void TraceEvent::UpdateDuration(const TimeTicks& now,
188                                 const ThreadTicks& thread_now) {
189   DCHECK_EQ(duration_.ToInternalValue(), -1);
190   duration_ = now - timestamp_;
191 
192   // |thread_timestamp_| can be empty if the thread ticks clock wasn't
193   // initialized when it was recorded.
194   if (thread_timestamp_ != ThreadTicks())
195     thread_duration_ = thread_now - thread_timestamp_;
196 }
197 
EstimateTraceMemoryOverhead(TraceEventMemoryOverhead * overhead)198 void TraceEvent::EstimateTraceMemoryOverhead(
199     TraceEventMemoryOverhead* overhead) {
200   overhead->Add(TraceEventMemoryOverhead::kTraceEvent, sizeof(*this));
201 
202   if (parameter_copy_storage_)
203     overhead->AddString(*parameter_copy_storage_);
204 
205   for (size_t i = 0; i < kTraceMaxNumArgs; ++i) {
206     if (arg_types_[i] == TRACE_VALUE_TYPE_CONVERTABLE)
207       convertable_values_[i]->EstimateTraceMemoryOverhead(overhead);
208   }
209 }
210 
211 // static
AppendValueAsJSON(unsigned char type,TraceEvent::TraceValue value,std::string * out)212 void TraceEvent::AppendValueAsJSON(unsigned char type,
213                                    TraceEvent::TraceValue value,
214                                    std::string* out) {
215   switch (type) {
216     case TRACE_VALUE_TYPE_BOOL:
217       *out += value.as_bool ? "true" : "false";
218       break;
219     case TRACE_VALUE_TYPE_UINT:
220       StringAppendF(out, "%" PRIu64, static_cast<uint64_t>(value.as_uint));
221       break;
222     case TRACE_VALUE_TYPE_INT:
223       StringAppendF(out, "%" PRId64, static_cast<int64_t>(value.as_int));
224       break;
225     case TRACE_VALUE_TYPE_DOUBLE: {
226       // FIXME: base/json/json_writer.cc is using the same code,
227       //        should be made into a common method.
228       std::string real;
229       double val = value.as_double;
230       if (std::isfinite(val)) {
231         real = NumberToString(val);
232         // Ensure that the number has a .0 if there's no decimal or 'e'.  This
233         // makes sure that when we read the JSON back, it's interpreted as a
234         // real rather than an int.
235         if (real.find('.') == std::string::npos &&
236             real.find('e') == std::string::npos &&
237             real.find('E') == std::string::npos) {
238           real.append(".0");
239         }
240         // The JSON spec requires that non-integer values in the range (-1,1)
241         // have a zero before the decimal point - ".52" is not valid, "0.52" is.
242         if (real[0] == '.') {
243           real.insert(0, "0");
244         } else if (real.length() > 1 && real[0] == '-' && real[1] == '.') {
245           // "-.1" bad "-0.1" good
246           real.insert(1, "0");
247         }
248       } else if (std::isnan(val)){
249         // The JSON spec doesn't allow NaN and Infinity (since these are
250         // objects in EcmaScript).  Use strings instead.
251         real = "\"NaN\"";
252       } else if (val < 0) {
253         real = "\"-Infinity\"";
254       } else {
255         real = "\"Infinity\"";
256       }
257       StringAppendF(out, "%s", real.c_str());
258       break;
259     }
260     case TRACE_VALUE_TYPE_POINTER:
261       // JSON only supports double and int numbers.
262       // So as not to lose bits from a 64-bit pointer, output as a hex string.
263       StringAppendF(
264           out, "\"0x%" PRIx64 "\"",
265           static_cast<uint64_t>(reinterpret_cast<uintptr_t>(value.as_pointer)));
266       break;
267     case TRACE_VALUE_TYPE_STRING:
268     case TRACE_VALUE_TYPE_COPY_STRING:
269       EscapeJSONString(value.as_string ? value.as_string : "NULL", true, out);
270       break;
271     default:
272       NOTREACHED() << "Don't know how to print this value";
273       break;
274   }
275 }
276 
AppendAsJSON(std::string * out,const ArgumentFilterPredicate & argument_filter_predicate) const277 void TraceEvent::AppendAsJSON(
278     std::string* out,
279     const ArgumentFilterPredicate& argument_filter_predicate) const {
280   int64_t time_int64 = timestamp_.ToInternalValue();
281   int process_id;
282   int thread_id;
283   if ((flags_ & TRACE_EVENT_FLAG_HAS_PROCESS_ID) &&
284       process_id_ != kNullProcessId) {
285     process_id = process_id_;
286     thread_id = -1;
287   } else {
288     process_id = TraceLog::GetInstance()->process_id();
289     thread_id = thread_id_;
290   }
291   const char* category_group_name =
292       TraceLog::GetCategoryGroupName(category_group_enabled_);
293 
294   // Category group checked at category creation time.
295   DCHECK(!strchr(name_, '"'));
296   StringAppendF(out, "{\"pid\":%i,\"tid\":%i,\"ts\":%" PRId64
297                      ",\"ph\":\"%c\",\"cat\":\"%s\",\"name\":",
298                 process_id, thread_id, time_int64, phase_, category_group_name);
299   EscapeJSONString(name_, true, out);
300   *out += ",\"args\":";
301 
302   // Output argument names and values, stop at first NULL argument name.
303   // TODO(oysteine): The dual predicates here is a bit ugly; if the filtering
304   // capabilities need to grow even more precise we should rethink this
305   // approach
306   ArgumentNameFilterPredicate argument_name_filter_predicate;
307   bool strip_args =
308       arg_names_[0] && !argument_filter_predicate.is_null() &&
309       !argument_filter_predicate.Run(category_group_name, name_,
310                                      &argument_name_filter_predicate);
311 
312   if (strip_args) {
313     *out += "\"__stripped__\"";
314   } else {
315     *out += "{";
316 
317     for (int i = 0; i < kTraceMaxNumArgs && arg_names_[i]; ++i) {
318       if (i > 0)
319         *out += ",";
320       *out += "\"";
321       *out += arg_names_[i];
322       *out += "\":";
323 
324       if (argument_name_filter_predicate.is_null() ||
325           argument_name_filter_predicate.Run(arg_names_[i])) {
326         if (arg_types_[i] == TRACE_VALUE_TYPE_CONVERTABLE)
327           convertable_values_[i]->AppendAsTraceFormat(out);
328         else
329           AppendValueAsJSON(arg_types_[i], arg_values_[i], out);
330       } else {
331         *out += "\"__stripped__\"";
332       }
333     }
334 
335     *out += "}";
336   }
337 
338   if (phase_ == TRACE_EVENT_PHASE_COMPLETE) {
339     int64_t duration = duration_.ToInternalValue();
340     if (duration != -1)
341       StringAppendF(out, ",\"dur\":%" PRId64, duration);
342     if (!thread_timestamp_.is_null()) {
343       int64_t thread_duration = thread_duration_.ToInternalValue();
344       if (thread_duration != -1)
345         StringAppendF(out, ",\"tdur\":%" PRId64, thread_duration);
346     }
347   }
348 
349   // Output tts if thread_timestamp is valid.
350   if (!thread_timestamp_.is_null()) {
351     int64_t thread_time_int64 = thread_timestamp_.ToInternalValue();
352     StringAppendF(out, ",\"tts\":%" PRId64, thread_time_int64);
353   }
354 
355   // Output async tts marker field if flag is set.
356   if (flags_ & TRACE_EVENT_FLAG_ASYNC_TTS) {
357     StringAppendF(out, ", \"use_async_tts\":1");
358   }
359 
360   // If id_ is set, print it out as a hex string so we don't loose any
361   // bits (it might be a 64-bit pointer).
362   unsigned int id_flags_ = flags_ & (TRACE_EVENT_FLAG_HAS_ID |
363                                      TRACE_EVENT_FLAG_HAS_LOCAL_ID |
364                                      TRACE_EVENT_FLAG_HAS_GLOBAL_ID);
365   if (id_flags_) {
366     if (scope_ != trace_event_internal::kGlobalScope)
367       StringAppendF(out, ",\"scope\":\"%s\"", scope_);
368 
369     switch (id_flags_) {
370       case TRACE_EVENT_FLAG_HAS_ID:
371         StringAppendF(out, ",\"id\":\"0x%" PRIx64 "\"",
372                       static_cast<uint64_t>(id_));
373         break;
374 
375       case TRACE_EVENT_FLAG_HAS_LOCAL_ID:
376         StringAppendF(out, ",\"id2\":{\"local\":\"0x%" PRIx64 "\"}",
377                       static_cast<uint64_t>(id_));
378         break;
379 
380       case TRACE_EVENT_FLAG_HAS_GLOBAL_ID:
381         StringAppendF(out, ",\"id2\":{\"global\":\"0x%" PRIx64 "\"}",
382                       static_cast<uint64_t>(id_));
383         break;
384 
385       default:
386         NOTREACHED() << "More than one of the ID flags are set";
387         break;
388     }
389   }
390 
391   if (flags_ & TRACE_EVENT_FLAG_BIND_TO_ENCLOSING)
392     StringAppendF(out, ",\"bp\":\"e\"");
393 
394   if ((flags_ & TRACE_EVENT_FLAG_FLOW_OUT) ||
395       (flags_ & TRACE_EVENT_FLAG_FLOW_IN)) {
396     StringAppendF(out, ",\"bind_id\":\"0x%" PRIx64 "\"",
397                   static_cast<uint64_t>(bind_id_));
398   }
399   if (flags_ & TRACE_EVENT_FLAG_FLOW_IN)
400     StringAppendF(out, ",\"flow_in\":true");
401   if (flags_ & TRACE_EVENT_FLAG_FLOW_OUT)
402     StringAppendF(out, ",\"flow_out\":true");
403 
404   // Instant events also output their scope.
405   if (phase_ == TRACE_EVENT_PHASE_INSTANT) {
406     char scope = '?';
407     switch (flags_ & TRACE_EVENT_FLAG_SCOPE_MASK) {
408       case TRACE_EVENT_SCOPE_GLOBAL:
409         scope = TRACE_EVENT_SCOPE_NAME_GLOBAL;
410         break;
411 
412       case TRACE_EVENT_SCOPE_PROCESS:
413         scope = TRACE_EVENT_SCOPE_NAME_PROCESS;
414         break;
415 
416       case TRACE_EVENT_SCOPE_THREAD:
417         scope = TRACE_EVENT_SCOPE_NAME_THREAD;
418         break;
419     }
420     StringAppendF(out, ",\"s\":\"%c\"", scope);
421   }
422 
423   *out += "}";
424 }
425 
AppendPrettyPrinted(std::ostringstream * out) const426 void TraceEvent::AppendPrettyPrinted(std::ostringstream* out) const {
427   *out << name_ << "[";
428   *out << TraceLog::GetCategoryGroupName(category_group_enabled_);
429   *out << "]";
430   if (arg_names_[0]) {
431     *out << ", {";
432     for (int i = 0; i < kTraceMaxNumArgs && arg_names_[i]; ++i) {
433       if (i > 0)
434         *out << ", ";
435       *out << arg_names_[i] << ":";
436       std::string value_as_text;
437 
438       if (arg_types_[i] == TRACE_VALUE_TYPE_CONVERTABLE)
439         convertable_values_[i]->AppendAsTraceFormat(&value_as_text);
440       else
441         AppendValueAsJSON(arg_types_[i], arg_values_[i], &value_as_text);
442 
443       *out << value_as_text;
444     }
445     *out << "}";
446   }
447 }
448 
449 }  // namespace trace_event
450 }  // namespace base
451 
452 namespace trace_event_internal {
453 
454 std::unique_ptr<base::trace_event::ConvertableToTraceFormat>
AsConvertableToTraceFormat() const455 TraceID::AsConvertableToTraceFormat() const {
456   auto value = std::make_unique<base::trace_event::TracedValue>();
457 
458   if (scope_ != kGlobalScope)
459     value->SetString("scope", scope_);
460 
461   const char* id_field_name = "id";
462   if (id_flags_ == TRACE_EVENT_FLAG_HAS_GLOBAL_ID) {
463     id_field_name = "global";
464     value->BeginDictionary("id2");
465   } else if (id_flags_ == TRACE_EVENT_FLAG_HAS_LOCAL_ID) {
466     id_field_name = "local";
467     value->BeginDictionary("id2");
468   } else if (id_flags_ != TRACE_EVENT_FLAG_HAS_ID) {
469     NOTREACHED() << "Unrecognized ID flag";
470   }
471 
472   if (has_prefix_) {
473     value->SetString(id_field_name,
474                      base::StringPrintf("0x%" PRIx64 "/0x%" PRIx64,
475                                         static_cast<uint64_t>(prefix_),
476                                         static_cast<uint64_t>(raw_id_)));
477   } else {
478     value->SetString(
479         id_field_name,
480         base::StringPrintf("0x%" PRIx64, static_cast<uint64_t>(raw_id_)));
481   }
482 
483   if (id_flags_ != TRACE_EVENT_FLAG_HAS_ID)
484     value->EndDictionary();
485 
486   return std::move(value);
487 }
488 
489 }  // namespace trace_event_internal
490