blob: 38a8f45c508d676bb587bb0ddc2741014e494a04 [file] [log] [blame]
Primiano Tucci4f9b6d72017-12-05 20:59:16 +00001/*
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 "src/ipc/buffered_frame_deserializer.h"
18
19#include <inttypes.h>
Primiano Tucci4f9b6d72017-12-05 20:59:16 +000020
21#include <algorithm>
22#include <type_traits>
23#include <utility>
24
25#include "google/protobuf/io/zero_copy_stream_impl_lite.h"
26#include "perfetto/base/logging.h"
Primiano Tucci4f9b6d72017-12-05 20:59:16 +000027
28#include "src/ipc/wire_protocol.pb.h"
29
30namespace perfetto {
31namespace ipc {
32
33namespace {
34constexpr size_t kPageSize = 4096;
35
Primiano Tucci4f9b6d72017-12-05 20:59:16 +000036// The header is just the number of bytes of the Frame protobuf message.
37constexpr size_t kHeaderSize = sizeof(uint32_t);
38} // namespace
39
40BufferedFrameDeserializer::BufferedFrameDeserializer(size_t max_capacity)
41 : capacity_(max_capacity) {
42 PERFETTO_CHECK(max_capacity % kPageSize == 0);
43 PERFETTO_CHECK(max_capacity > kPageSize);
44}
45
Primiano Tuccibbaa58c2017-12-20 13:48:20 +010046BufferedFrameDeserializer::~BufferedFrameDeserializer() = default;
Primiano Tucci4f9b6d72017-12-05 20:59:16 +000047
48BufferedFrameDeserializer::ReceiveBuffer
49BufferedFrameDeserializer::BeginReceive() {
50 // Upon the first recv initialize the buffer to the max message size but
51 // release the physical memory for all but the first page. The kernel will
52 // automatically give us physical pages back as soon as we page-fault on them.
53 if (!buf_) {
54 PERFETTO_DCHECK(size_ == 0);
Primiano Tuccibbaa58c2017-12-20 13:48:20 +010055 buf_ = base::PageAllocator::Allocate(capacity_);
Primiano Tucci4f9b6d72017-12-05 20:59:16 +000056
57 // Surely we are going to use at least the first page. There is very little
58 // point in madvising that as well and immedately after telling the kernel
59 // that we want it back (via recv()).
Primiano Tuccibbaa58c2017-12-20 13:48:20 +010060 int res = madvise(buf() + kPageSize, capacity_ - kPageSize, MADV_DONTNEED);
Primiano Tucci4f9b6d72017-12-05 20:59:16 +000061 PERFETTO_DCHECK(res == 0);
62 }
63
64 PERFETTO_CHECK(capacity_ > size_);
Primiano Tuccibbaa58c2017-12-20 13:48:20 +010065 return ReceiveBuffer{buf() + size_, capacity_ - size_};
Primiano Tucci4f9b6d72017-12-05 20:59:16 +000066}
67
68bool BufferedFrameDeserializer::EndReceive(size_t recv_size) {
69 PERFETTO_CHECK(recv_size + size_ <= capacity_);
70 size_ += recv_size;
71
72 // At this point the contents buf_ can contain:
73 // A) Only a fragment of the header (the size of the frame). E.g.,
74 // 03 00 00 (the header is 4 bytes, one is missing).
75 //
76 // B) A header and a part of the frame. E.g.,
77 // 05 00 00 00 11 22 33
78 // [ header, size=5 ] [ Partial frame ]
79 //
80 // C) One or more complete header+frame. E.g.,
81 // 05 00 00 00 11 22 33 44 55 03 00 00 00 AA BB CC
82 // [ header, size=5 ] [ Whole frame ] [ header, size=3 ] [ Whole frame ]
83 //
84 // D) Some complete header+frame(s) and a partial header or frame (C + A/B).
85 //
86 // C Is the more likely case and the one we are optimizing for. A, B, D can
87 // happen because of the streaming nature of the socket.
88 // The invariant of this function is that, when it returns, buf_ is either
89 // empty (we drained all the complete frames) or starts with the header of the
90 // next, still incomplete, frame.
91
92 size_t consumed_size = 0;
93 for (;;) {
94 if (size_ < consumed_size + kHeaderSize)
95 break; // Case A, not enough data to read even the header.
96
97 // Read the header into |payload_size|.
98 uint32_t payload_size = 0;
Primiano Tuccibbaa58c2017-12-20 13:48:20 +010099 const char* rd_ptr = buf() + consumed_size;
Primiano Tucci4f9b6d72017-12-05 20:59:16 +0000100 memcpy(base::AssumeLittleEndian(&payload_size), rd_ptr, kHeaderSize);
101
102 // Saturate the |payload_size| to prevent overflows. The > capacity_ check
103 // below will abort the parsing.
104 size_t next_frame_size =
105 std::min(static_cast<size_t>(payload_size), capacity_);
106 next_frame_size += kHeaderSize;
107 rd_ptr += kHeaderSize;
108
109 if (size_ < consumed_size + next_frame_size) {
110 // Case B. We got the header but not the whole frame.
111 if (next_frame_size > capacity_) {
112 // The caller is expected to shut down the socket and give up at this
113 // point. If it doesn't do that and insists going on at some point it
114 // will hit the capacity check in BeginReceive().
115 PERFETTO_DLOG("Frame too large (size %zu)", next_frame_size);
116 return false;
117 }
118 break;
119 }
120
121 // Case C. We got at least one header and whole frame.
122 DecodeFrame(rd_ptr, payload_size);
123 consumed_size += next_frame_size;
124 }
125
126 PERFETTO_DCHECK(consumed_size <= size_);
127 if (consumed_size > 0) {
128 // Shift out the consumed data from the buffer. In the typical case (C)
129 // there is nothing to shift really, just setting size_ = 0 is enough.
130 // Shifting is only for the (unlikely) case D.
131 size_ -= consumed_size;
132 if (size_ > 0) {
133 // Case D. We consumed some frames but there is a leftover at the end of
134 // the buffer. Shift out the consumed bytes, so that on the next round
135 // |buf_| starts with the header of the next unconsumed frame.
Primiano Tuccibbaa58c2017-12-20 13:48:20 +0100136 const char* move_begin = buf() + consumed_size;
137 PERFETTO_CHECK(move_begin > buf());
138 PERFETTO_CHECK(move_begin + size_ <= buf() + capacity_);
139 memmove(buf(), move_begin, size_);
Primiano Tucci4f9b6d72017-12-05 20:59:16 +0000140 }
141 // If we just finished decoding a large frame that used more than one page,
142 // release the extra memory in the buffer. Large frames should be quite
143 // rare.
144 if (consumed_size > kPageSize) {
145 size_t size_rounded_up = (size_ / kPageSize + 1) * kPageSize;
146 if (size_rounded_up < capacity_) {
Primiano Tuccibbaa58c2017-12-20 13:48:20 +0100147 char* madvise_begin = buf() + size_rounded_up;
Primiano Tucci4f9b6d72017-12-05 20:59:16 +0000148 const size_t madvise_size = capacity_ - size_rounded_up;
Primiano Tuccibbaa58c2017-12-20 13:48:20 +0100149 PERFETTO_CHECK(madvise_begin > buf() + size_);
150 PERFETTO_CHECK(madvise_begin + madvise_size <= buf() + capacity_);
Primiano Tucci4f9b6d72017-12-05 20:59:16 +0000151 int res = madvise(madvise_begin, madvise_size, MADV_DONTNEED);
152 PERFETTO_DCHECK(res == 0);
153 }
154 }
155 }
156 // At this point |size_| == 0 for case C, > 0 for cases A, B, D.
157 return true;
158}
159
160std::unique_ptr<Frame> BufferedFrameDeserializer::PopNextFrame() {
161 if (decoded_frames_.empty())
162 return nullptr;
163 std::unique_ptr<Frame> frame = std::move(decoded_frames_.front());
164 decoded_frames_.pop_front();
165 return frame;
166}
167
168void BufferedFrameDeserializer::DecodeFrame(const char* data, size_t size) {
169 if (size == 0)
170 return;
171 std::unique_ptr<Frame> frame(new Frame);
172 const int sz = static_cast<int>(size);
173 ::google::protobuf::io::ArrayInputStream stream(data, sz);
174 if (frame->ParseFromBoundedZeroCopyStream(&stream, sz))
175 decoded_frames_.push_back(std::move(frame));
176}
177
178// static
179std::string BufferedFrameDeserializer::Serialize(const Frame& frame) {
180 std::string buf;
181 buf.reserve(1024); // Just an educated guess to avoid trivial expansions.
182 buf.insert(0, kHeaderSize, 0); // Reserve the space for the header.
183 frame.AppendToString(&buf);
184 const uint32_t payload_size = static_cast<uint32_t>(buf.size() - kHeaderSize);
185 PERFETTO_DCHECK(payload_size == static_cast<uint32_t>(frame.GetCachedSize()));
186 char header[kHeaderSize];
187 memcpy(header, base::AssumeLittleEndian(&payload_size), kHeaderSize);
188 buf.replace(0, kHeaderSize, header, kHeaderSize);
189 return buf;
190}
191
192} // namespace ipc
193} // namespace perfetto