• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2015 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef BASE_TRACE_EVENT_TRACE_CONFIG_H_
6 #define BASE_TRACE_EVENT_TRACE_CONFIG_H_
7 
8 #include <stdint.h>
9 
10 #include <memory>
11 #include <set>
12 #include <string>
13 #include <unordered_set>
14 #include <vector>
15 
16 #include "base/base_export.h"
17 #include "base/gtest_prod_util.h"
18 #include "base/strings/string_piece.h"
19 #include "base/trace_event/memory_dump_request_args.h"
20 #include "base/trace_event/trace_config_category_filter.h"
21 #include "base/values.h"
22 
23 namespace base::trace_event {
24 
25 class ConvertableToTraceFormat;
26 
27 // Options determines how the trace buffer stores data.
28 // A Java counterpart will be generated for this enum.
29 // GENERATED_JAVA_ENUM_PACKAGE: org.chromium.base
30 enum TraceRecordMode {
31   // Record until the trace buffer is full.
32   RECORD_UNTIL_FULL,
33 
34   // Record until the user ends the trace. The trace buffer is a fixed size
35   // and we use it as a ring buffer during recording.
36   RECORD_CONTINUOUSLY,
37 
38   // Record until the trace buffer is full, but with a huge buffer size.
39   RECORD_AS_MUCH_AS_POSSIBLE,
40 
41   // Echo to console. Events are discarded.
42   ECHO_TO_CONSOLE,
43 };
44 
45 class BASE_EXPORT TraceConfig {
46  public:
47   using StringList = std::vector<std::string>;
48 
49   // Specifies the memory dump config for tracing.
50   // Used only when "memory-infra" category is enabled.
51   struct BASE_EXPORT MemoryDumpConfig {
52     MemoryDumpConfig();
53     MemoryDumpConfig(const MemoryDumpConfig& other);
54     ~MemoryDumpConfig();
55 
56     // Specifies the triggers in the memory dump config.
57     struct Trigger {
58       uint32_t min_time_between_dumps_ms;
59       MemoryDumpLevelOfDetail level_of_detail;
60       MemoryDumpType trigger_type;
61     };
62 
63     // Specifies the configuration options for the heap profiler.
64     struct HeapProfiler {
65       // Default value for |breakdown_threshold_bytes|.
66       enum { kDefaultBreakdownThresholdBytes = 1024 };
67 
68       HeapProfiler();
69 
70       // Reset the options to default.
71       void Clear();
72 
73       uint32_t breakdown_threshold_bytes;
74     };
75 
76     // Reset the values in the config.
77     void Clear();
78 
79     void Merge(const MemoryDumpConfig& config);
80 
81     // Set of memory dump modes allowed for the tracing session. The explicitly
82     // triggered dumps will be successful only if the dump mode is allowed in
83     // the config.
84     std::set<MemoryDumpLevelOfDetail> allowed_dump_modes;
85 
86     std::vector<Trigger> triggers;
87     HeapProfiler heap_profiler_options;
88   };
89 
90   class BASE_EXPORT ProcessFilterConfig {
91    public:
92     ProcessFilterConfig();
93     explicit ProcessFilterConfig(
94         const std::unordered_set<base::ProcessId>& included_process_ids);
95     ProcessFilterConfig(const ProcessFilterConfig&);
96     ~ProcessFilterConfig();
97 
empty()98     bool empty() const { return included_process_ids_.empty(); }
99 
100     void Clear();
101     void Merge(const ProcessFilterConfig&);
102 
103     void InitializeFromConfigDict(const Value::Dict&);
104     void ToDict(Value::Dict& dict) const;
105 
106     bool IsEnabled(base::ProcessId) const;
included_process_ids()107     const std::unordered_set<base::ProcessId>& included_process_ids() const {
108       return included_process_ids_;
109     }
110 
111     bool operator==(const ProcessFilterConfig& other) const {
112       return included_process_ids_ == other.included_process_ids_;
113     }
114 
115    private:
116     std::unordered_set<base::ProcessId> included_process_ids_;
117   };
118 
119   class BASE_EXPORT EventFilterConfig {
120    public:
121     explicit EventFilterConfig(const std::string& predicate_name);
122     EventFilterConfig(const EventFilterConfig& tc);
123 
124     ~EventFilterConfig();
125 
126     EventFilterConfig& operator=(const EventFilterConfig& rhs);
127 
128     void InitializeFromConfigDict(const Value::Dict& event_filter);
129 
130     void SetCategoryFilter(const TraceConfigCategoryFilter& category_filter);
131 
132     void ToDict(Value::Dict& filter_dict) const;
133 
134     bool GetArgAsSet(const char* key, std::unordered_set<std::string>*) const;
135 
136     bool IsCategoryGroupEnabled(const StringPiece& category_group_name) const;
137 
predicate_name()138     const std::string& predicate_name() const { return predicate_name_; }
filter_args()139     const Value::Dict& filter_args() const { return args_; }
category_filter()140     const TraceConfigCategoryFilter& category_filter() const {
141       return category_filter_;
142     }
143 
144    private:
145     std::string predicate_name_;
146     TraceConfigCategoryFilter category_filter_;
147     Value::Dict args_;
148   };
149   typedef std::vector<EventFilterConfig> EventFilters;
150 
151   static std::string TraceRecordModeToStr(TraceRecordMode record_mode);
152 
153   TraceConfig();
154 
155   // Create TraceConfig object from category filter and trace options strings.
156   //
157   // |category_filter_string| is a comma-delimited list of category wildcards.
158   // A category can have an optional '-' prefix to make it an excluded category.
159   // All the same rules apply above, so for example, having both included and
160   // excluded categories in the same list would not be supported.
161   //
162   // |trace_options_string| is a comma-delimited list of trace options.
163   // Possible options are: "record-until-full", "record-continuously",
164   // "record-as-much-as-possible", "trace-to-console", "enable-systrace" and
165   // "enable-argument-filter".
166   // The first 4 options are trace recoding modes and hence
167   // mutually exclusive. If more than one trace recording modes appear in the
168   // options_string, the last one takes precedence. If none of the trace
169   // recording mode is specified, recording mode is RECORD_UNTIL_FULL.
170   //
171   // The trace option will first be reset to the default option
172   // (record_mode set to RECORD_UNTIL_FULL, enable_systrace and
173   // enable_argument_filter set to false) before options parsed from
174   // |trace_options_string| are applied on it. If |trace_options_string| is
175   // invalid, the final state of trace options is undefined.
176   //
177   // Example: TraceConfig("test_MyTest*", "record-until-full");
178   // Example: TraceConfig("test_MyTest*,test_OtherStuff",
179   //                      "record-continuously");
180   // Example: TraceConfig("-excluded_category1,-excluded_category2",
181   //                      "record-until-full, trace-to-console");
182   //          would set ECHO_TO_CONSOLE as the recording mode.
183   // Example: TraceConfig("-*,webkit", "");
184   //          would disable everything but webkit; and use default options.
185   // Example: TraceConfig("-webkit", "");
186   //          would enable everything but webkit; and use default options.
187   TraceConfig(StringPiece category_filter_string,
188               StringPiece trace_options_string);
189 
190   TraceConfig(StringPiece category_filter_string, TraceRecordMode record_mode);
191 
192   // Create TraceConfig object from the trace config string.
193   //
194   // |config_string| is a dictionary formatted as a JSON string, containing both
195   // category filters and trace options.
196   //
197   // Example:
198   //   {
199   //     "record_mode": "record-continuously",
200   //     "enable_systrace": true,
201   //     "enable_argument_filter": true,
202   //     "included_categories": ["included",
203   //                             "inc_pattern*",
204   //                             "disabled-by-default-memory-infra"],
205   //     "excluded_categories": ["excluded", "exc_pattern*"],
206   //     "memory_dump_config": {
207   //       "triggers": [
208   //         {
209   //           "mode": "detailed",
210   //           "periodic_interval_ms": 2000
211   //         }
212   //       ]
213   //     }
214   //   }
215   //
216   // Note: memory_dump_config can be specified only if
217   // disabled-by-default-memory-infra category is enabled.
218   explicit TraceConfig(StringPiece config_string);
219 
220   // Functionally identical to the above, but takes a parsed dictionary as input
221   // instead of its JSON serialization.
222   explicit TraceConfig(const Value::Dict& config);
223 
224   TraceConfig(const TraceConfig& tc);
225 
226   ~TraceConfig();
227 
228   TraceConfig& operator=(const TraceConfig& rhs);
229 
GetTraceRecordMode()230   TraceRecordMode GetTraceRecordMode() const { return record_mode_; }
GetTraceBufferSizeInEvents()231   size_t GetTraceBufferSizeInEvents() const {
232     return trace_buffer_size_in_events_;
233   }
GetTraceBufferSizeInKb()234   size_t GetTraceBufferSizeInKb() const { return trace_buffer_size_in_kb_; }
IsSystraceEnabled()235   bool IsSystraceEnabled() const { return enable_systrace_; }
IsArgumentFilterEnabled()236   bool IsArgumentFilterEnabled() const { return enable_argument_filter_; }
237 
SetTraceRecordMode(TraceRecordMode mode)238   void SetTraceRecordMode(TraceRecordMode mode) { record_mode_ = mode; }
SetTraceBufferSizeInEvents(size_t size)239   void SetTraceBufferSizeInEvents(size_t size) {
240     trace_buffer_size_in_events_ = size;
241   }
SetTraceBufferSizeInKb(size_t size)242   void SetTraceBufferSizeInKb(size_t size) { trace_buffer_size_in_kb_ = size; }
EnableSystrace()243   void EnableSystrace() { enable_systrace_ = true; }
244   void EnableSystraceEvent(const std::string& systrace_event);
EnableArgumentFilter()245   void EnableArgumentFilter() { enable_argument_filter_ = true; }
246   void EnableHistogram(const std::string& histogram_name);
247 
248   // Writes the string representation of the TraceConfig. The string is JSON
249   // formatted.
250   std::string ToString() const;
251 
252   // Returns a copy of the TraceConfig wrapped in a ConvertableToTraceFormat
253   std::unique_ptr<ConvertableToTraceFormat> AsConvertableToTraceFormat() const;
254 
255   // Write the string representation of the CategoryFilter part.
256   std::string ToCategoryFilterString() const;
257 
258   // Write the string representation of the trace options part (record mode,
259   // systrace, argument filtering). Does not include category filters, event
260   // filters, or memory dump configs.
261   std::string ToTraceOptionsString() const;
262 
263 #if BUILDFLAG(USE_PERFETTO_CLIENT_LIBRARY)
264   // Write the serialized perfetto::TrackEventConfig corresponding to this
265   // TraceConfig.
266   std::string ToPerfettoTrackEventConfigRaw(
267       bool privacy_filtering_enabled) const;
268 #endif  // BUILDFLAG(USE_PERFETTO_CLIENT_LIBRARY)
269 
270   // Returns true if at least one category in the list is enabled by this
271   // trace config. This is used to determine if the category filters are
272   // enabled in the TRACE_* macros.
273   bool IsCategoryGroupEnabled(const StringPiece& category_group_name) const;
274 
275   // Merges config with the current TraceConfig
276   void Merge(const TraceConfig& config);
277 
278   void Clear();
279 
280   // Clears and resets the memory dump config.
281   void ResetMemoryDumpConfig(const MemoryDumpConfig& memory_dump_config);
282 
category_filter()283   const TraceConfigCategoryFilter& category_filter() const {
284     return category_filter_;
285   }
286 
memory_dump_config()287   const MemoryDumpConfig& memory_dump_config() const {
288     return memory_dump_config_;
289   }
290 
process_filter_config()291   const ProcessFilterConfig& process_filter_config() const {
292     return process_filter_config_;
293   }
294   void SetProcessFilterConfig(const ProcessFilterConfig&);
295 
event_filters()296   const EventFilters& event_filters() const { return event_filters_; }
SetEventFilters(const EventFilters & filter_configs)297   void SetEventFilters(const EventFilters& filter_configs) {
298     event_filters_ = filter_configs;
299   }
300 
301   // Returns true if event names should not contain package names.
IsEventPackageNameFilterEnabled()302   bool IsEventPackageNameFilterEnabled() const {
303     return enable_event_package_name_filter_;
304   }
305 
306   // If `enabled` is true, event names will not contain package names.
SetEventPackageNameFilterEnabled(bool enabled)307   void SetEventPackageNameFilterEnabled(bool enabled) {
308     enable_event_package_name_filter_ = enabled;
309   }
310 
systrace_events()311   const std::unordered_set<std::string>& systrace_events() const {
312     return systrace_events_;
313   }
314 
histogram_names()315   const std::unordered_set<std::string>& histogram_names() const {
316     return histogram_names_;
317   }
318 
319  private:
320   FRIEND_TEST_ALL_PREFIXES(TraceConfigTest, TraceConfigFromValidLegacyFormat);
321   FRIEND_TEST_ALL_PREFIXES(TraceConfigTest,
322                            TraceConfigFromInvalidLegacyStrings);
323   FRIEND_TEST_ALL_PREFIXES(TraceConfigTest, SystraceEventsSerialization);
324 
325   // The default trace config, used when none is provided.
326   // Allows all non-disabled-by-default categories through, except if they end
327   // in the suffix 'Debug' or 'Test'.
328   void InitializeDefault();
329 
330   // Initialize from a config dictionary.
331   void InitializeFromConfigDict(const Value::Dict& dict);
332 
333   // Initialize from a config string.
334   void InitializeFromConfigString(StringPiece config_string);
335 
336   // Initialize from category filter and trace options strings
337   void InitializeFromStrings(StringPiece category_filter_string,
338                              StringPiece trace_options_string);
339 
340   void SetMemoryDumpConfigFromConfigDict(const Value::Dict& memory_dump_config);
341   void SetDefaultMemoryDumpConfig();
342 
343   void SetHistogramNamesFromConfigList(const Value::List& histogram_names);
344   void SetEventFiltersFromConfigList(const Value::List& event_filters);
345   Value ToValue() const;
346 
347   TraceRecordMode record_mode_;
348   size_t trace_buffer_size_in_events_ = 0;  // 0 specifies default size
349   size_t trace_buffer_size_in_kb_ = 0;      // 0 specifies default size
350   bool enable_systrace_ : 1;
351   bool enable_argument_filter_ : 1;
352 
353   TraceConfigCategoryFilter category_filter_;
354 
355   MemoryDumpConfig memory_dump_config_;
356   ProcessFilterConfig process_filter_config_;
357 
358   EventFilters event_filters_;
359   bool enable_event_package_name_filter_ : 1;
360   std::unordered_set<std::string> histogram_names_;
361   std::unordered_set<std::string> systrace_events_;
362 };
363 
364 }  // namespace base::trace_event
365 
366 #endif  // BASE_TRACE_EVENT_TRACE_CONFIG_H_
367