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 return *this;
37 }
38
AddSlice(Slice slice)39 void TracePacket::AddSlice(Slice slice) {
40 size_ += slice.size;
41 slices_.push_back(std::move(slice));
42 }
43
AddSlice(const void * start,size_t size)44 void TracePacket::AddSlice(const void* start, size_t size) {
45 size_ += size;
46 slices_.emplace_back(start, size);
47 }
48
GetProtoPreamble()49 std::tuple<char*, size_t> TracePacket::GetProtoPreamble() {
50 using protozero::proto_utils::MakeTagLengthDelimited;
51 using protozero::proto_utils::WriteVarInt;
52 uint8_t* ptr = reinterpret_cast<uint8_t*>(&preamble_[0]);
53
54 constexpr uint8_t tag = MakeTagLengthDelimited(kPacketFieldNumber);
55 static_assert(tag < 0x80, "TracePacket tag should fit in one byte");
56 *(ptr++) = tag;
57
58 ptr = WriteVarInt(size(), ptr);
59 size_t preamble_size = reinterpret_cast<uintptr_t>(ptr) -
60 reinterpret_cast<uintptr_t>(&preamble_[0]);
61 PERFETTO_DCHECK(preamble_size <= sizeof(preamble_));
62 return std::make_tuple(&preamble_[0], preamble_size);
63 }
64
GetRawBytesForTesting()65 std::string TracePacket::GetRawBytesForTesting() {
66 std::string data;
67 data.resize(size());
68 size_t pos = 0;
69 for (const Slice& slice : slices()) {
70 PERFETTO_CHECK(pos + slice.size <= data.size());
71 memcpy(&data[pos], slice.start, slice.size);
72 pos += slice.size;
73 }
74 return data;
75 }
76
77 } // namespace perfetto
78