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_TRACE_PROCESSOR_IMPORTERS_PROTO_PACKET_SEQUENCE_STATE_H_
18 #define SRC_TRACE_PROCESSOR_IMPORTERS_PROTO_PACKET_SEQUENCE_STATE_H_
19
20 #include <stdint.h>
21
22 #include <unordered_map>
23 #include <vector>
24
25 #include "perfetto/base/compiler.h"
26 #include "perfetto/protozero/proto_decoder.h"
27 #include "src/trace_processor/importers/common/trace_blob_view.h"
28 #include "src/trace_processor/importers/proto/stack_profile_tracker.h"
29 #include "src/trace_processor/storage/trace_storage.h"
30 #include "src/trace_processor/types/trace_processor_context.h"
31
32 #include "protos/perfetto/trace/trace_packet_defaults.pbzero.h"
33 #include "protos/perfetto/trace/track_event/track_event.pbzero.h"
34
35 namespace perfetto {
36 namespace trace_processor {
37
38 #if PERFETTO_DCHECK_IS_ON()
39 // When called from GetOrCreateDecoder(), should include the stringified name of
40 // the MessageType.
41 #define PERFETTO_TYPE_IDENTIFIER PERFETTO_DEBUG_FUNCTION_IDENTIFIER()
42 #else // PERFETTO_DCHECK_IS_ON()
43 #define PERFETTO_TYPE_IDENTIFIER nullptr
44 #endif // PERFETTO_DCHECK_IS_ON()
45
46 // Entry in an interning index, refers to the interned message.
47 class InternedMessageView {
48 public:
InternedMessageView(TraceBlobView msg)49 InternedMessageView(TraceBlobView msg) : message_(std::move(msg)) {}
50
51 InternedMessageView(InternedMessageView&&) = default;
52 InternedMessageView& operator=(InternedMessageView&&) = default;
53
54 // Allow copy by cloning the TraceBlobView. This is required for
55 // UpdateTracePacketDefaults().
InternedMessageView(const InternedMessageView & view)56 InternedMessageView(const InternedMessageView& view)
57 : message_(view.message_.slice(0, view.message_.length())) {}
58 InternedMessageView& operator=(const InternedMessageView& view) {
59 this->message_ = view.message_.slice(0, view.message_.length());
60 this->decoder_ = nullptr;
61 this->decoder_type_ = nullptr;
62 this->submessages_.clear();
63 return *this;
64 }
65
66 // Lazily initializes and returns the decoder object for the message. The
67 // decoder is stored in the InternedMessageView to avoid having to parse the
68 // message multiple times.
69 template <typename MessageType>
GetOrCreateDecoder()70 typename MessageType::Decoder* GetOrCreateDecoder() {
71 if (!decoder_) {
72 // Lazy init the decoder and save it away, so that we don't have to
73 // reparse the message every time we access the interning entry.
74 decoder_ = std::unique_ptr<void, std::function<void(void*)>>(
75 new typename MessageType::Decoder(message_.data(), message_.length()),
76 [](void* obj) {
77 delete reinterpret_cast<typename MessageType::Decoder*>(obj);
78 });
79 decoder_type_ = PERFETTO_TYPE_IDENTIFIER;
80 }
81 // Verify that the type of the decoder didn't change.
82 if (PERFETTO_TYPE_IDENTIFIER &&
83 strcmp(decoder_type_,
84 // GCC complains if this arg can be null.
85 PERFETTO_TYPE_IDENTIFIER ? PERFETTO_TYPE_IDENTIFIER : "") != 0) {
86 PERFETTO_FATAL(
87 "Interning entry accessed under different types! previous type: "
88 "%s. new type: %s.",
89 decoder_type_, PERFETTO_DEBUG_FUNCTION_IDENTIFIER());
90 }
91 return reinterpret_cast<typename MessageType::Decoder*>(decoder_.get());
92 }
93
94 // Lookup a submessage of the interned message, which is then itself stored
95 // as InternedMessageView, so that we only need to parse it once. Returns
96 // nullptr if the field isn't set.
97 // TODO(eseckler): Support repeated fields.
98 template <typename MessageType, uint32_t FieldId>
GetOrCreateSubmessageView()99 InternedMessageView* GetOrCreateSubmessageView() {
100 auto it = submessages_.find(FieldId);
101 if (it != submessages_.end())
102 return it->second.get();
103 auto* decoder = GetOrCreateDecoder<MessageType>();
104 // Calls the at() template method on the decoder.
105 auto field = decoder->template at<FieldId>().as_bytes();
106 if (!field.data)
107 return nullptr;
108 const size_t offset = message_.offset_of(field.data);
109 TraceBlobView submessage = message_.slice(offset, field.size);
110 InternedMessageView* submessage_view =
111 new InternedMessageView(std::move(submessage));
112 submessages_.emplace_hint(
113 it, FieldId, std::unique_ptr<InternedMessageView>(submessage_view));
114 return submessage_view;
115 }
116
message()117 const TraceBlobView& message() { return message_; }
118
119 private:
120 using SubMessageViewMap =
121 std::unordered_map<uint32_t /*field_id*/,
122 std::unique_ptr<InternedMessageView>>;
123
124 TraceBlobView message_;
125
126 // Stores the decoder for the message_, so that the message does not have to
127 // be re-decoded every time the interned message is looked up. Lazily
128 // initialized in GetOrCreateDecoder(). Since we don't know the type of the
129 // decoder until GetOrCreateDecoder() is called, we store the decoder as a
130 // void* unique_pointer with a destructor function that's supplied in
131 // GetOrCreateDecoder() when the decoder is created.
132 std::unique_ptr<void, std::function<void(void*)>> decoder_;
133
134 // Type identifier for the decoder. Only valid in debug builds and on
135 // supported platforms. Used to verify that GetOrCreateDecoder() is always
136 // called with the same template argument.
137 const char* decoder_type_ = nullptr;
138
139 // Views of submessages of the interned message. Submessages are lazily
140 // added by GetOrCreateSubmessageView(). By storing submessages and their
141 // decoders, we avoid having to decode submessages multiple times if they
142 // looked up often.
143 SubMessageViewMap submessages_;
144 };
145
146 using InternedMessageMap =
147 std::unordered_map<uint64_t /*iid*/, InternedMessageView>;
148 using InternedFieldMap =
149 std::unordered_map<uint32_t /*field_id*/, InternedMessageMap>;
150
151 class PacketSequenceState;
152
153 class PacketSequenceStateGeneration {
154 public:
155 // Returns |nullptr| if the message with the given |iid| was not found (also
156 // records a stat in this case).
157 template <uint32_t FieldId, typename MessageType>
158 typename MessageType::Decoder* LookupInternedMessage(uint64_t iid);
159
160 InternedMessageView* GetInternedMessageView(uint32_t field_id, uint64_t iid);
161 // Returns |nullptr| if no defaults were set.
GetTracePacketDefaultsView()162 InternedMessageView* GetTracePacketDefaultsView() {
163 if (!trace_packet_defaults_)
164 return nullptr;
165 return &trace_packet_defaults_.value();
166 }
167
168 // Returns |nullptr| if no defaults were set.
GetTracePacketDefaults()169 protos::pbzero::TracePacketDefaults::Decoder* GetTracePacketDefaults() {
170 InternedMessageView* view = GetTracePacketDefaultsView();
171 if (!view)
172 return nullptr;
173 return view->GetOrCreateDecoder<protos::pbzero::TracePacketDefaults>();
174 }
175
176 // Returns |nullptr| if no TrackEventDefaults were set.
GetTrackEventDefaults()177 protos::pbzero::TrackEventDefaults::Decoder* GetTrackEventDefaults() {
178 auto* packet_defaults_view = GetTracePacketDefaultsView();
179 if (packet_defaults_view) {
180 auto* track_event_defaults_view =
181 packet_defaults_view
182 ->GetOrCreateSubmessageView<protos::pbzero::TracePacketDefaults,
183 protos::pbzero::TracePacketDefaults::
184 kTrackEventDefaultsFieldNumber>();
185 if (track_event_defaults_view) {
186 return track_event_defaults_view
187 ->GetOrCreateDecoder<protos::pbzero::TrackEventDefaults>();
188 }
189 }
190 return nullptr;
191 }
192
state()193 PacketSequenceState* state() const { return state_; }
generation_index()194 size_t generation_index() const { return generation_index_; }
195
196 private:
197 friend class PacketSequenceState;
198
PacketSequenceStateGeneration(PacketSequenceState * state,size_t generation_index)199 PacketSequenceStateGeneration(PacketSequenceState* state,
200 size_t generation_index)
201 : state_(state), generation_index_(generation_index) {}
202
PacketSequenceStateGeneration(PacketSequenceState * state,size_t generation_index,InternedFieldMap interned_data,TraceBlobView defaults)203 PacketSequenceStateGeneration(PacketSequenceState* state,
204 size_t generation_index,
205 InternedFieldMap interned_data,
206 TraceBlobView defaults)
207 : state_(state),
208 generation_index_(generation_index),
209 interned_data_(interned_data),
210 trace_packet_defaults_(InternedMessageView(std::move(defaults))) {}
211
212 void InternMessage(uint32_t field_id, TraceBlobView message);
213
SetTracePacketDefaults(TraceBlobView defaults)214 void SetTracePacketDefaults(TraceBlobView defaults) {
215 // Defaults should only be set once per generation.
216 PERFETTO_DCHECK(!trace_packet_defaults_);
217 trace_packet_defaults_ = InternedMessageView(std::move(defaults));
218 }
219
220 PacketSequenceState* state_;
221 size_t generation_index_;
222 InternedFieldMap interned_data_;
223 base::Optional<InternedMessageView> trace_packet_defaults_;
224 };
225
226 class PacketSequenceState {
227 public:
PacketSequenceState(TraceProcessorContext * context)228 PacketSequenceState(TraceProcessorContext* context)
229 : context_(context), sequence_stack_profile_tracker_(context) {
230 current_generation_.reset(
231 new PacketSequenceStateGeneration(this, generation_index_++));
232 }
233
IncrementAndGetTrackEventTimeNs(int64_t delta_ns)234 int64_t IncrementAndGetTrackEventTimeNs(int64_t delta_ns) {
235 PERFETTO_DCHECK(track_event_timestamps_valid());
236 track_event_timestamp_ns_ += delta_ns;
237 return track_event_timestamp_ns_;
238 }
239
IncrementAndGetTrackEventThreadTimeNs(int64_t delta_ns)240 int64_t IncrementAndGetTrackEventThreadTimeNs(int64_t delta_ns) {
241 PERFETTO_DCHECK(track_event_timestamps_valid());
242 track_event_thread_timestamp_ns_ += delta_ns;
243 return track_event_thread_timestamp_ns_;
244 }
245
IncrementAndGetTrackEventThreadInstructionCount(int64_t delta)246 int64_t IncrementAndGetTrackEventThreadInstructionCount(int64_t delta) {
247 PERFETTO_DCHECK(track_event_timestamps_valid());
248 track_event_thread_instruction_count_ += delta;
249 return track_event_thread_instruction_count_;
250 }
251
252 // Intern a message into the current generation.
InternMessage(uint32_t field_id,TraceBlobView message)253 void InternMessage(uint32_t field_id, TraceBlobView message) {
254 current_generation_->InternMessage(field_id, std::move(message));
255 }
256
257 // Set the trace packet defaults for the current generation. If the current
258 // generation already has defaults set, starts a new generation without
259 // invalidating other incremental state (such as interned data).
UpdateTracePacketDefaults(TraceBlobView defaults)260 void UpdateTracePacketDefaults(TraceBlobView defaults) {
261 if (!current_generation_->GetTracePacketDefaultsView()) {
262 current_generation_->SetTracePacketDefaults(std::move(defaults));
263 return;
264 }
265
266 // The new defaults should only apply to subsequent messages on the
267 // sequence. Add a new generation with the updated defaults but the
268 // current generation's interned data state.
269 current_generation_.reset(new PacketSequenceStateGeneration(
270 this, generation_index_++, current_generation_->interned_data_,
271 std::move(defaults)));
272 }
273
SetThreadDescriptor(int32_t pid,int32_t tid,int64_t timestamp_ns,int64_t thread_timestamp_ns,int64_t thread_instruction_count)274 void SetThreadDescriptor(int32_t pid,
275 int32_t tid,
276 int64_t timestamp_ns,
277 int64_t thread_timestamp_ns,
278 int64_t thread_instruction_count) {
279 track_event_timestamps_valid_ = true;
280 pid_and_tid_valid_ = true;
281 pid_ = pid;
282 tid_ = tid;
283 track_event_timestamp_ns_ = timestamp_ns;
284 track_event_thread_timestamp_ns_ = thread_timestamp_ns;
285 track_event_thread_instruction_count_ = thread_instruction_count;
286 }
287
OnPacketLoss()288 void OnPacketLoss() {
289 packet_loss_ = true;
290 track_event_timestamps_valid_ = false;
291 }
292
293 // Starts a new generation with clean-slate incremental state and defaults.
OnIncrementalStateCleared()294 void OnIncrementalStateCleared() {
295 packet_loss_ = false;
296 current_generation_.reset(
297 new PacketSequenceStateGeneration(this, generation_index_++));
298 }
299
IsIncrementalStateValid()300 bool IsIncrementalStateValid() const { return !packet_loss_; }
301
sequence_stack_profile_tracker()302 SequenceStackProfileTracker& sequence_stack_profile_tracker() {
303 return sequence_stack_profile_tracker_;
304 }
305
306 // Returns a ref-counted ptr to the current generation.
current_generation()307 std::shared_ptr<PacketSequenceStateGeneration> current_generation() const {
308 return current_generation_;
309 }
310
track_event_timestamps_valid()311 bool track_event_timestamps_valid() const {
312 return track_event_timestamps_valid_;
313 }
314
pid_and_tid_valid()315 bool pid_and_tid_valid() const { return pid_and_tid_valid_; }
316
pid()317 int32_t pid() const { return pid_; }
tid()318 int32_t tid() const { return tid_; }
319
context()320 TraceProcessorContext* context() const { return context_; }
321
322 private:
323 TraceProcessorContext* context_;
324
325 size_t generation_index_ = 0;
326
327 // If true, incremental state on the sequence is considered invalid until we
328 // see the next packet with incremental_state_cleared. We assume that we
329 // missed some packets at the beginning of the trace.
330 bool packet_loss_ = true;
331
332 // We can only consider TrackEvent delta timestamps to be correct after we
333 // have observed a thread descriptor (since the last packet loss).
334 bool track_event_timestamps_valid_ = false;
335
336 // |pid_| and |tid_| are only valid after we parsed at least one
337 // ThreadDescriptor packet on the sequence.
338 bool pid_and_tid_valid_ = false;
339
340 // Process/thread ID of the packet sequence set by a ThreadDescriptor
341 // packet. Used as default values for TrackEvents that don't specify a
342 // pid/tid override. Only valid after |pid_and_tid_valid_| is set to true.
343 int32_t pid_ = 0;
344 int32_t tid_ = 0;
345
346 // Current wall/thread timestamps/counters used as reference for the next
347 // TrackEvent delta timestamp.
348 int64_t track_event_timestamp_ns_ = 0;
349 int64_t track_event_thread_timestamp_ns_ = 0;
350 int64_t track_event_thread_instruction_count_ = 0;
351
352 std::shared_ptr<PacketSequenceStateGeneration> current_generation_;
353 SequenceStackProfileTracker sequence_stack_profile_tracker_;
354 };
355
356 template <uint32_t FieldId, typename MessageType>
357 typename MessageType::Decoder*
LookupInternedMessage(uint64_t iid)358 PacketSequenceStateGeneration::LookupInternedMessage(uint64_t iid) {
359 auto* interned_message_view = GetInternedMessageView(FieldId, iid);
360 if (!interned_message_view)
361 return nullptr;
362
363 return interned_message_view->template GetOrCreateDecoder<MessageType>();
364 }
365
366 } // namespace trace_processor
367 } // namespace perfetto
368
369 #endif // SRC_TRACE_PROCESSOR_IMPORTERS_PROTO_PACKET_SEQUENCE_STATE_H_
370