• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2019 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 #ifndef SRC_TRACING_CORE_METATRACE_WRITER_H_
18 #define SRC_TRACING_CORE_METATRACE_WRITER_H_
19 
20 #include <functional>
21 #include <memory>
22 
23 #include "perfetto/ext/base/metatrace.h"
24 #include "perfetto/ext/base/thread_checker.h"
25 #include "perfetto/ext/base/weak_ptr.h"
26 
27 namespace perfetto {
28 
29 namespace base {
30 class TaskRunner;
31 }
32 
33 class TraceWriter;
34 
35 // Complements the base::metatrace infrastructure.
36 // It hooks a callback to metatrace::Enable() and writes metatrace events into
37 // a TraceWriter whenever the metatrace ring buffer is half full.
38 // It is safe to create and attempt to start multiple instances of this class,
39 // however only the first one will succeed because the metatrace framework
40 // doesn't support multiple instances.
41 // This class is defined here (instead of directly in src/probes/) so it can
42 // be reused by other components (e.g. heapprofd).
43 class MetatraceWriter {
44  public:
45   static constexpr char kDataSourceName[] = "perfetto.metatrace";
46 
47   MetatraceWriter();
48   ~MetatraceWriter();
49 
50   MetatraceWriter(const MetatraceWriter&) = delete;
51   MetatraceWriter& operator=(const MetatraceWriter&) = delete;
52   MetatraceWriter(MetatraceWriter&&) = delete;
53   MetatraceWriter& operator=(MetatraceWriter&&) = delete;
54 
55   void Enable(base::TaskRunner*, std::unique_ptr<TraceWriter>, uint32_t tags);
56   void Disable();
57   void WriteAllAndFlushTraceWriter(std::function<void()> callback);
58 
59  private:
60   void WriteAllAvailableEvents();
61 
62   bool started_ = false;
63   base::TaskRunner* task_runner_ = nullptr;
64   std::unique_ptr<TraceWriter> trace_writer_;
65   PERFETTO_THREAD_CHECKER(thread_checker_)
66   base::WeakPtrFactory<MetatraceWriter> weak_ptr_factory_;  // Keep last.
67 };
68 
69 }  // namespace perfetto
70 
71 #endif  // SRC_TRACING_CORE_METATRACE_WRITER_H_
72