1 /* 2 * Copyright (C) 2020 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 INCLUDE_PERFETTO_TRACING_INTERNAL_INTERCEPTOR_TRACE_WRITER_H_ 18 #define INCLUDE_PERFETTO_TRACING_INTERNAL_INTERCEPTOR_TRACE_WRITER_H_ 19 20 #include <atomic> 21 #include <cstdint> 22 #include <functional> 23 #include <memory> 24 25 #include "perfetto/protozero/message_handle.h" 26 #include "perfetto/protozero/scattered_heap_buffer.h" 27 #include "perfetto/tracing/interceptor.h" 28 #include "perfetto/tracing/internal/data_source_internal.h" 29 #include "perfetto/tracing/trace_writer_base.h" 30 #include "protos/perfetto/trace/trace_packet.pbzero.h" 31 32 namespace perfetto { 33 namespace internal { 34 35 // A heap-backed trace writer used to reroute trace packets to an interceptor. 36 class InterceptorTraceWriter : public TraceWriterBase { 37 public: 38 InterceptorTraceWriter(std::unique_ptr<InterceptorBase::ThreadLocalState> tls, 39 InterceptorBase::TracePacketCallback packet_callback, 40 DataSourceStaticState* static_state, 41 uint32_t instance_index); 42 ~InterceptorTraceWriter() override; 43 44 // TraceWriterBase implementation. 45 protozero::MessageHandle<protos::pbzero::TracePacket> NewTracePacket() 46 override; 47 void FinishTracePacket() override; 48 void Flush(std::function<void()> callback = {}) override; 49 uint64_t written() const override; 50 uint64_t drop_count() const override; 51 52 private: 53 std::unique_ptr<InterceptorBase::ThreadLocalState> tls_; 54 InterceptorBase::TracePacketCallback packet_callback_; 55 56 protozero::HeapBuffered<protos::pbzero::TracePacket> cur_packet_; 57 uint64_t bytes_written_ = 0; 58 59 // Static state of the data source we are intercepting. 60 DataSourceStaticState* const static_state_; 61 62 // Index of the data source tracing session which we are intercepting 63 // (0...kMaxDataSourceInstances - 1). Used to look up this interceptor's 64 // session state (i.e., the Interceptor class instance) in the 65 // DataSourceStaticState::instances array. 66 const uint32_t instance_index_; 67 68 const uint32_t sequence_id_; 69 70 static std::atomic<uint32_t> next_sequence_id_; 71 }; 72 73 } // namespace internal 74 } // namespace perfetto 75 76 #endif // INCLUDE_PERFETTO_TRACING_INTERNAL_INTERCEPTOR_TRACE_WRITER_H_ 77