xref: /aosp_15_r20/external/perfetto/src/perfetto_cmd/packet_writer.cc (revision 6dbdd20afdafa5e3ca9b8809fa73465d530080dc)
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 "src/perfetto_cmd/packet_writer.h"
18 
19 #include <array>
20 
21 #include <fcntl.h>
22 #include <signal.h>
23 #include <stdio.h>
24 #include <sys/stat.h>
25 
26 #include "perfetto/base/build_config.h"
27 #include "perfetto/ext/base/getopt.h"
28 #include "perfetto/ext/base/paged_memory.h"
29 #include "perfetto/ext/base/utils.h"
30 #include "perfetto/ext/tracing/core/trace_packet.h"
31 #include "perfetto/protozero/proto_utils.h"
32 #include "protos/perfetto/trace/trace.pbzero.h"
33 
34 namespace perfetto {
35 namespace {
36 
37 using protozero::proto_utils::MakeTagLengthDelimited;
38 using protozero::proto_utils::WriteVarInt;
39 using Preamble = std::array<char, 16>;
40 
41 template <uint32_t id>
GetPreamble(size_t sz,Preamble * preamble)42 size_t GetPreamble(size_t sz, Preamble* preamble) {
43   uint8_t* ptr = reinterpret_cast<uint8_t*>(preamble->data());
44   constexpr uint32_t tag = MakeTagLengthDelimited(id);
45   ptr = WriteVarInt(tag, ptr);
46   ptr = WriteVarInt(sz, ptr);
47   size_t preamble_size = reinterpret_cast<uintptr_t>(ptr) -
48                          reinterpret_cast<uintptr_t>(preamble->data());
49   PERFETTO_DCHECK(preamble_size < preamble->size());
50   return preamble_size;
51 }
52 
53 }  // namespace
54 
~PacketWriter()55 PacketWriter::~PacketWriter() {
56   fflush(fd_);
57 }
58 
WritePacket(const TracePacket & packet)59 bool PacketWriter::WritePacket(const TracePacket& packet) {
60   Preamble preamble;
61   size_t size = GetPreamble<protos::pbzero::Trace::kPacketFieldNumber>(
62       packet.size(), &preamble);
63   if (fwrite(preamble.data(), 1, size, fd_) != size)
64     return false;
65   for (const Slice& slice : packet.slices()) {
66     if (fwrite(reinterpret_cast<const char*>(slice.start), 1, slice.size,
67                fd_) != slice.size) {
68       return false;
69     }
70   }
71 
72   return true;
73 }
74 
75 }  // namespace perfetto
76