xref: /aosp_15_r20/external/perfetto/src/tracing/core/trace_packet.cc (revision 6dbdd20afdafa5e3ca9b8809fa73465d530080dc)
1 /*
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 
17 #include "perfetto/ext/tracing/core/trace_packet.h"
18 
19 #include "perfetto/base/logging.h"
20 #include "perfetto/protozero/proto_utils.h"
21 
22 namespace perfetto {
23 
24 TracePacket::TracePacket() = default;
25 TracePacket::~TracePacket() = default;
26 
TracePacket(TracePacket && other)27 TracePacket::TracePacket(TracePacket&& other) noexcept {
28   *this = std::move(other);
29 }
30 
operator =(TracePacket && other)31 TracePacket& TracePacket::operator=(TracePacket&& other) {
32   slices_ = std::move(other.slices_);
33   other.slices_.clear();
34   size_ = other.size_;
35   other.size_ = 0;
36   buffer_index_for_stats_ = other.buffer_index_for_stats_;
37   other.buffer_index_for_stats_ = 0;
38   return *this;
39 }
40 
AddSlice(Slice slice)41 void TracePacket::AddSlice(Slice slice) {
42   size_ += slice.size;
43   slices_.push_back(std::move(slice));
44 }
45 
AddSlice(const void * start,size_t size)46 void TracePacket::AddSlice(const void* start, size_t size) {
47   size_ += size;
48   slices_.emplace_back(start, size);
49 }
50 
GetProtoPreamble()51 std::tuple<char*, size_t> TracePacket::GetProtoPreamble() {
52   using protozero::proto_utils::MakeTagLengthDelimited;
53   using protozero::proto_utils::WriteVarInt;
54   uint8_t* ptr = reinterpret_cast<uint8_t*>(&preamble_[0]);
55 
56   constexpr uint8_t tag = MakeTagLengthDelimited(kPacketFieldNumber);
57   static_assert(tag < 0x80, "TracePacket tag should fit in one byte");
58   *(ptr++) = tag;
59 
60   ptr = WriteVarInt(size(), ptr);
61   size_t preamble_size = reinterpret_cast<uintptr_t>(ptr) -
62                          reinterpret_cast<uintptr_t>(&preamble_[0]);
63   PERFETTO_DCHECK(preamble_size <= sizeof(preamble_));
64   return std::make_tuple(&preamble_[0], preamble_size);
65 }
66 
GetRawBytesForTesting()67 std::string TracePacket::GetRawBytesForTesting() {
68   std::string data;
69   data.resize(size());
70   size_t pos = 0;
71   for (const Slice& slice : slices()) {
72     PERFETTO_CHECK(pos + slice.size <= data.size());
73     memcpy(&data[pos], slice.start, slice.size);
74     pos += slice.size;
75   }
76   return data;
77 }
78 
79 }  // namespace perfetto
80