blob: c643b3a78714fe69e4d49301c6b629889391ddee [file] [log] [blame]
Primiano Tucci4f9b6d72017-12-05 20:59:16 +00001/*
2 * Copyright (C) 2017 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
Florian Mayer6a1a4d52018-06-08 16:47:07 +010017#ifndef SRC_TRACING_CORE_TRACING_SERVICE_IMPL_H_
18#define SRC_TRACING_CORE_TRACING_SERVICE_IMPL_H_
Primiano Tucci4f9b6d72017-12-05 20:59:16 +000019
20#include <functional>
21#include <map>
22#include <memory>
Primiano Tucci14219ff2019-02-27 12:41:05 +010023#include <mutex>
Primiano Tucci42e2de12017-12-07 16:46:04 +000024#include <set>
Stephen Nusko59847292019-03-22 13:54:08 +000025#include <vector>
Primiano Tucci4f9b6d72017-12-05 20:59:16 +000026
Eric Seckler57c89d92018-10-26 15:11:55 +010027#include "perfetto/base/gtest_prod_util.h"
Primiano Tucci2ffd1a52018-03-27 01:01:30 +010028#include "perfetto/base/logging.h"
Eric Secklerf3f524b2018-12-13 09:09:34 +000029#include "perfetto/base/optional.h"
Sami Kyostilafbccb3c2018-03-21 14:00:47 +000030#include "perfetto/base/time.h"
Primiano Tucci42e2de12017-12-07 16:46:04 +000031#include "perfetto/base/weak_ptr.h"
Primiano Tucci4f9b6d72017-12-05 20:59:16 +000032#include "perfetto/tracing/core/basic_types.h"
Primiano Tucciecf9e4a2018-03-14 14:51:58 +000033#include "perfetto/tracing/core/commit_data_request.h"
Primiano Tucci53589332017-12-19 11:31:13 +010034#include "perfetto/tracing/core/data_source_descriptor.h"
Eric Seckler7b0c9452019-03-18 13:14:36 +000035#include "perfetto/tracing/core/observable_events.h"
Primiano Tucci53589332017-12-19 11:31:13 +010036#include "perfetto/tracing/core/shared_memory_abi.h"
Oystein Eftevaag1269b4a2018-01-10 16:29:38 -080037#include "perfetto/tracing/core/trace_config.h"
Eric Secklereaf29ed2019-01-23 09:53:55 +000038#include "perfetto/tracing/core/trace_stats.h"
Florian Mayer6a1a4d52018-06-08 16:47:07 +010039#include "perfetto/tracing/core/tracing_service.h"
Primiano Tucci53589332017-12-19 11:31:13 +010040#include "src/tracing/core/id_allocator.h"
Primiano Tucci4f9b6d72017-12-05 20:59:16 +000041
42namespace perfetto {
43
44namespace base {
45class TaskRunner;
46} // namespace base
47
Primiano Tucci42e2de12017-12-07 16:46:04 +000048class Consumer;
Primiano Tucci4f9b6d72017-12-05 20:59:16 +000049class DataSourceConfig;
50class Producer;
51class SharedMemory;
Primiano Tucci2ffd1a52018-03-27 01:01:30 +010052class SharedMemoryArbiterImpl;
Hector Dearman6214c8f2018-03-27 16:16:22 +010053class TraceBuffer;
Primiano Tucci42e2de12017-12-07 16:46:04 +000054class TraceConfig;
Sami Kyostilafbccb3c2018-03-21 14:00:47 +000055class TracePacket;
Primiano Tucci4f9b6d72017-12-05 20:59:16 +000056
57// The tracing service business logic.
Florian Mayer6a1a4d52018-06-08 16:47:07 +010058class TracingServiceImpl : public TracingService {
Eric Seckler4ff03e52019-03-15 10:10:30 +000059 private:
60 struct DataSourceInstance;
61
Primiano Tucci4f9b6d72017-12-05 20:59:16 +000062 public:
Primiano Tucci1a1951d2018-04-04 21:08:16 +020063 static constexpr size_t kDefaultShmSize = 256 * 1024ul;
Primiano Tuccie7ca7c62018-04-07 08:28:03 +020064 static constexpr size_t kMaxShmSize = 32 * 1024 * 1024ul;
Primiano Tuccibaeecf12018-07-25 12:02:20 +010065 static constexpr uint32_t kDataSourceStopTimeoutMs = 5000;
Primiano Tucci9754d0d2018-09-15 12:41:46 +010066 static constexpr uint8_t kSyncMarker[] = {0x82, 0x47, 0x7a, 0x76, 0xb2, 0x8d,
67 0x42, 0xba, 0x81, 0xdc, 0x33, 0x32,
68 0x6d, 0x57, 0xa0, 0x79};
Primiano Tucci1a1951d2018-04-04 21:08:16 +020069
Primiano Tucci4f9b6d72017-12-05 20:59:16 +000070 // The implementation behind the service endpoint exposed to each producer.
Florian Mayer6a1a4d52018-06-08 16:47:07 +010071 class ProducerEndpointImpl : public TracingService::ProducerEndpoint {
Primiano Tucci4f9b6d72017-12-05 20:59:16 +000072 public:
73 ProducerEndpointImpl(ProducerID,
Sami Kyostila32e0b542018-02-14 08:55:43 +000074 uid_t uid,
Florian Mayer6a1a4d52018-06-08 16:47:07 +010075 TracingServiceImpl*,
Primiano Tucci4f9b6d72017-12-05 20:59:16 +000076 base::TaskRunner*,
Isabelle Taylor86262cb2018-03-27 16:00:54 +010077 Producer*,
Oystein Eftevaagc8d2f072019-03-29 09:41:04 -070078 const std::string& producer_name,
79 bool in_process);
Primiano Tucci4f9b6d72017-12-05 20:59:16 +000080 ~ProducerEndpointImpl() override;
81
Florian Mayer6a1a4d52018-06-08 16:47:07 +010082 // TracingService::ProducerEndpoint implementation.
Primiano Tucci9daa4832018-03-28 23:28:17 +010083 void RegisterDataSource(const DataSourceDescriptor&) override;
84 void UnregisterDataSource(const std::string& name) override;
Eric Seckler1c4e1ac2018-11-29 10:23:14 +000085 void RegisterTraceWriter(uint32_t writer_id,
86 uint32_t target_buffer) override;
87 void UnregisterTraceWriter(uint32_t writer_id) override;
Primiano Tucci3e69ed92018-03-14 14:52:29 +000088 void CommitData(const CommitDataRequest&, CommitDataCallback) override;
Isabelle Taylor69faa902018-03-21 15:42:03 +000089 void SetSharedMemory(std::unique_ptr<SharedMemory>);
Primiano Tucciaf429f92017-12-19 01:51:50 +010090 std::unique_ptr<TraceWriter> CreateTraceWriter(BufferID) override;
Oystein Eftevaagf4cccb52019-04-17 13:31:29 -070091 SharedMemoryArbiter* GetInProcessShmemArbiter() override;
Primiano Tuccid52e6272018-04-06 19:06:53 +020092 void NotifyFlushComplete(FlushRequestID) override;
Eric Seckler4ff03e52019-03-15 10:10:30 +000093 void NotifyDataSourceStarted(DataSourceInstanceID) override;
Primiano Tuccibaeecf12018-07-25 12:02:20 +010094 void NotifyDataSourceStopped(DataSourceInstanceID) override;
Primiano Tucci4f9b6d72017-12-05 20:59:16 +000095 SharedMemory* shared_memory() const override;
Isabelle Taylor69faa902018-03-21 15:42:03 +000096 size_t shared_buffer_page_size_kb() const override;
Stephen Nusko1393ffd2019-03-22 13:54:58 +000097 void ActivateTriggers(const std::vector<std::string>&) override;
Primiano Tucci4f9b6d72017-12-05 20:59:16 +000098
Primiano Tuccibaeecf12018-07-25 12:02:20 +010099 void OnTracingSetup();
Primiano Tucci674076d2018-10-01 10:41:09 +0100100 void SetupDataSource(DataSourceInstanceID, const DataSourceConfig&);
Primiano Tucciafb72b52018-09-25 09:37:24 +0100101 void StartDataSource(DataSourceInstanceID, const DataSourceConfig&);
Primiano Tucci674076d2018-10-01 10:41:09 +0100102 void StopDataSource(DataSourceInstanceID);
Primiano Tuccibaeecf12018-07-25 12:02:20 +0100103 void Flush(FlushRequestID, const std::vector<DataSourceInstanceID>&);
Eric Seckler6dc23592018-11-30 10:59:06 +0000104 void OnFreeBuffers(const std::vector<BufferID>& target_buffers);
Ryan Savitski33868d52019-05-13 10:56:14 +0100105 void ClearIncrementalState(const std::vector<DataSourceInstanceID>&);
Primiano Tuccibaeecf12018-07-25 12:02:20 +0100106
Eric Secklerdd0ad102018-12-06 11:32:04 +0000107 bool is_allowed_target_buffer(BufferID buffer_id) const {
108 return allowed_target_buffers_.count(buffer_id);
109 }
110
Eric Secklerf3f524b2018-12-13 09:09:34 +0000111 base::Optional<BufferID> buffer_id_for_writer(WriterID writer_id) const {
112 const auto it = writers_.find(writer_id);
113 if (it != writers_.end())
114 return it->second;
115 return base::nullopt;
116 }
117
Primiano Tucci4f9b6d72017-12-05 20:59:16 +0000118 private:
Florian Mayer6a1a4d52018-06-08 16:47:07 +0100119 friend class TracingServiceImpl;
120 friend class TracingServiceImplTest;
Primiano Tucci4f9b6d72017-12-05 20:59:16 +0000121 ProducerEndpointImpl(const ProducerEndpointImpl&) = delete;
122 ProducerEndpointImpl& operator=(const ProducerEndpointImpl&) = delete;
123
124 ProducerID const id_;
Sami Kyostila32e0b542018-02-14 08:55:43 +0000125 const uid_t uid_;
Florian Mayer6a1a4d52018-06-08 16:47:07 +0100126 TracingServiceImpl* const service_;
Primiano Tucci4f9b6d72017-12-05 20:59:16 +0000127 base::TaskRunner* const task_runner_;
128 Producer* producer_;
129 std::unique_ptr<SharedMemory> shared_memory_;
Isabelle Taylor69faa902018-03-21 15:42:03 +0000130 size_t shared_buffer_page_size_kb_ = 0;
Primiano Tucci53589332017-12-19 11:31:13 +0100131 SharedMemoryABI shmem_abi_;
Primiano Tucci1a1951d2018-04-04 21:08:16 +0200132 size_t shmem_size_hint_bytes_ = 0;
Isabelle Taylor86262cb2018-03-27 16:00:54 +0100133 const std::string name_;
Oystein Eftevaagc8d2f072019-03-29 09:41:04 -0700134 bool in_process_;
Primiano Tucci2ffd1a52018-03-27 01:01:30 +0100135
Eric Seckler6dc23592018-11-30 10:59:06 +0000136 // Set of the global target_buffer IDs that the producer is configured to
137 // write into in any active tracing session.
138 std::set<BufferID> allowed_target_buffers_;
139
Eric Secklerf3f524b2018-12-13 09:09:34 +0000140 // Maps registered TraceWriter IDs to their target buffers as registered by
141 // the producer. Note that producers aren't required to register their
142 // writers, so we may see commits of chunks with WriterIDs that aren't
143 // contained in this map. However, if a producer does register a writer, the
144 // service will prevent the writer from writing into any other buffer than
145 // the one associated with it here. The BufferIDs stored in this map are
146 // untrusted, so need to be verified against |allowed_target_buffers_|
147 // before use.
148 std::map<WriterID, BufferID> writers_;
149
Oystein Eftevaagc8d2f072019-03-29 09:41:04 -0700150 // This is used only in in-process configurations.
Primiano Tucci14219ff2019-02-27 12:41:05 +0100151 // SharedMemoryArbiterImpl methods themselves are thread-safe.
Primiano Tucci2ffd1a52018-03-27 01:01:30 +0100152 std::unique_ptr<SharedMemoryArbiterImpl> inproc_shmem_arbiter_;
Primiano Tucci14219ff2019-02-27 12:41:05 +0100153
Florian Mayercd08ec62018-01-31 17:49:25 +0000154 PERFETTO_THREAD_CHECKER(thread_checker_)
Primiano Tuccidca727d2018-04-04 11:31:55 +0200155 base::WeakPtrFactory<ProducerEndpointImpl> weak_ptr_factory_; // Keep last.
Primiano Tucci4f9b6d72017-12-05 20:59:16 +0000156 };
157
Primiano Tucci42e2de12017-12-07 16:46:04 +0000158 // The implementation behind the service endpoint exposed to each consumer.
Florian Mayer6a1a4d52018-06-08 16:47:07 +0100159 class ConsumerEndpointImpl : public TracingService::ConsumerEndpoint {
Primiano Tucci42e2de12017-12-07 16:46:04 +0000160 public:
Primiano Tucci9ba1d842018-12-20 17:31:04 +0100161 ConsumerEndpointImpl(TracingServiceImpl*,
162 base::TaskRunner*,
163 Consumer*,
164 uid_t uid);
Primiano Tucci42e2de12017-12-07 16:46:04 +0000165 ~ConsumerEndpointImpl() override;
166
Primiano Tuccidca727d2018-04-04 11:31:55 +0200167 void NotifyOnTracingDisabled();
Primiano Tucci42e2de12017-12-07 16:46:04 +0000168 base::WeakPtr<ConsumerEndpointImpl> GetWeakPtr();
169
Florian Mayer6a1a4d52018-06-08 16:47:07 +0100170 // TracingService::ConsumerEndpoint implementation.
Primiano Tucci2ffd1a52018-03-27 01:01:30 +0100171 void EnableTracing(const TraceConfig&, base::ScopedFile) override;
Oystein Eftevaagcb6e4c82019-03-06 15:38:26 -0800172 void ChangeTraceConfig(const TraceConfig& cfg) override;
Primiano Tucci674076d2018-10-01 10:41:09 +0100173 void StartTracing() override;
Primiano Tucci42e2de12017-12-07 16:46:04 +0000174 void DisableTracing() override;
175 void ReadBuffers() override;
176 void FreeBuffers() override;
Primiano Tucci3cbb10a2018-04-10 17:52:40 +0100177 void Flush(uint32_t timeout_ms, FlushCallback) override;
Primiano Tucci9ba1d842018-12-20 17:31:04 +0100178 void Detach(const std::string& key) override;
179 void Attach(const std::string& key) override;
Eric Secklereaf29ed2019-01-23 09:53:55 +0000180 void GetTraceStats() override;
Eric Seckler7b0c9452019-03-18 13:14:36 +0000181 void ObserveEvents(uint32_t enabled_event_types) override;
Primiano Tucci42e2de12017-12-07 16:46:04 +0000182
Eric Seckler7b0c9452019-03-18 13:14:36 +0000183 // If |observe_data_source_instances == true|, will queue a task to notify
184 // the consumer about the state change.
Eric Seckler4ff03e52019-03-15 10:10:30 +0000185 void OnDataSourceInstanceStateChange(const ProducerEndpointImpl&,
Eric Seckler7b0c9452019-03-18 13:14:36 +0000186 const DataSourceInstance&);
Eric Seckler4ff03e52019-03-15 10:10:30 +0000187
Primiano Tucci42e2de12017-12-07 16:46:04 +0000188 private:
Florian Mayer6a1a4d52018-06-08 16:47:07 +0100189 friend class TracingServiceImpl;
Primiano Tucci42e2de12017-12-07 16:46:04 +0000190 ConsumerEndpointImpl(const ConsumerEndpointImpl&) = delete;
191 ConsumerEndpointImpl& operator=(const ConsumerEndpointImpl&) = delete;
192
Eric Seckler7b0c9452019-03-18 13:14:36 +0000193 // Returns a pointer to an ObservableEvents object that the caller can fill
194 // and schedules a task to send the ObservableEvents to the consumer.
195 ObservableEvents* AddObservableEvents();
196
Primiano Tucci2ffd1a52018-03-27 01:01:30 +0100197 base::TaskRunner* const task_runner_;
Florian Mayer6a1a4d52018-06-08 16:47:07 +0100198 TracingServiceImpl* const service_;
Primiano Tucci42e2de12017-12-07 16:46:04 +0000199 Consumer* const consumer_;
Primiano Tucci9ba1d842018-12-20 17:31:04 +0100200 uid_t const uid_;
Primiano Tucci20d441d2018-01-16 09:25:51 +0000201 TracingSessionID tracing_session_id_ = 0;
Eric Seckler7b0c9452019-03-18 13:14:36 +0000202
203 // Whether the consumer is interested in DataSourceInstance state change
204 // events.
205 uint32_t enabled_observable_event_types_ = ObservableEventType::kNone;
206 // ObservableEvents that will be sent to the consumer. If set, a task to
207 // flush the events to the consumer has been queued.
208 std::unique_ptr<ObservableEvents> observable_events_;
209
Florian Mayercd08ec62018-01-31 17:49:25 +0000210 PERFETTO_THREAD_CHECKER(thread_checker_)
Primiano Tuccidca727d2018-04-04 11:31:55 +0200211 base::WeakPtrFactory<ConsumerEndpointImpl> weak_ptr_factory_; // Keep last.
Primiano Tucci42e2de12017-12-07 16:46:04 +0000212 };
213
Florian Mayer6a1a4d52018-06-08 16:47:07 +0100214 explicit TracingServiceImpl(std::unique_ptr<SharedMemory::Factory>,
215 base::TaskRunner*);
216 ~TracingServiceImpl() override;
Primiano Tucci4f9b6d72017-12-05 20:59:16 +0000217
Primiano Tucci42e2de12017-12-07 16:46:04 +0000218 // Called by ProducerEndpointImpl.
Primiano Tucci4f9b6d72017-12-05 20:59:16 +0000219 void DisconnectProducer(ProducerID);
Primiano Tucci9daa4832018-03-28 23:28:17 +0100220 void RegisterDataSource(ProducerID, const DataSourceDescriptor&);
221 void UnregisterDataSource(ProducerID, const std::string& name);
Primiano Tucci53589332017-12-19 11:31:13 +0100222 void CopyProducerPageIntoLogBuffer(ProducerID,
Primiano Tucciecf9e4a2018-03-14 14:51:58 +0000223 uid_t,
224 WriterID,
225 ChunkID,
Primiano Tucci53589332017-12-19 11:31:13 +0100226 BufferID,
Primiano Tucciecf9e4a2018-03-14 14:51:58 +0000227 uint16_t num_fragments,
228 uint8_t chunk_flags,
Eric Secklerb77b27e2018-12-17 11:42:52 +0000229 bool chunk_complete,
Primiano Tucciecf9e4a2018-03-14 14:51:58 +0000230 const uint8_t* src,
231 size_t size);
232 void ApplyChunkPatches(ProducerID,
233 const std::vector<CommitDataRequest::ChunkToPatch>&);
Primiano Tuccid52e6272018-04-06 19:06:53 +0200234 void NotifyFlushDoneForProducer(ProducerID, FlushRequestID);
Eric Seckler4ff03e52019-03-15 10:10:30 +0000235 void NotifyDataSourceStarted(ProducerID, const DataSourceInstanceID);
Primiano Tuccibaeecf12018-07-25 12:02:20 +0100236 void NotifyDataSourceStopped(ProducerID, const DataSourceInstanceID);
Stephen Nusko59847292019-03-22 13:54:08 +0000237 void ActivateTriggers(ProducerID, const std::vector<std::string>& triggers);
Primiano Tucci4f9b6d72017-12-05 20:59:16 +0000238
Primiano Tucci42e2de12017-12-07 16:46:04 +0000239 // Called by ConsumerEndpointImpl.
Primiano Tucci9ba1d842018-12-20 17:31:04 +0100240 bool DetachConsumer(ConsumerEndpointImpl*, const std::string& key);
241 bool AttachConsumer(ConsumerEndpointImpl*, const std::string& key);
Primiano Tucci42e2de12017-12-07 16:46:04 +0000242 void DisconnectConsumer(ConsumerEndpointImpl*);
Primiano Tucci2ffd1a52018-03-27 01:01:30 +0100243 bool EnableTracing(ConsumerEndpointImpl*,
244 const TraceConfig&,
245 base::ScopedFile);
Oystein Eftevaagcb6e4c82019-03-06 15:38:26 -0800246 void ChangeTraceConfig(ConsumerEndpointImpl*, const TraceConfig&);
247
Primiano Tucci674076d2018-10-01 10:41:09 +0100248 bool StartTracing(TracingSessionID);
Primiano Tuccibaeecf12018-07-25 12:02:20 +0100249 void DisableTracing(TracingSessionID, bool disable_immediately = false);
Primiano Tuccid52e6272018-04-06 19:06:53 +0200250 void Flush(TracingSessionID tsid,
Primiano Tucci3cbb10a2018-04-10 17:52:40 +0100251 uint32_t timeout_ms,
Primiano Tuccid52e6272018-04-06 19:06:53 +0200252 ConsumerEndpoint::FlushCallback);
253 void FlushAndDisableTracing(TracingSessionID);
Primiano Tucci20d441d2018-01-16 09:25:51 +0000254 void ReadBuffers(TracingSessionID, ConsumerEndpointImpl*);
255 void FreeBuffers(TracingSessionID);
Primiano Tucci42e2de12017-12-07 16:46:04 +0000256
Primiano Tucci4f9b6d72017-12-05 20:59:16 +0000257 // Service implementation.
Florian Mayer6a1a4d52018-06-08 16:47:07 +0100258 std::unique_ptr<TracingService::ProducerEndpoint> ConnectProducer(
Primiano Tucci4f9b6d72017-12-05 20:59:16 +0000259 Producer*,
Sami Kyostila32e0b542018-02-14 08:55:43 +0000260 uid_t uid,
Isabelle Taylor86262cb2018-03-27 16:00:54 +0100261 const std::string& producer_name,
Oystein Eftevaagc8d2f072019-03-29 09:41:04 -0700262 size_t shared_memory_size_hint_bytes = 0,
263 bool in_process = false) override;
Primiano Tucci42e2de12017-12-07 16:46:04 +0000264
Florian Mayer6a1a4d52018-06-08 16:47:07 +0100265 std::unique_ptr<TracingService::ConsumerEndpoint> ConnectConsumer(
Primiano Tucci9ba1d842018-12-20 17:31:04 +0100266 Consumer*,
267 uid_t) override;
Primiano Tucci42e2de12017-12-07 16:46:04 +0000268
Eric Secklera01e28a2019-01-08 11:21:04 +0000269 void SetSMBScrapingEnabled(bool enabled) override {
270 smb_scraping_enabled_ = enabled;
271 }
272
Primiano Tucci4f9b6d72017-12-05 20:59:16 +0000273 // Exposed mainly for testing.
274 size_t num_producers() const { return producers_.size(); }
275 ProducerEndpointImpl* GetProducer(ProducerID) const;
276
Primiano Tuccibaeecf12018-07-25 12:02:20 +0100277 uint32_t override_data_source_test_timeout_ms_for_testing = 0;
278
Primiano Tucci4f9b6d72017-12-05 20:59:16 +0000279 private:
Florian Mayer6a1a4d52018-06-08 16:47:07 +0100280 friend class TracingServiceImplTest;
Primiano Tucci081d46a2018-02-28 11:09:43 +0000281
Primiano Tucci53589332017-12-19 11:31:13 +0100282 struct RegisteredDataSource {
283 ProducerID producer_id;
Primiano Tucci53589332017-12-19 11:31:13 +0100284 DataSourceDescriptor descriptor;
285 };
286
Sami Kyostila06487a22018-02-27 13:48:38 +0000287 // Represents an active data source for a tracing session.
288 struct DataSourceInstance {
Primiano Tucci5403e4f2018-11-27 10:07:03 +0000289 DataSourceInstance(DataSourceInstanceID id,
290 const DataSourceConfig& cfg,
291 const std::string& ds_name,
Eric Seckler4ff03e52019-03-15 10:10:30 +0000292 bool notify_on_start,
Ryan Savitski33868d52019-05-13 10:56:14 +0100293 bool notify_on_stop,
294 bool handles_incremental_state_invalidation)
Primiano Tucci5403e4f2018-11-27 10:07:03 +0000295 : instance_id(id),
296 config(cfg),
297 data_source_name(ds_name),
Eric Seckler4ff03e52019-03-15 10:10:30 +0000298 will_notify_on_start(notify_on_start),
Ryan Savitski33868d52019-05-13 10:56:14 +0100299 will_notify_on_stop(notify_on_stop),
300 handles_incremental_state_clear(
301 handles_incremental_state_invalidation) {}
Primiano Tucci674076d2018-10-01 10:41:09 +0100302 DataSourceInstance(const DataSourceInstance&) = delete;
303 DataSourceInstance& operator=(const DataSourceInstance&) = delete;
Primiano Tucci674076d2018-10-01 10:41:09 +0100304
Sami Kyostila06487a22018-02-27 13:48:38 +0000305 DataSourceInstanceID instance_id;
Primiano Tucci674076d2018-10-01 10:41:09 +0100306 DataSourceConfig config;
Primiano Tucci9daa4832018-03-28 23:28:17 +0100307 std::string data_source_name;
Eric Seckler4ff03e52019-03-15 10:10:30 +0000308 bool will_notify_on_start;
Primiano Tuccibaeecf12018-07-25 12:02:20 +0100309 bool will_notify_on_stop;
Ryan Savitski33868d52019-05-13 10:56:14 +0100310 bool handles_incremental_state_clear;
Eric Seckler4ff03e52019-03-15 10:10:30 +0000311
312 enum DataSourceInstanceState {
313 CONFIGURED,
314 STARTING,
315 STARTED,
316 STOPPING,
317 STOPPED
318 };
319 DataSourceInstanceState state = CONFIGURED;
Sami Kyostila06487a22018-02-27 13:48:38 +0000320 };
321
Primiano Tuccid52e6272018-04-06 19:06:53 +0200322 struct PendingFlush {
323 std::set<ProducerID> producers;
324 ConsumerEndpoint::FlushCallback callback;
325 explicit PendingFlush(decltype(callback) cb) : callback(std::move(cb)) {}
326 };
327
Primiano Tucci53589332017-12-19 11:31:13 +0100328 // Holds the state of a tracing session. A tracing session is uniquely bound
329 // a specific Consumer. Each Consumer can own one or more sessions.
330 struct TracingSession {
Primiano Tucci674076d2018-10-01 10:41:09 +0100331 enum State {
332 DISABLED = 0,
333 CONFIGURED,
334 STARTED,
335 DISABLING_WAITING_STOP_ACKS
336 };
Primiano Tuccibaeecf12018-07-25 12:02:20 +0100337
338 TracingSession(TracingSessionID, ConsumerEndpointImpl*, const TraceConfig&);
Primiano Tucci20d441d2018-01-16 09:25:51 +0000339
340 size_t num_buffers() const { return buffers_index.size(); }
341
Primiano Tucci3cbb10a2018-04-10 17:52:40 +0100342 uint32_t delay_to_next_write_period_ms() const {
Sami Kyostila01c45f02018-03-29 15:43:10 +0100343 PERFETTO_DCHECK(write_period_ms > 0);
344 return write_period_ms -
345 (base::GetWallTimeMs().count() % write_period_ms);
Primiano Tucci2ffd1a52018-03-27 01:01:30 +0100346 }
347
Florian Mayere563f662019-01-09 11:04:50 +0000348 uint32_t flush_timeout_ms() {
349 uint32_t timeout_ms = config.flush_timeout_ms();
350 return timeout_ms ? timeout_ms : kDefaultFlushTimeoutMs;
351 }
352
Eric Secklerd0ac7ca2019-02-06 09:13:45 +0000353 PacketSequenceID GetPacketSequenceID(ProducerID producer_id,
354 WriterID writer_id) {
355 auto key = std::make_pair(producer_id, writer_id);
356 auto it = packet_sequence_ids.find(key);
357 if (it != packet_sequence_ids.end())
358 return it->second;
359 // We shouldn't run out of sequence IDs (producer ID is 16 bit, writer IDs
360 // are limited to 1024).
361 static_assert(kMaxPacketSequenceID > kMaxProducerID * kMaxWriterID,
362 "PacketSequenceID value space doesn't cover service "
363 "sequence ID and all producer/writer ID combinations!");
364 PERFETTO_DCHECK(last_packet_sequence_id < kMaxPacketSequenceID);
365 PacketSequenceID sequence_id = ++last_packet_sequence_id;
366 packet_sequence_ids[key] = sequence_id;
367 return sequence_id;
368 }
369
Eric Seckler4ff03e52019-03-15 10:10:30 +0000370 DataSourceInstance* GetDataSourceInstance(
371 ProducerID producer_id,
372 DataSourceInstanceID instance_id) {
373 for (auto& inst_kv : data_source_instances) {
374 if (inst_kv.first != producer_id ||
375 inst_kv.second.instance_id != instance_id) {
376 continue;
377 }
378 return &inst_kv.second;
379 }
380 return nullptr;
381 }
382
383 bool AllDataSourceInstancesStopped() {
384 for (const auto& inst_kv : data_source_instances) {
385 if (inst_kv.second.state != DataSourceInstance::STOPPED)
386 return false;
387 }
388 return true;
389 }
390
Primiano Tuccibaeecf12018-07-25 12:02:20 +0100391 const TracingSessionID id;
392
Primiano Tucci2ffd1a52018-03-27 01:01:30 +0100393 // The consumer that started the session.
Primiano Tucci9ba1d842018-12-20 17:31:04 +0100394 // Can be nullptr if the consumer detached from the session.
395 ConsumerEndpointImpl* consumer_maybe_null;
396
397 // Unix uid of the consumer. This is valid even after the consumer detaches
398 // and does not change for the entire duration of the session. It is used to
399 // prevent that a consumer re-attaches to a session from a different uid.
400 uid_t const consumer_uid;
Primiano Tucci2ffd1a52018-03-27 01:01:30 +0100401
Stephen Nusko59847292019-03-22 13:54:08 +0000402 // The list of triggers this session received while alive and the time they
403 // were received at. This is used to insert 'fake' packets back to the
404 // consumer so they can tell when some event happened. The order matches the
405 // order they were received.
Stephen Nusko70ea3302019-04-01 19:44:40 +0100406 struct TriggerInfo {
407 uint64_t boot_time_ns;
408 std::string trigger_name;
409 std::string producer_name;
410 uid_t producer_uid;
411 };
412 std::vector<TriggerInfo> received_triggers;
Stephen Nusko59847292019-03-22 13:54:08 +0000413
Oystein Eftevaagcb6e4c82019-03-06 15:38:26 -0800414 // The trace config provided by the Consumer when calling
415 // EnableTracing(), plus any updates performed by ChangeTraceConfig.
416 TraceConfig config;
Oystein Eftevaag1269b4a2018-01-10 16:29:38 -0800417
Primiano Tucci53589332017-12-19 11:31:13 +0100418 // List of data source instances that have been enabled on the various
419 // producers for this tracing session.
Ryan Savitski33868d52019-05-13 10:56:14 +0100420 // TODO(rsavitski): at the time of writing, the map structure is unused
421 // (even when the calling code has a key). This is also an opportunity to
422 // consider an alternative data type, e.g. a map of vectors.
Sami Kyostila06487a22018-02-27 13:48:38 +0000423 std::multimap<ProducerID, DataSourceInstance> data_source_instances;
Primiano Tucci53589332017-12-19 11:31:13 +0100424
Primiano Tuccid52e6272018-04-06 19:06:53 +0200425 // For each Flush(N) request, keeps track of the set of producers for which
426 // we are still awaiting a NotifyFlushComplete(N) ack.
427 std::map<FlushRequestID, PendingFlush> pending_flushes;
428
Primiano Tucci20d441d2018-01-16 09:25:51 +0000429 // Maps a per-trace-session buffer index into the corresponding global
430 // BufferID (shared namespace amongst all consumers). This vector has as
431 // many entries as |config.buffers_size()|.
432 std::vector<BufferID> buffers_index;
Sami Kyostilafbccb3c2018-03-21 14:00:47 +0000433
Eric Secklerd0ac7ca2019-02-06 09:13:45 +0000434 std::map<std::pair<ProducerID, WriterID>, PacketSequenceID>
435 packet_sequence_ids;
436 PacketSequenceID last_packet_sequence_id = kServicePacketSequenceID;
437
Primiano Tucci9754d0d2018-09-15 12:41:46 +0100438 // When the last snapshots (clock, stats, sync marker) were emitted into
439 // the output stream.
440 base::TimeMillis last_snapshot_time = {};
Primiano Tucci5e33cad2018-04-30 14:41:25 +0100441
Sami Kyostila200bd2e2018-03-26 12:24:10 +0100442 // Whether we mirrored the trace config back to the trace output yet.
443 bool did_emit_config = false;
Primiano Tucci2ffd1a52018-03-27 01:01:30 +0100444
Hector Dearman685f7522019-03-12 14:28:56 +0000445 // Whether we put the system info into the trace output yet.
446 bool did_emit_system_info = false;
447
Stephen Nusko70ea3302019-04-01 19:44:40 +0100448 // The number of received triggers we've emitted into the trace output.
449 size_t num_triggers_emitted_into_trace = 0;
450
Primiano Tuccibaeecf12018-07-25 12:02:20 +0100451 State state = DISABLED;
Primiano Tucci2ffd1a52018-03-27 01:01:30 +0100452
Primiano Tucci9ba1d842018-12-20 17:31:04 +0100453 // If the consumer detached the session, this variable defines the key used
454 // for identifying the session later when reattaching.
455 std::string detach_key;
456
Primiano Tucci2ffd1a52018-03-27 01:01:30 +0100457 // This is set when the Consumer calls sets |write_into_file| == true in the
458 // TraceConfig. In this case this represents the file we should stream the
459 // trace packets into, rather than returning it to the consumer via
460 // OnTraceData().
461 base::ScopedFile write_into_file;
Primiano Tucci3cbb10a2018-04-10 17:52:40 +0100462 uint32_t write_period_ms = 0;
463 uint64_t max_file_size_bytes = 0;
464 uint64_t bytes_written_into_file = 0;
Primiano Tucci53589332017-12-19 11:31:13 +0100465 };
466
Florian Mayer6a1a4d52018-06-08 16:47:07 +0100467 TracingServiceImpl(const TracingServiceImpl&) = delete;
468 TracingServiceImpl& operator=(const TracingServiceImpl&) = delete;
Primiano Tucci20d441d2018-01-16 09:25:51 +0000469
Primiano Tucci674076d2018-10-01 10:41:09 +0100470 DataSourceInstance* SetupDataSource(const TraceConfig::DataSource&,
471 const TraceConfig::ProducerConfig&,
472 const RegisteredDataSource&,
473 TracingSession*);
Oystein Eftevaag1269b4a2018-01-10 16:29:38 -0800474
Primiano Tucci081d46a2018-02-28 11:09:43 +0000475 // Returns the next available ProducerID that is not in |producers_|.
476 ProducerID GetNextProducerID();
477
Primiano Tucci20d441d2018-01-16 09:25:51 +0000478 // Returns a pointer to the |tracing_sessions_| entry or nullptr if the
479 // session doesn't exists.
480 TracingSession* GetTracingSession(TracingSessionID);
Primiano Tucci4f9b6d72017-12-05 20:59:16 +0000481
Primiano Tucci9ba1d842018-12-20 17:31:04 +0100482 // Returns a pointer to the |tracing_sessions_| entry, matching the given
483 // uid and detach key, or nullptr if no such session exists.
484 TracingSession* GetDetachedSession(uid_t, const std::string& key);
485
Lalit Maganti485faff2018-03-06 11:51:35 +0000486 // Update the memory guard rail by using the latest information from the
487 // shared memory and trace buffers.
488 void UpdateMemoryGuardrail();
489
Eric Seckler4ff03e52019-03-15 10:10:30 +0000490 void StartDataSourceInstance(ProducerEndpointImpl* producer,
491 TracingSession* tracing_session,
492 DataSourceInstance* instance);
Primiano Tucci9754d0d2018-09-15 12:41:46 +0100493 void SnapshotSyncMarker(std::vector<TracePacket>*);
494 void SnapshotClocks(std::vector<TracePacket>*);
495 void SnapshotStats(TracingSession*, std::vector<TracePacket>*);
Eric Secklereaf29ed2019-01-23 09:53:55 +0000496 TraceStats GetTraceStats(TracingSession* tracing_session);
Sami Kyostila200bd2e2018-03-26 12:24:10 +0100497 void MaybeEmitTraceConfig(TracingSession*, std::vector<TracePacket>*);
Hector Dearman685f7522019-03-12 14:28:56 +0000498 void MaybeEmitSystemInfo(TracingSession*, std::vector<TracePacket>*);
Stephen Nusko70ea3302019-04-01 19:44:40 +0100499 void MaybeEmitReceivedTriggers(TracingSession*, std::vector<TracePacket>*);
Primiano Tuccid52e6272018-04-06 19:06:53 +0200500 void OnFlushTimeout(TracingSessionID, FlushRequestID);
Primiano Tuccibaeecf12018-07-25 12:02:20 +0100501 void OnDisableTracingTimeout(TracingSessionID);
502 void DisableTracingNotifyConsumerAndFlushFile(TracingSession*);
Primiano Tuccicaa57802018-11-25 11:07:07 +0000503 void PeriodicFlushTask(TracingSessionID, bool post_next_only);
Eric Secklera01e28a2019-01-08 11:21:04 +0000504 void CompleteFlush(TracingSessionID tsid,
505 ConsumerEndpoint::FlushCallback callback,
506 bool success);
507 void ScrapeSharedMemoryBuffers(TracingSession* tracing_session,
508 ProducerEndpointImpl* producer);
Ryan Savitski33868d52019-05-13 10:56:14 +0100509 void PeriodicClearIncrementalStateTask(TracingSessionID, bool post_next_only);
Hector Dearman6214c8f2018-03-27 16:16:22 +0100510 TraceBuffer* GetBufferByID(BufferID);
Stephen Nusko59847292019-03-22 13:54:08 +0000511 void OnStartTriggersTimeout(TracingSessionID tsid);
Primiano Tucciecf9e4a2018-03-14 14:51:58 +0000512
Primiano Tucci4f9b6d72017-12-05 20:59:16 +0000513 base::TaskRunner* const task_runner_;
Primiano Tucci53589332017-12-19 11:31:13 +0100514 std::unique_ptr<SharedMemory::Factory> shm_factory_;
Primiano Tucci4f9b6d72017-12-05 20:59:16 +0000515 ProducerID last_producer_id_ = 0;
Primiano Tucci53589332017-12-19 11:31:13 +0100516 DataSourceInstanceID last_data_source_instance_id_ = 0;
Primiano Tucci20d441d2018-01-16 09:25:51 +0000517 TracingSessionID last_tracing_session_id_ = 0;
Primiano Tuccid52e6272018-04-06 19:06:53 +0200518 FlushRequestID last_flush_request_id_ = 0;
Primiano Tucci5e33cad2018-04-30 14:41:25 +0100519 uid_t uid_ = 0;
Primiano Tucci53589332017-12-19 11:31:13 +0100520
521 // Buffer IDs are global across all consumers (because a Producer can produce
522 // data for more than one trace session, hence more than one consumer).
Primiano Tucci20d441d2018-01-16 09:25:51 +0000523 IdAllocator<BufferID> buffer_ids_;
Primiano Tucci53589332017-12-19 11:31:13 +0100524
525 std::multimap<std::string /*name*/, RegisteredDataSource> data_sources_;
Primiano Tucci4f9b6d72017-12-05 20:59:16 +0000526 std::map<ProducerID, ProducerEndpointImpl*> producers_;
Primiano Tucci42e2de12017-12-07 16:46:04 +0000527 std::set<ConsumerEndpointImpl*> consumers_;
Primiano Tucci20d441d2018-01-16 09:25:51 +0000528 std::map<TracingSessionID, TracingSession> tracing_sessions_;
Hector Dearman6214c8f2018-03-27 16:16:22 +0100529 std::map<BufferID, std::unique_ptr<TraceBuffer>> buffers_;
Primiano Tucci20d441d2018-01-16 09:25:51 +0000530
Eric Secklera01e28a2019-01-08 11:21:04 +0000531 bool smb_scraping_enabled_ = false;
Florian Mayer61c55482018-03-06 14:43:54 +0000532 bool lockdown_mode_ = false;
Primiano Tucci9754d0d2018-09-15 12:41:46 +0100533 uint32_t min_write_period_ms_ = 100; // Overridable for testing.
534
535 uint8_t sync_marker_packet_[32]; // Lazily initialized.
536 size_t sync_marker_packet_size_ = 0;
Florian Mayer61c55482018-03-06 14:43:54 +0000537
Eric Seckler2c72bd82019-02-08 15:01:34 +0000538 // Stats.
539 uint64_t chunks_discarded_ = 0;
540 uint64_t patches_discarded_ = 0;
541
Florian Mayercd08ec62018-01-31 17:49:25 +0000542 PERFETTO_THREAD_CHECKER(thread_checker_)
543
Florian Mayer6a1a4d52018-06-08 16:47:07 +0100544 base::WeakPtrFactory<TracingServiceImpl>
545 weak_ptr_factory_; // Keep at the end.
Primiano Tucci4f9b6d72017-12-05 20:59:16 +0000546};
547
548} // namespace perfetto
549
Florian Mayer6a1a4d52018-06-08 16:47:07 +0100550#endif // SRC_TRACING_CORE_TRACING_SERVICE_IMPL_H_