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