blob: 3d734cd2dc05f9a404fac5ea1595f1208617865e [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
Primiano Tucci2ffd1a52018-03-27 01:01:30 +010027#include "perfetto/base/logging.h"
Primiano Tucci2c5488f2019-06-01 03:27:28 +010028#include "perfetto/ext/base/optional.h"
29#include "perfetto/ext/base/time.h"
30#include "perfetto/ext/base/weak_ptr.h"
31#include "perfetto/ext/tracing/core/basic_types.h"
32#include "perfetto/ext/tracing/core/commit_data_request.h"
33#include "perfetto/ext/tracing/core/data_source_descriptor.h"
34#include "perfetto/ext/tracing/core/observable_events.h"
35#include "perfetto/ext/tracing/core/shared_memory_abi.h"
36#include "perfetto/ext/tracing/core/trace_config.h"
37#include "perfetto/ext/tracing/core/trace_stats.h"
38#include "perfetto/ext/tracing/core/tracing_service.h"
Primiano Tucci53589332017-12-19 11:31:13 +010039#include "src/tracing/core/id_allocator.h"
Primiano Tucci4f9b6d72017-12-05 20:59:16 +000040
41namespace perfetto {
42
43namespace base {
44class TaskRunner;
45} // namespace base
46
Primiano Tucci42e2de12017-12-07 16:46:04 +000047class Consumer;
Primiano Tucci4f9b6d72017-12-05 20:59:16 +000048class DataSourceConfig;
49class Producer;
50class SharedMemory;
Primiano Tucci2ffd1a52018-03-27 01:01:30 +010051class SharedMemoryArbiterImpl;
Hector Dearman6214c8f2018-03-27 16:16:22 +010052class TraceBuffer;
Primiano Tucci42e2de12017-12-07 16:46:04 +000053class TraceConfig;
Sami Kyostilafbccb3c2018-03-21 14:00:47 +000054class TracePacket;
Primiano Tucci4f9b6d72017-12-05 20:59:16 +000055
56// The tracing service business logic.
Florian Mayer6a1a4d52018-06-08 16:47:07 +010057class TracingServiceImpl : public TracingService {
Eric Seckler4ff03e52019-03-15 10:10:30 +000058 private:
59 struct DataSourceInstance;
60
Primiano Tucci4f9b6d72017-12-05 20:59:16 +000061 public:
Primiano Tucci1a1951d2018-04-04 21:08:16 +020062 static constexpr size_t kDefaultShmSize = 256 * 1024ul;
Primiano Tuccie7ca7c62018-04-07 08:28:03 +020063 static constexpr size_t kMaxShmSize = 32 * 1024 * 1024ul;
Primiano Tuccibaeecf12018-07-25 12:02:20 +010064 static constexpr uint32_t kDataSourceStopTimeoutMs = 5000;
Primiano Tucci9754d0d2018-09-15 12:41:46 +010065 static constexpr uint8_t kSyncMarker[] = {0x82, 0x47, 0x7a, 0x76, 0xb2, 0x8d,
66 0x42, 0xba, 0x81, 0xdc, 0x33, 0x32,
67 0x6d, 0x57, 0xa0, 0x79};
Primiano Tucci1a1951d2018-04-04 21:08:16 +020068
Primiano Tucci4f9b6d72017-12-05 20:59:16 +000069 // The implementation behind the service endpoint exposed to each producer.
Florian Mayer6a1a4d52018-06-08 16:47:07 +010070 class ProducerEndpointImpl : public TracingService::ProducerEndpoint {
Primiano Tucci4f9b6d72017-12-05 20:59:16 +000071 public:
72 ProducerEndpointImpl(ProducerID,
Sami Kyostila32e0b542018-02-14 08:55:43 +000073 uid_t uid,
Florian Mayer6a1a4d52018-06-08 16:47:07 +010074 TracingServiceImpl*,
Primiano Tucci4f9b6d72017-12-05 20:59:16 +000075 base::TaskRunner*,
Isabelle Taylor86262cb2018-03-27 16:00:54 +010076 Producer*,
Oystein Eftevaagc8d2f072019-03-29 09:41:04 -070077 const std::string& producer_name,
Eric Seckler062ed502019-05-23 09:02:57 +010078 bool in_process,
79 bool smb_scraping_enabled);
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;
Eric Seckler062ed502019-05-23 09:02:57 +0100121 friend class TracingIntegrationTest;
Primiano Tucci4f9b6d72017-12-05 20:59:16 +0000122 ProducerEndpointImpl(const ProducerEndpointImpl&) = delete;
123 ProducerEndpointImpl& operator=(const ProducerEndpointImpl&) = delete;
124
125 ProducerID const id_;
Sami Kyostila32e0b542018-02-14 08:55:43 +0000126 const uid_t uid_;
Florian Mayer6a1a4d52018-06-08 16:47:07 +0100127 TracingServiceImpl* const service_;
Primiano Tucci4f9b6d72017-12-05 20:59:16 +0000128 base::TaskRunner* const task_runner_;
129 Producer* producer_;
130 std::unique_ptr<SharedMemory> shared_memory_;
Isabelle Taylor69faa902018-03-21 15:42:03 +0000131 size_t shared_buffer_page_size_kb_ = 0;
Primiano Tucci53589332017-12-19 11:31:13 +0100132 SharedMemoryABI shmem_abi_;
Primiano Tucci1a1951d2018-04-04 21:08:16 +0200133 size_t shmem_size_hint_bytes_ = 0;
Isabelle Taylor86262cb2018-03-27 16:00:54 +0100134 const std::string name_;
Oystein Eftevaagc8d2f072019-03-29 09:41:04 -0700135 bool in_process_;
Eric Seckler062ed502019-05-23 09:02:57 +0100136 bool smb_scraping_enabled_;
Primiano Tucci2ffd1a52018-03-27 01:01:30 +0100137
Eric Seckler6dc23592018-11-30 10:59:06 +0000138 // Set of the global target_buffer IDs that the producer is configured to
139 // write into in any active tracing session.
140 std::set<BufferID> allowed_target_buffers_;
141
Eric Secklerf3f524b2018-12-13 09:09:34 +0000142 // Maps registered TraceWriter IDs to their target buffers as registered by
143 // the producer. Note that producers aren't required to register their
144 // writers, so we may see commits of chunks with WriterIDs that aren't
145 // contained in this map. However, if a producer does register a writer, the
146 // service will prevent the writer from writing into any other buffer than
147 // the one associated with it here. The BufferIDs stored in this map are
148 // untrusted, so need to be verified against |allowed_target_buffers_|
149 // before use.
150 std::map<WriterID, BufferID> writers_;
151
Oystein Eftevaagc8d2f072019-03-29 09:41:04 -0700152 // This is used only in in-process configurations.
Primiano Tucci14219ff2019-02-27 12:41:05 +0100153 // SharedMemoryArbiterImpl methods themselves are thread-safe.
Primiano Tucci2ffd1a52018-03-27 01:01:30 +0100154 std::unique_ptr<SharedMemoryArbiterImpl> inproc_shmem_arbiter_;
Primiano Tucci14219ff2019-02-27 12:41:05 +0100155
Florian Mayercd08ec62018-01-31 17:49:25 +0000156 PERFETTO_THREAD_CHECKER(thread_checker_)
Primiano Tuccidca727d2018-04-04 11:31:55 +0200157 base::WeakPtrFactory<ProducerEndpointImpl> weak_ptr_factory_; // Keep last.
Primiano Tucci4f9b6d72017-12-05 20:59:16 +0000158 };
159
Primiano Tucci42e2de12017-12-07 16:46:04 +0000160 // The implementation behind the service endpoint exposed to each consumer.
Florian Mayer6a1a4d52018-06-08 16:47:07 +0100161 class ConsumerEndpointImpl : public TracingService::ConsumerEndpoint {
Primiano Tucci42e2de12017-12-07 16:46:04 +0000162 public:
Primiano Tucci9ba1d842018-12-20 17:31:04 +0100163 ConsumerEndpointImpl(TracingServiceImpl*,
164 base::TaskRunner*,
165 Consumer*,
166 uid_t uid);
Primiano Tucci42e2de12017-12-07 16:46:04 +0000167 ~ConsumerEndpointImpl() override;
168
Primiano Tuccidca727d2018-04-04 11:31:55 +0200169 void NotifyOnTracingDisabled();
Primiano Tucci42e2de12017-12-07 16:46:04 +0000170 base::WeakPtr<ConsumerEndpointImpl> GetWeakPtr();
171
Florian Mayer6a1a4d52018-06-08 16:47:07 +0100172 // TracingService::ConsumerEndpoint implementation.
Primiano Tucci2ffd1a52018-03-27 01:01:30 +0100173 void EnableTracing(const TraceConfig&, base::ScopedFile) override;
Oystein Eftevaagcb6e4c82019-03-06 15:38:26 -0800174 void ChangeTraceConfig(const TraceConfig& cfg) override;
Primiano Tucci674076d2018-10-01 10:41:09 +0100175 void StartTracing() override;
Primiano Tucci42e2de12017-12-07 16:46:04 +0000176 void DisableTracing() override;
177 void ReadBuffers() override;
178 void FreeBuffers() override;
Primiano Tucci3cbb10a2018-04-10 17:52:40 +0100179 void Flush(uint32_t timeout_ms, FlushCallback) override;
Primiano Tucci9ba1d842018-12-20 17:31:04 +0100180 void Detach(const std::string& key) override;
181 void Attach(const std::string& key) override;
Eric Secklereaf29ed2019-01-23 09:53:55 +0000182 void GetTraceStats() override;
Eric Seckler7b0c9452019-03-18 13:14:36 +0000183 void ObserveEvents(uint32_t enabled_event_types) override;
Primiano Tucci42e2de12017-12-07 16:46:04 +0000184
Eric Seckler7b0c9452019-03-18 13:14:36 +0000185 // If |observe_data_source_instances == true|, will queue a task to notify
186 // the consumer about the state change.
Eric Seckler4ff03e52019-03-15 10:10:30 +0000187 void OnDataSourceInstanceStateChange(const ProducerEndpointImpl&,
Eric Seckler7b0c9452019-03-18 13:14:36 +0000188 const DataSourceInstance&);
Eric Seckler4ff03e52019-03-15 10:10:30 +0000189
Primiano Tucci42e2de12017-12-07 16:46:04 +0000190 private:
Florian Mayer6a1a4d52018-06-08 16:47:07 +0100191 friend class TracingServiceImpl;
Primiano Tucci42e2de12017-12-07 16:46:04 +0000192 ConsumerEndpointImpl(const ConsumerEndpointImpl&) = delete;
193 ConsumerEndpointImpl& operator=(const ConsumerEndpointImpl&) = delete;
194
Eric Seckler7b0c9452019-03-18 13:14:36 +0000195 // Returns a pointer to an ObservableEvents object that the caller can fill
196 // and schedules a task to send the ObservableEvents to the consumer.
197 ObservableEvents* AddObservableEvents();
198
Primiano Tucci2ffd1a52018-03-27 01:01:30 +0100199 base::TaskRunner* const task_runner_;
Florian Mayer6a1a4d52018-06-08 16:47:07 +0100200 TracingServiceImpl* const service_;
Primiano Tucci42e2de12017-12-07 16:46:04 +0000201 Consumer* const consumer_;
Primiano Tucci9ba1d842018-12-20 17:31:04 +0100202 uid_t const uid_;
Primiano Tucci20d441d2018-01-16 09:25:51 +0000203 TracingSessionID tracing_session_id_ = 0;
Eric Seckler7b0c9452019-03-18 13:14:36 +0000204
205 // Whether the consumer is interested in DataSourceInstance state change
206 // events.
207 uint32_t enabled_observable_event_types_ = ObservableEventType::kNone;
208 // ObservableEvents that will be sent to the consumer. If set, a task to
209 // flush the events to the consumer has been queued.
210 std::unique_ptr<ObservableEvents> observable_events_;
211
Florian Mayercd08ec62018-01-31 17:49:25 +0000212 PERFETTO_THREAD_CHECKER(thread_checker_)
Primiano Tuccidca727d2018-04-04 11:31:55 +0200213 base::WeakPtrFactory<ConsumerEndpointImpl> weak_ptr_factory_; // Keep last.
Primiano Tucci42e2de12017-12-07 16:46:04 +0000214 };
215
Florian Mayer6a1a4d52018-06-08 16:47:07 +0100216 explicit TracingServiceImpl(std::unique_ptr<SharedMemory::Factory>,
217 base::TaskRunner*);
218 ~TracingServiceImpl() override;
Primiano Tucci4f9b6d72017-12-05 20:59:16 +0000219
Primiano Tucci42e2de12017-12-07 16:46:04 +0000220 // Called by ProducerEndpointImpl.
Primiano Tucci4f9b6d72017-12-05 20:59:16 +0000221 void DisconnectProducer(ProducerID);
Primiano Tucci9daa4832018-03-28 23:28:17 +0100222 void RegisterDataSource(ProducerID, const DataSourceDescriptor&);
223 void UnregisterDataSource(ProducerID, const std::string& name);
Primiano Tucci53589332017-12-19 11:31:13 +0100224 void CopyProducerPageIntoLogBuffer(ProducerID,
Primiano Tucciecf9e4a2018-03-14 14:51:58 +0000225 uid_t,
226 WriterID,
227 ChunkID,
Primiano Tucci53589332017-12-19 11:31:13 +0100228 BufferID,
Primiano Tucciecf9e4a2018-03-14 14:51:58 +0000229 uint16_t num_fragments,
230 uint8_t chunk_flags,
Eric Secklerb77b27e2018-12-17 11:42:52 +0000231 bool chunk_complete,
Primiano Tucciecf9e4a2018-03-14 14:51:58 +0000232 const uint8_t* src,
233 size_t size);
234 void ApplyChunkPatches(ProducerID,
235 const std::vector<CommitDataRequest::ChunkToPatch>&);
Primiano Tuccid52e6272018-04-06 19:06:53 +0200236 void NotifyFlushDoneForProducer(ProducerID, FlushRequestID);
Eric Seckler4ff03e52019-03-15 10:10:30 +0000237 void NotifyDataSourceStarted(ProducerID, const DataSourceInstanceID);
Primiano Tuccibaeecf12018-07-25 12:02:20 +0100238 void NotifyDataSourceStopped(ProducerID, const DataSourceInstanceID);
Stephen Nusko59847292019-03-22 13:54:08 +0000239 void ActivateTriggers(ProducerID, const std::vector<std::string>& triggers);
Primiano Tucci4f9b6d72017-12-05 20:59:16 +0000240
Primiano Tucci42e2de12017-12-07 16:46:04 +0000241 // Called by ConsumerEndpointImpl.
Primiano Tucci9ba1d842018-12-20 17:31:04 +0100242 bool DetachConsumer(ConsumerEndpointImpl*, const std::string& key);
243 bool AttachConsumer(ConsumerEndpointImpl*, const std::string& key);
Primiano Tucci42e2de12017-12-07 16:46:04 +0000244 void DisconnectConsumer(ConsumerEndpointImpl*);
Primiano Tucci2ffd1a52018-03-27 01:01:30 +0100245 bool EnableTracing(ConsumerEndpointImpl*,
246 const TraceConfig&,
247 base::ScopedFile);
Oystein Eftevaagcb6e4c82019-03-06 15:38:26 -0800248 void ChangeTraceConfig(ConsumerEndpointImpl*, const TraceConfig&);
249
Primiano Tucci674076d2018-10-01 10:41:09 +0100250 bool StartTracing(TracingSessionID);
Primiano Tuccibaeecf12018-07-25 12:02:20 +0100251 void DisableTracing(TracingSessionID, bool disable_immediately = false);
Primiano Tuccid52e6272018-04-06 19:06:53 +0200252 void Flush(TracingSessionID tsid,
Primiano Tucci3cbb10a2018-04-10 17:52:40 +0100253 uint32_t timeout_ms,
Primiano Tuccid52e6272018-04-06 19:06:53 +0200254 ConsumerEndpoint::FlushCallback);
255 void FlushAndDisableTracing(TracingSessionID);
Primiano Tucci20d441d2018-01-16 09:25:51 +0000256 void ReadBuffers(TracingSessionID, ConsumerEndpointImpl*);
257 void FreeBuffers(TracingSessionID);
Primiano Tucci42e2de12017-12-07 16:46:04 +0000258
Primiano Tucci4f9b6d72017-12-05 20:59:16 +0000259 // Service implementation.
Florian Mayer6a1a4d52018-06-08 16:47:07 +0100260 std::unique_ptr<TracingService::ProducerEndpoint> ConnectProducer(
Primiano Tucci4f9b6d72017-12-05 20:59:16 +0000261 Producer*,
Sami Kyostila32e0b542018-02-14 08:55:43 +0000262 uid_t uid,
Isabelle Taylor86262cb2018-03-27 16:00:54 +0100263 const std::string& producer_name,
Oystein Eftevaagc8d2f072019-03-29 09:41:04 -0700264 size_t shared_memory_size_hint_bytes = 0,
Eric Seckler062ed502019-05-23 09:02:57 +0100265 bool in_process = false,
266 ProducerSMBScrapingMode smb_scraping_mode =
267 ProducerSMBScrapingMode::kDefault) override;
Primiano Tucci42e2de12017-12-07 16:46:04 +0000268
Florian Mayer6a1a4d52018-06-08 16:47:07 +0100269 std::unique_ptr<TracingService::ConsumerEndpoint> ConnectConsumer(
Primiano Tucci9ba1d842018-12-20 17:31:04 +0100270 Consumer*,
271 uid_t) override;
Primiano Tucci42e2de12017-12-07 16:46:04 +0000272
Eric Seckler062ed502019-05-23 09:02:57 +0100273 // Set whether SMB scraping should be enabled by default or not. Producers can
274 // override this setting for their own SMBs.
Eric Secklera01e28a2019-01-08 11:21:04 +0000275 void SetSMBScrapingEnabled(bool enabled) override {
276 smb_scraping_enabled_ = enabled;
277 }
278
Primiano Tucci4f9b6d72017-12-05 20:59:16 +0000279 // Exposed mainly for testing.
280 size_t num_producers() const { return producers_.size(); }
281 ProducerEndpointImpl* GetProducer(ProducerID) const;
282
Primiano Tuccibaeecf12018-07-25 12:02:20 +0100283 uint32_t override_data_source_test_timeout_ms_for_testing = 0;
284
Primiano Tucci4f9b6d72017-12-05 20:59:16 +0000285 private:
Florian Mayer6a1a4d52018-06-08 16:47:07 +0100286 friend class TracingServiceImplTest;
Eric Seckler062ed502019-05-23 09:02:57 +0100287 friend class TracingIntegrationTest;
Primiano Tucci081d46a2018-02-28 11:09:43 +0000288
Primiano Tucci53589332017-12-19 11:31:13 +0100289 struct RegisteredDataSource {
290 ProducerID producer_id;
Primiano Tucci53589332017-12-19 11:31:13 +0100291 DataSourceDescriptor descriptor;
292 };
293
Sami Kyostila06487a22018-02-27 13:48:38 +0000294 // Represents an active data source for a tracing session.
295 struct DataSourceInstance {
Primiano Tucci5403e4f2018-11-27 10:07:03 +0000296 DataSourceInstance(DataSourceInstanceID id,
297 const DataSourceConfig& cfg,
298 const std::string& ds_name,
Eric Seckler4ff03e52019-03-15 10:10:30 +0000299 bool notify_on_start,
Ryan Savitski33868d52019-05-13 10:56:14 +0100300 bool notify_on_stop,
301 bool handles_incremental_state_invalidation)
Primiano Tucci5403e4f2018-11-27 10:07:03 +0000302 : instance_id(id),
303 config(cfg),
304 data_source_name(ds_name),
Eric Seckler4ff03e52019-03-15 10:10:30 +0000305 will_notify_on_start(notify_on_start),
Ryan Savitski33868d52019-05-13 10:56:14 +0100306 will_notify_on_stop(notify_on_stop),
307 handles_incremental_state_clear(
308 handles_incremental_state_invalidation) {}
Primiano Tucci674076d2018-10-01 10:41:09 +0100309 DataSourceInstance(const DataSourceInstance&) = delete;
310 DataSourceInstance& operator=(const DataSourceInstance&) = delete;
Primiano Tucci674076d2018-10-01 10:41:09 +0100311
Sami Kyostila06487a22018-02-27 13:48:38 +0000312 DataSourceInstanceID instance_id;
Primiano Tucci674076d2018-10-01 10:41:09 +0100313 DataSourceConfig config;
Primiano Tucci9daa4832018-03-28 23:28:17 +0100314 std::string data_source_name;
Eric Seckler4ff03e52019-03-15 10:10:30 +0000315 bool will_notify_on_start;
Primiano Tuccibaeecf12018-07-25 12:02:20 +0100316 bool will_notify_on_stop;
Ryan Savitski33868d52019-05-13 10:56:14 +0100317 bool handles_incremental_state_clear;
Eric Seckler4ff03e52019-03-15 10:10:30 +0000318
319 enum DataSourceInstanceState {
320 CONFIGURED,
321 STARTING,
322 STARTED,
323 STOPPING,
324 STOPPED
325 };
326 DataSourceInstanceState state = CONFIGURED;
Sami Kyostila06487a22018-02-27 13:48:38 +0000327 };
328
Primiano Tuccid52e6272018-04-06 19:06:53 +0200329 struct PendingFlush {
330 std::set<ProducerID> producers;
331 ConsumerEndpoint::FlushCallback callback;
332 explicit PendingFlush(decltype(callback) cb) : callback(std::move(cb)) {}
333 };
334
Primiano Tucci53589332017-12-19 11:31:13 +0100335 // Holds the state of a tracing session. A tracing session is uniquely bound
336 // a specific Consumer. Each Consumer can own one or more sessions.
337 struct TracingSession {
Primiano Tucci674076d2018-10-01 10:41:09 +0100338 enum State {
339 DISABLED = 0,
340 CONFIGURED,
341 STARTED,
342 DISABLING_WAITING_STOP_ACKS
343 };
Primiano Tuccibaeecf12018-07-25 12:02:20 +0100344
345 TracingSession(TracingSessionID, ConsumerEndpointImpl*, const TraceConfig&);
Primiano Tucci20d441d2018-01-16 09:25:51 +0000346
347 size_t num_buffers() const { return buffers_index.size(); }
348
Primiano Tucci3cbb10a2018-04-10 17:52:40 +0100349 uint32_t delay_to_next_write_period_ms() const {
Sami Kyostila01c45f02018-03-29 15:43:10 +0100350 PERFETTO_DCHECK(write_period_ms > 0);
351 return write_period_ms -
352 (base::GetWallTimeMs().count() % write_period_ms);
Primiano Tucci2ffd1a52018-03-27 01:01:30 +0100353 }
354
Florian Mayere563f662019-01-09 11:04:50 +0000355 uint32_t flush_timeout_ms() {
356 uint32_t timeout_ms = config.flush_timeout_ms();
357 return timeout_ms ? timeout_ms : kDefaultFlushTimeoutMs;
358 }
359
Eric Secklerd0ac7ca2019-02-06 09:13:45 +0000360 PacketSequenceID GetPacketSequenceID(ProducerID producer_id,
361 WriterID writer_id) {
362 auto key = std::make_pair(producer_id, writer_id);
363 auto it = packet_sequence_ids.find(key);
364 if (it != packet_sequence_ids.end())
365 return it->second;
366 // We shouldn't run out of sequence IDs (producer ID is 16 bit, writer IDs
367 // are limited to 1024).
368 static_assert(kMaxPacketSequenceID > kMaxProducerID * kMaxWriterID,
369 "PacketSequenceID value space doesn't cover service "
370 "sequence ID and all producer/writer ID combinations!");
371 PERFETTO_DCHECK(last_packet_sequence_id < kMaxPacketSequenceID);
372 PacketSequenceID sequence_id = ++last_packet_sequence_id;
373 packet_sequence_ids[key] = sequence_id;
374 return sequence_id;
375 }
376
Eric Seckler4ff03e52019-03-15 10:10:30 +0000377 DataSourceInstance* GetDataSourceInstance(
378 ProducerID producer_id,
379 DataSourceInstanceID instance_id) {
380 for (auto& inst_kv : data_source_instances) {
381 if (inst_kv.first != producer_id ||
382 inst_kv.second.instance_id != instance_id) {
383 continue;
384 }
385 return &inst_kv.second;
386 }
387 return nullptr;
388 }
389
390 bool AllDataSourceInstancesStopped() {
391 for (const auto& inst_kv : data_source_instances) {
392 if (inst_kv.second.state != DataSourceInstance::STOPPED)
393 return false;
394 }
395 return true;
396 }
397
Primiano Tuccibaeecf12018-07-25 12:02:20 +0100398 const TracingSessionID id;
399
Primiano Tucci2ffd1a52018-03-27 01:01:30 +0100400 // The consumer that started the session.
Primiano Tucci9ba1d842018-12-20 17:31:04 +0100401 // Can be nullptr if the consumer detached from the session.
402 ConsumerEndpointImpl* consumer_maybe_null;
403
404 // Unix uid of the consumer. This is valid even after the consumer detaches
405 // and does not change for the entire duration of the session. It is used to
406 // prevent that a consumer re-attaches to a session from a different uid.
407 uid_t const consumer_uid;
Primiano Tucci2ffd1a52018-03-27 01:01:30 +0100408
Stephen Nusko59847292019-03-22 13:54:08 +0000409 // The list of triggers this session received while alive and the time they
410 // were received at. This is used to insert 'fake' packets back to the
411 // consumer so they can tell when some event happened. The order matches the
412 // order they were received.
Stephen Nusko70ea3302019-04-01 19:44:40 +0100413 struct TriggerInfo {
414 uint64_t boot_time_ns;
415 std::string trigger_name;
416 std::string producer_name;
417 uid_t producer_uid;
418 };
419 std::vector<TriggerInfo> received_triggers;
Stephen Nusko59847292019-03-22 13:54:08 +0000420
Oystein Eftevaagcb6e4c82019-03-06 15:38:26 -0800421 // The trace config provided by the Consumer when calling
422 // EnableTracing(), plus any updates performed by ChangeTraceConfig.
423 TraceConfig config;
Oystein Eftevaag1269b4a2018-01-10 16:29:38 -0800424
Primiano Tucci53589332017-12-19 11:31:13 +0100425 // List of data source instances that have been enabled on the various
426 // producers for this tracing session.
Ryan Savitski33868d52019-05-13 10:56:14 +0100427 // TODO(rsavitski): at the time of writing, the map structure is unused
428 // (even when the calling code has a key). This is also an opportunity to
429 // consider an alternative data type, e.g. a map of vectors.
Sami Kyostila06487a22018-02-27 13:48:38 +0000430 std::multimap<ProducerID, DataSourceInstance> data_source_instances;
Primiano Tucci53589332017-12-19 11:31:13 +0100431
Primiano Tuccid52e6272018-04-06 19:06:53 +0200432 // For each Flush(N) request, keeps track of the set of producers for which
433 // we are still awaiting a NotifyFlushComplete(N) ack.
434 std::map<FlushRequestID, PendingFlush> pending_flushes;
435
Primiano Tucci20d441d2018-01-16 09:25:51 +0000436 // Maps a per-trace-session buffer index into the corresponding global
437 // BufferID (shared namespace amongst all consumers). This vector has as
438 // many entries as |config.buffers_size()|.
439 std::vector<BufferID> buffers_index;
Sami Kyostilafbccb3c2018-03-21 14:00:47 +0000440
Eric Secklerd0ac7ca2019-02-06 09:13:45 +0000441 std::map<std::pair<ProducerID, WriterID>, PacketSequenceID>
442 packet_sequence_ids;
443 PacketSequenceID last_packet_sequence_id = kServicePacketSequenceID;
444
Primiano Tucci9754d0d2018-09-15 12:41:46 +0100445 // When the last snapshots (clock, stats, sync marker) were emitted into
446 // the output stream.
447 base::TimeMillis last_snapshot_time = {};
Primiano Tucci5e33cad2018-04-30 14:41:25 +0100448
Sami Kyostila200bd2e2018-03-26 12:24:10 +0100449 // Whether we mirrored the trace config back to the trace output yet.
450 bool did_emit_config = false;
Primiano Tucci2ffd1a52018-03-27 01:01:30 +0100451
Hector Dearman685f7522019-03-12 14:28:56 +0000452 // Whether we put the system info into the trace output yet.
453 bool did_emit_system_info = false;
454
Stephen Nusko70ea3302019-04-01 19:44:40 +0100455 // The number of received triggers we've emitted into the trace output.
456 size_t num_triggers_emitted_into_trace = 0;
457
Hector Dearmane004a572019-05-13 17:51:43 +0100458 // Initial clock snapshot, captured at trace start time (when state goes
459 // to TracingSession::STARTED). Emitted into the trace when the consumer
460 // first begins reading the trace.
461 std::vector<TracePacket> initial_clock_snapshot_;
462
Primiano Tuccibaeecf12018-07-25 12:02:20 +0100463 State state = DISABLED;
Primiano Tucci2ffd1a52018-03-27 01:01:30 +0100464
Primiano Tucci9ba1d842018-12-20 17:31:04 +0100465 // If the consumer detached the session, this variable defines the key used
466 // for identifying the session later when reattaching.
467 std::string detach_key;
468
Primiano Tucci2ffd1a52018-03-27 01:01:30 +0100469 // This is set when the Consumer calls sets |write_into_file| == true in the
470 // TraceConfig. In this case this represents the file we should stream the
471 // trace packets into, rather than returning it to the consumer via
472 // OnTraceData().
473 base::ScopedFile write_into_file;
Primiano Tucci3cbb10a2018-04-10 17:52:40 +0100474 uint32_t write_period_ms = 0;
475 uint64_t max_file_size_bytes = 0;
476 uint64_t bytes_written_into_file = 0;
Primiano Tucci53589332017-12-19 11:31:13 +0100477 };
478
Florian Mayer6a1a4d52018-06-08 16:47:07 +0100479 TracingServiceImpl(const TracingServiceImpl&) = delete;
480 TracingServiceImpl& operator=(const TracingServiceImpl&) = delete;
Primiano Tucci20d441d2018-01-16 09:25:51 +0000481
Primiano Tucci674076d2018-10-01 10:41:09 +0100482 DataSourceInstance* SetupDataSource(const TraceConfig::DataSource&,
483 const TraceConfig::ProducerConfig&,
484 const RegisteredDataSource&,
485 TracingSession*);
Oystein Eftevaag1269b4a2018-01-10 16:29:38 -0800486
Primiano Tucci081d46a2018-02-28 11:09:43 +0000487 // Returns the next available ProducerID that is not in |producers_|.
488 ProducerID GetNextProducerID();
489
Primiano Tucci20d441d2018-01-16 09:25:51 +0000490 // Returns a pointer to the |tracing_sessions_| entry or nullptr if the
491 // session doesn't exists.
492 TracingSession* GetTracingSession(TracingSessionID);
Primiano Tucci4f9b6d72017-12-05 20:59:16 +0000493
Primiano Tucci9ba1d842018-12-20 17:31:04 +0100494 // Returns a pointer to the |tracing_sessions_| entry, matching the given
495 // uid and detach key, or nullptr if no such session exists.
496 TracingSession* GetDetachedSession(uid_t, const std::string& key);
497
Lalit Maganti485faff2018-03-06 11:51:35 +0000498 // Update the memory guard rail by using the latest information from the
499 // shared memory and trace buffers.
500 void UpdateMemoryGuardrail();
501
Eric Seckler4ff03e52019-03-15 10:10:30 +0000502 void StartDataSourceInstance(ProducerEndpointImpl* producer,
503 TracingSession* tracing_session,
504 DataSourceInstance* instance);
Primiano Tucci9754d0d2018-09-15 12:41:46 +0100505 void SnapshotSyncMarker(std::vector<TracePacket>*);
Primiano Tucci80cb4182019-05-14 09:37:56 +0100506 void SnapshotClocks(std::vector<TracePacket>*, bool set_root_timestamp);
Primiano Tucci9754d0d2018-09-15 12:41:46 +0100507 void SnapshotStats(TracingSession*, std::vector<TracePacket>*);
Eric Secklereaf29ed2019-01-23 09:53:55 +0000508 TraceStats GetTraceStats(TracingSession* tracing_session);
Sami Kyostila200bd2e2018-03-26 12:24:10 +0100509 void MaybeEmitTraceConfig(TracingSession*, std::vector<TracePacket>*);
Hector Dearman685f7522019-03-12 14:28:56 +0000510 void MaybeEmitSystemInfo(TracingSession*, std::vector<TracePacket>*);
Stephen Nusko70ea3302019-04-01 19:44:40 +0100511 void MaybeEmitReceivedTriggers(TracingSession*, std::vector<TracePacket>*);
Primiano Tuccid52e6272018-04-06 19:06:53 +0200512 void OnFlushTimeout(TracingSessionID, FlushRequestID);
Primiano Tuccibaeecf12018-07-25 12:02:20 +0100513 void OnDisableTracingTimeout(TracingSessionID);
514 void DisableTracingNotifyConsumerAndFlushFile(TracingSession*);
Primiano Tuccicaa57802018-11-25 11:07:07 +0000515 void PeriodicFlushTask(TracingSessionID, bool post_next_only);
Eric Secklera01e28a2019-01-08 11:21:04 +0000516 void CompleteFlush(TracingSessionID tsid,
517 ConsumerEndpoint::FlushCallback callback,
518 bool success);
519 void ScrapeSharedMemoryBuffers(TracingSession* tracing_session,
520 ProducerEndpointImpl* producer);
Ryan Savitski33868d52019-05-13 10:56:14 +0100521 void PeriodicClearIncrementalStateTask(TracingSessionID, bool post_next_only);
Hector Dearman6214c8f2018-03-27 16:16:22 +0100522 TraceBuffer* GetBufferByID(BufferID);
Stephen Nusko59847292019-03-22 13:54:08 +0000523 void OnStartTriggersTimeout(TracingSessionID tsid);
Primiano Tucciecf9e4a2018-03-14 14:51:58 +0000524
Primiano Tucci4f9b6d72017-12-05 20:59:16 +0000525 base::TaskRunner* const task_runner_;
Primiano Tucci53589332017-12-19 11:31:13 +0100526 std::unique_ptr<SharedMemory::Factory> shm_factory_;
Primiano Tucci4f9b6d72017-12-05 20:59:16 +0000527 ProducerID last_producer_id_ = 0;
Primiano Tucci53589332017-12-19 11:31:13 +0100528 DataSourceInstanceID last_data_source_instance_id_ = 0;
Primiano Tucci20d441d2018-01-16 09:25:51 +0000529 TracingSessionID last_tracing_session_id_ = 0;
Primiano Tuccid52e6272018-04-06 19:06:53 +0200530 FlushRequestID last_flush_request_id_ = 0;
Primiano Tucci5e33cad2018-04-30 14:41:25 +0100531 uid_t uid_ = 0;
Primiano Tucci53589332017-12-19 11:31:13 +0100532
533 // Buffer IDs are global across all consumers (because a Producer can produce
534 // data for more than one trace session, hence more than one consumer).
Primiano Tucci20d441d2018-01-16 09:25:51 +0000535 IdAllocator<BufferID> buffer_ids_;
Primiano Tucci53589332017-12-19 11:31:13 +0100536
537 std::multimap<std::string /*name*/, RegisteredDataSource> data_sources_;
Primiano Tucci4f9b6d72017-12-05 20:59:16 +0000538 std::map<ProducerID, ProducerEndpointImpl*> producers_;
Primiano Tucci42e2de12017-12-07 16:46:04 +0000539 std::set<ConsumerEndpointImpl*> consumers_;
Primiano Tucci20d441d2018-01-16 09:25:51 +0000540 std::map<TracingSessionID, TracingSession> tracing_sessions_;
Hector Dearman6214c8f2018-03-27 16:16:22 +0100541 std::map<BufferID, std::unique_ptr<TraceBuffer>> buffers_;
Primiano Tucci20d441d2018-01-16 09:25:51 +0000542
Eric Secklera01e28a2019-01-08 11:21:04 +0000543 bool smb_scraping_enabled_ = false;
Florian Mayer61c55482018-03-06 14:43:54 +0000544 bool lockdown_mode_ = false;
Primiano Tucci9754d0d2018-09-15 12:41:46 +0100545 uint32_t min_write_period_ms_ = 100; // Overridable for testing.
546
547 uint8_t sync_marker_packet_[32]; // Lazily initialized.
548 size_t sync_marker_packet_size_ = 0;
Florian Mayer61c55482018-03-06 14:43:54 +0000549
Eric Seckler2c72bd82019-02-08 15:01:34 +0000550 // Stats.
551 uint64_t chunks_discarded_ = 0;
552 uint64_t patches_discarded_ = 0;
553
Florian Mayercd08ec62018-01-31 17:49:25 +0000554 PERFETTO_THREAD_CHECKER(thread_checker_)
555
Florian Mayer6a1a4d52018-06-08 16:47:07 +0100556 base::WeakPtrFactory<TracingServiceImpl>
557 weak_ptr_factory_; // Keep at the end.
Primiano Tucci4f9b6d72017-12-05 20:59:16 +0000558};
559
560} // namespace perfetto
561
Florian Mayer6a1a4d52018-06-08 16:47:07 +0100562#endif // SRC_TRACING_CORE_TRACING_SERVICE_IMPL_H_