Home | History | Annotate | Download | only in ipc
      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 #ifndef SRC_IPC_BUFFERED_FRAME_DESERIALIZER_H_
     18 #define SRC_IPC_BUFFERED_FRAME_DESERIALIZER_H_
     19 
     20 #include <stddef.h>
     21 
     22 #include <list>
     23 #include <memory>
     24 
     25 #include <sys/mman.h>
     26 
     27 #include "perfetto/base/page_allocator.h"
     28 #include "perfetto/ipc/basic_types.h"
     29 
     30 namespace perfetto {
     31 namespace ipc {
     32 
     33 class Frame;  // Defined in the protobuf autogenerated wire_protocol.pb.h.
     34 
     35 // Deserializes incoming frames, taking care of buffering and tokenization.
     36 // Used by both host and client to decode incoming frames.
     37 //
     38 // Which problem does it solve?
     39 // ----------------------------
     40 // The wire protocol is as follows:
     41 // [32-bit frame size][proto-encoded Frame], e.g:
     42 // [06 00 00 00][00 11 22 33 44 55 66]
     43 // [02 00 00 00][AA BB]
     44 // [04 00 00 00][CC DD EE FF]
     45 // However, given that the socket works in SOCK_STREAM mode, the recv() calls
     46 // might see the following:
     47 // 06 00 00
     48 // 00 00 11 22 33 44 55
     49 // 66 02 00 00 00 ...
     50 // This class takes care of buffering efficiently the data received, without
     51 // making any assumption on how the incoming data will be chunked by the socket.
     52 // For instance, it is possible that a recv() doesn't produce any frame (because
     53 // it received only a part of the frame) or produces more than one frame.
     54 //
     55 // Usage
     56 // -----
     57 // Both host and client use this as follows:
     58 //
     59 // auto buf = rpc_frame_decoder.BeginReceive();
     60 // size_t rsize = socket.recv(buf.first, buf.second);
     61 // rpc_frame_decoder.EndReceive(rsize);
     62 // while (Frame frame = rpc_frame_decoder.PopNextFrame()) {
     63 //   ... process |frame|
     64 // }
     65 //
     66 // Design goals:
     67 // -------------
     68 // - Optimize for the realistic case of each recv() receiving one or more
     69 //   whole frames. In this case no memmove is performed.
     70 // - Guarantee that frames lay in a virtually contiguous memory area.
     71 //   This allows to use the protobuf-lite deserialization API (scattered
     72 //   deserialization is supported only by libprotobuf-full).
     73 // - Put a hard boundary to the size of the incoming buffer. This is to prevent
     74 //   that a malicious sends an abnormally large frame and OOMs us.
     75 // - Simplicity: just use a linear mmap region. No reallocations or scattering.
     76 //   Takes care of madvise()-ing unused memory.
     77 
     78 class BufferedFrameDeserializer {
     79  public:
     80   struct ReceiveBuffer {
     81     char* data;
     82     size_t size;
     83   };
     84 
     85   // |max_capacity| is overridable only for tests.
     86   explicit BufferedFrameDeserializer(size_t max_capacity = kIPCBufferSize);
     87   ~BufferedFrameDeserializer();
     88 
     89   // This function doesn't really belong here as it does Serialization, unlike
     90   // the rest of this class. However it is so small and has so many dependencies
     91   // in common that doesn't justify having its own class.
     92   static std::string Serialize(const Frame&);
     93 
     94   // Returns a buffer that can be passed to recv(). The buffer is deliberately
     95   // not initialized.
     96   ReceiveBuffer BeginReceive();
     97 
     98   // Must be called soon after BeginReceive().
     99   // |recv_size| is the number of valid bytes that have been written into the
    100   // buffer previously returned by BeginReceive() (the return value of recv()).
    101   // Returns false if a header > |max_capacity| is received, in which case the
    102   // caller is expected to shutdown the socket and terminate the ipc.
    103   bool EndReceive(size_t recv_size) __attribute__((warn_unused_result));
    104 
    105   // Decodes and returns the next decoded frame in the buffer if any, nullptr
    106   // if no further frames have been decoded.
    107   std::unique_ptr<Frame> PopNextFrame();
    108 
    109   size_t capacity() const { return capacity_; }
    110   size_t size() const { return size_; }
    111 
    112  private:
    113   BufferedFrameDeserializer(const BufferedFrameDeserializer&) = delete;
    114   BufferedFrameDeserializer& operator=(const BufferedFrameDeserializer&) =
    115       delete;
    116 
    117   // If a valid frame is decoded it is added to |decoded_frames_|.
    118   void DecodeFrame(const char*, size_t);
    119 
    120   char* buf() { return reinterpret_cast<char*>(buf_.get()); }
    121 
    122   base::PageAllocator::UniquePtr buf_;
    123   const size_t capacity_ = 0;  // sizeof(|buf_|).
    124 
    125   // THe number of bytes in |buf_| that contain valid data (as a result of
    126   // EndReceive()). This is always <= |capacity_|.
    127   size_t size_ = 0;
    128 
    129   std::list<std::unique_ptr<Frame>> decoded_frames_;
    130 };
    131 
    132 }  // namespace ipc
    133 }  // namespace perfetto
    134 
    135 #endif  // SRC_IPC_BUFFERED_FRAME_DESERIALIZER_H_
    136