• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "src/ipc/buffered_frame_deserializer.h"
18 
19 #include <inttypes.h>
20 
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"
27 #include "perfetto/base/utils.h"
28 
29 #include "src/ipc/wire_protocol.pb.h"
30 
31 namespace perfetto {
32 namespace ipc {
33 
34 namespace {
35 
36 // The header is just the number of bytes of the Frame protobuf message.
37 constexpr size_t kHeaderSize = sizeof(uint32_t);
38 }  // namespace
39 
BufferedFrameDeserializer(size_t max_capacity)40 BufferedFrameDeserializer::BufferedFrameDeserializer(size_t max_capacity)
41     : capacity_(max_capacity) {
42   PERFETTO_CHECK(max_capacity % base::kPageSize == 0);
43   PERFETTO_CHECK(max_capacity > base::kPageSize);
44 }
45 
46 BufferedFrameDeserializer::~BufferedFrameDeserializer() = default;
47 
48 BufferedFrameDeserializer::ReceiveBuffer
BeginReceive()49 BufferedFrameDeserializer::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_.IsValid()) {
54     PERFETTO_DCHECK(size_ == 0);
55     // TODO(eseckler): Don't commit all of the buffer at once on Windows.
56     buf_ = base::PagedMemory::Allocate(capacity_);
57 
58     // Surely we are going to use at least the first page, but we may not need
59     // the rest for a bit.
60     buf_.AdviseDontNeed(buf() + base::kPageSize, capacity_ - base::kPageSize);
61   }
62 
63   PERFETTO_CHECK(capacity_ > size_);
64   return ReceiveBuffer{buf() + size_, capacity_ - size_};
65 }
66 
EndReceive(size_t recv_size)67 bool BufferedFrameDeserializer::EndReceive(size_t recv_size) {
68   PERFETTO_CHECK(recv_size + size_ <= capacity_);
69   size_ += recv_size;
70 
71   // At this point the contents buf_ can contain:
72   // A) Only a fragment of the header (the size of the frame). E.g.,
73   //    03 00 00 (the header is 4 bytes, one is missing).
74   //
75   // B) A header and a part of the frame. E.g.,
76   //     05 00 00 00         11 22 33
77   //    [ header, size=5 ]  [ Partial frame ]
78   //
79   // C) One or more complete header+frame. E.g.,
80   //     05 00 00 00         11 22 33 44 55   03 00 00 00        AA BB CC
81   //    [ header, size=5 ]  [ Whole frame ]  [ header, size=3 ] [ Whole frame ]
82   //
83   // D) Some complete header+frame(s) and a partial header or frame (C + A/B).
84   //
85   // C Is the more likely case and the one we are optimizing for. A, B, D can
86   // happen because of the streaming nature of the socket.
87   // The invariant of this function is that, when it returns, buf_ is either
88   // empty (we drained all the complete frames) or starts with the header of the
89   // next, still incomplete, frame.
90 
91   size_t consumed_size = 0;
92   for (;;) {
93     if (size_ < consumed_size + kHeaderSize)
94       break;  // Case A, not enough data to read even the header.
95 
96     // Read the header into |payload_size|.
97     uint32_t payload_size = 0;
98     const char* rd_ptr = buf() + consumed_size;
99     memcpy(base::AssumeLittleEndian(&payload_size), rd_ptr, kHeaderSize);
100 
101     // Saturate the |payload_size| to prevent overflows. The > capacity_ check
102     // below will abort the parsing.
103     size_t next_frame_size =
104         std::min(static_cast<size_t>(payload_size), capacity_);
105     next_frame_size += kHeaderSize;
106     rd_ptr += kHeaderSize;
107 
108     if (size_ < consumed_size + next_frame_size) {
109       // Case B. We got the header but not the whole frame.
110       if (next_frame_size > capacity_) {
111         // The caller is expected to shut down the socket and give up at this
112         // point. If it doesn't do that and insists going on at some point it
113         // will hit the capacity check in BeginReceive().
114         PERFETTO_DLOG("Frame too large (size %zu)", next_frame_size);
115         return false;
116       }
117       break;
118     }
119 
120     // Case C. We got at least one header and whole frame.
121     DecodeFrame(rd_ptr, payload_size);
122     consumed_size += next_frame_size;
123   }
124 
125   PERFETTO_DCHECK(consumed_size <= size_);
126   if (consumed_size > 0) {
127     // Shift out the consumed data from the buffer. In the typical case (C)
128     // there is nothing to shift really, just setting size_ = 0 is enough.
129     // Shifting is only for the (unlikely) case D.
130     size_ -= consumed_size;
131     if (size_ > 0) {
132       // Case D. We consumed some frames but there is a leftover at the end of
133       // the buffer. Shift out the consumed bytes, so that on the next round
134       // |buf_| starts with the header of the next unconsumed frame.
135       const char* move_begin = buf() + consumed_size;
136       PERFETTO_CHECK(move_begin > buf());
137       PERFETTO_CHECK(move_begin + size_ <= buf() + capacity_);
138       memmove(buf(), move_begin, size_);
139     }
140     // If we just finished decoding a large frame that used more than one page,
141     // release the extra memory in the buffer. Large frames should be quite
142     // rare.
143     if (consumed_size > base::kPageSize) {
144       size_t size_rounded_up = (size_ / base::kPageSize + 1) * base::kPageSize;
145       if (size_rounded_up < capacity_) {
146         char* madvise_begin = buf() + size_rounded_up;
147         const size_t madvise_size = capacity_ - size_rounded_up;
148         PERFETTO_CHECK(madvise_begin > buf() + size_);
149         PERFETTO_CHECK(madvise_begin + madvise_size <= buf() + capacity_);
150         buf_.AdviseDontNeed(madvise_begin, madvise_size);
151       }
152     }
153   }
154   // At this point |size_| == 0 for case C, > 0 for cases A, B, D.
155   return true;
156 }
157 
PopNextFrame()158 std::unique_ptr<Frame> BufferedFrameDeserializer::PopNextFrame() {
159   if (decoded_frames_.empty())
160     return nullptr;
161   std::unique_ptr<Frame> frame = std::move(decoded_frames_.front());
162   decoded_frames_.pop_front();
163   return frame;
164 }
165 
DecodeFrame(const char * data,size_t size)166 void BufferedFrameDeserializer::DecodeFrame(const char* data, size_t size) {
167   if (size == 0)
168     return;
169   std::unique_ptr<Frame> frame(new Frame);
170   const int sz = static_cast<int>(size);
171   ::google::protobuf::io::ArrayInputStream stream(data, sz);
172   if (frame->ParseFromBoundedZeroCopyStream(&stream, sz))
173     decoded_frames_.push_back(std::move(frame));
174 }
175 
176 // static
Serialize(const Frame & frame)177 std::string BufferedFrameDeserializer::Serialize(const Frame& frame) {
178   std::string buf;
179   buf.reserve(1024);  // Just an educated guess to avoid trivial expansions.
180   buf.insert(0, kHeaderSize, 0);  // Reserve the space for the header.
181   frame.AppendToString(&buf);
182   const uint32_t payload_size = static_cast<uint32_t>(buf.size() - kHeaderSize);
183   PERFETTO_DCHECK(payload_size == static_cast<uint32_t>(frame.GetCachedSize()));
184   // Don't send messages larger than what the receiver can handle.
185   PERFETTO_DCHECK(kHeaderSize + payload_size <= kIPCBufferSize);
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
194