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 #include "perfetto/tracing/event_context.h"
18
19 #include "perfetto/tracing/internal/track_event_interned_fields.h"
20 #include "protos/perfetto/trace/interned_data/interned_data.pbzero.h"
21 #include "protos/perfetto/trace/track_event/track_event.pbzero.h"
22
23 namespace perfetto {
24
EventContext(EventContext::TracePacketHandle trace_packet,internal::TrackEventIncrementalState * incremental_state,const internal::TrackEventTlsState * tls_state)25 EventContext::EventContext(
26 EventContext::TracePacketHandle trace_packet,
27 internal::TrackEventIncrementalState* incremental_state,
28 const internal::TrackEventTlsState* tls_state)
29 : trace_packet_(std::move(trace_packet)),
30 event_(trace_packet_->set_track_event()),
31 incremental_state_(incremental_state),
32 tls_state_(tls_state) {}
33
~EventContext()34 EventContext::~EventContext() {
35 if (!trace_packet_)
36 return;
37
38 // When the track event is finalized (i.e., the context is destroyed), we
39 // should flush any newly seen interned data to the trace. The data has
40 // earlier been written to a heap allocated protobuf message
41 // (|serialized_interned_data|). Here we just need to flush it to the main
42 // trace.
43 auto& serialized_interned_data = incremental_state_->serialized_interned_data;
44 if (PERFETTO_LIKELY(serialized_interned_data.empty()))
45 return;
46
47 auto ranges = serialized_interned_data.GetRanges();
48 trace_packet_->AppendScatteredBytes(
49 perfetto::protos::pbzero::TracePacket::kInternedDataFieldNumber,
50 &ranges[0], ranges.size());
51
52 // Reset the message but keep one buffer allocated for future use.
53 serialized_interned_data.Reset();
54 }
55
AddDebugAnnotation(const char * name)56 protos::pbzero::DebugAnnotation* EventContext::AddDebugAnnotation(
57 const char* name) {
58 auto annotation = event()->add_debug_annotations();
59 annotation->set_name_iid(
60 internal::InternedDebugAnnotationName::Get(this, name));
61 return annotation;
62 }
63
AddDebugAnnotation(::perfetto::DynamicString name)64 protos::pbzero::DebugAnnotation* EventContext::AddDebugAnnotation(
65 ::perfetto::DynamicString name) {
66 auto annotation = event()->add_debug_annotations();
67 annotation->set_name(name.value);
68 return annotation;
69 }
70
71 } // namespace perfetto
72