| 6 | #define BASE_PICKLE_H_ |
| 7 |
| 8 | #include <stddef.h> |
| 9 | #include <stdint.h> |
| 10 |
| 11 | #include <string> |
| 12 |
| 13 | #include "base/base_export.h" |
| 14 | #include "base/compiler_specific.h" |
| 15 | #include "base/gtest_prod_util.h" |
| 16 | #include "base/logging.h" |
| 17 | #include "base/memory/ref_counted.h" |
| 18 | #include "base/strings/string16.h" |
| 19 | #include "base/strings/string_piece.h" |
| 20 |
| 21 | namespace base { |
| 22 |
| 23 | class Pickle; |
| 24 |
| 25 | // PickleIterator reads data from a Pickle. The Pickle object must remain valid |
| 26 | // while the PickleIterator object is in use. |
| 27 | class BASE_EXPORT PickleIterator { |
| 28 | public: |
| 29 | PickleIterator() : payload_(nullptr), read_index_(0), end_index_(0) {} |
| 30 | explicit PickleIterator(const Pickle& pickle); |
| 31 |
| 32 | // Methods for reading the payload of the Pickle. To read from the start of |
| 33 | // the Pickle, create a PickleIterator from a Pickle. If successful, these |
| 34 | // methods return true. Otherwise, false is returned to indicate that the |
| 35 | // result could not be extracted. It is not possible to read from the iterator |
| 36 | // after that. |
| 37 | bool ReadBool(bool* result) WARN_UNUSED_RESULT; |
| 38 | bool ReadInt(int* result) WARN_UNUSED_RESULT; |
| 39 | bool ReadLong(long* result) WARN_UNUSED_RESULT; |
| 40 | bool ReadUInt16(uint16_t* result) WARN_UNUSED_RESULT; |
| 41 | bool ReadUInt32(uint32_t* result) WARN_UNUSED_RESULT; |
| 42 | bool ReadInt64(int64_t* result) WARN_UNUSED_RESULT; |
| 43 | bool ReadUInt64(uint64_t* result) WARN_UNUSED_RESULT; |
| 44 | bool ReadFloat(float* result) WARN_UNUSED_RESULT; |
| 45 | bool ReadDouble(double* result) WARN_UNUSED_RESULT; |
| 46 | bool ReadString(std::string* result) WARN_UNUSED_RESULT; |
| 47 | // The StringPiece data will only be valid for the lifetime of the message. |
| 48 | bool ReadStringPiece(StringPiece* result) WARN_UNUSED_RESULT; |
| 49 | bool ReadString16(string16* result) WARN_UNUSED_RESULT; |
| 50 | // The StringPiece16 data will only be valid for the lifetime of the message. |
| 51 | bool ReadStringPiece16(StringPiece16* result) WARN_UNUSED_RESULT; |
| 52 |
| 53 | // A pointer to the data will be placed in |*data|, and the length will be |
| 54 | // placed in |*length|. The pointer placed into |*data| points into the |
| 55 | // message's buffer so it will be scoped to the lifetime of the message (or |
| 56 | // until the message data is mutated). Do not keep the pointer around! |
| 57 | bool ReadData(const char** data, int* length) WARN_UNUSED_RESULT; |
| 58 |
| 59 | // A pointer to the data will be placed in |*data|. The caller specifies the |
| 60 | // number of bytes to read, and ReadBytes will validate this length. The |
| 61 | // pointer placed into |*data| points into the message's buffer so it will be |
| 62 | // scoped to the lifetime of the message (or until the message data is |
| 63 | // mutated). Do not keep the pointer around! |
| 64 | bool ReadBytes(const char** data, int length) WARN_UNUSED_RESULT; |
| 65 |
| 66 | // A safer version of ReadInt() that checks for the result not being negative. |
| 67 | // Use it for reading the object sizes. |
| 68 | bool ReadLength(int* result) WARN_UNUSED_RESULT { |
| 69 | return ReadInt(result) && *result >= 0; |
| 70 | } |
| 71 |
| 72 | // Skips bytes in the read buffer and returns true if there are at least |
| 73 | // num_bytes available. Otherwise, does nothing and returns false. |
| 74 | bool SkipBytes(int num_bytes) WARN_UNUSED_RESULT { |
| 75 | return !!GetReadPointerAndAdvance(num_bytes); |
| 76 | } |
| 77 |
| 78 | bool ReachedEnd() const { return read_index_ == end_index_; } |
| 79 |
| 80 | private: |
| 81 | // Read Type from Pickle. |
| 82 | template <typename Type> |
| 83 | bool ReadBuiltinType(Type* result); |
| 84 |
| 85 | // Advance read_index_ but do not allow it to exceed end_index_. |
| 86 | // Keeps read_index_ aligned. |
| 87 | void Advance(size_t size); |
| 88 |
| 89 | // Get read pointer for Type and advance read pointer. |
| 90 | template<typename Type> |
| 91 | const char* GetReadPointerAndAdvance(); |
| 92 |
| 93 | // Get read pointer for |num_bytes| and advance read pointer. This method |
| 94 | // checks num_bytes for negativity and wrapping. |
| 95 | const char* GetReadPointerAndAdvance(int num_bytes); |
| 96 |
| 97 | // Get read pointer for (num_elements * size_element) bytes and advance read |
| 98 | // pointer. This method checks for int overflow, negativity and wrapping. |
| 99 | const char* GetReadPointerAndAdvance(int num_elements, |
| 100 | size_t size_element); |
| 101 |
| 102 | const char* payload_; // Start of our pickle's payload. |
| 103 | size_t read_index_; // Offset of the next readable byte in payload. |
| 104 | size_t end_index_; // Payload size. |
| 105 |
| 106 | FRIEND_TEST_ALL_PREFIXES(PickleTest, GetReadPointerAndAdvance); |
| 107 | }; |
| 108 |
| 109 | // This class provides facilities for basic binary value packing and unpacking. |
| 110 | // |
| 111 | // The Pickle class supports appending primitive values (ints, strings, etc.) |
| 112 | // to a pickle instance. The Pickle instance grows its internal memory buffer |
| 113 | // dynamically to hold the sequence of primitive values. The internal memory |
| 114 | // buffer is exposed as the "data" of the Pickle. This "data" can be passed |
| 115 | // to a Pickle object to initialize it for reading. |
| 116 | // |
| 117 | // When reading from a Pickle object, it is important for the consumer to know |
| 118 | // what value types to read and in what order to read them as the Pickle does |
| 119 | // not keep track of the type of data written to it. |
| 120 | // |
| 121 | // The Pickle's data has a header which contains the size of the Pickle's |
| 122 | // payload. It can optionally support additional space in the header. That |
| 123 | // space is controlled by the header_size parameter passed to the Pickle |
| 124 | // constructor. |
| 125 | // |
| 126 | class BASE_EXPORT Pickle { |
| 127 | public: |
| 128 | // Auxiliary data attached to a Pickle. Pickle must be subclassed along with |
| 129 | // this interface in order to provide a concrete implementation of support |
| 130 | // for attachments. The base Pickle implementation does not accept |
| 131 | // attachments. |
| 132 | class BASE_EXPORT Attachment : public RefCountedThreadSafe<Attachment> { |
| 133 | public: |
| 134 | Attachment(); |
| 135 |
| 136 | protected: |
| 137 | friend class RefCountedThreadSafe<Attachment>; |
| 138 | virtual ~Attachment(); |
| 139 |
| 140 | DISALLOW_COPY_AND_ASSIGN(Attachment); |
| 141 | }; |
| 142 |
| 143 | // Initialize a Pickle object using the default header size. |
| 144 | Pickle(); |
| 145 |
| 146 | // Initialize a Pickle object with the specified header size in bytes, which |
| 147 | // must be greater-than-or-equal-to sizeof(Pickle::Header). The header size |
| 148 | // will be rounded up to ensure that the header size is 32bit-aligned. |
| 149 | explicit Pickle(int header_size); |
| 150 |
| 151 | // Initializes a Pickle from a const block of data. The data is not copied; |
| 152 | // instead the data is merely referenced by this Pickle. Only const methods |
| 153 | // should be used on the Pickle when initialized this way. The header |
| 154 | // padding size is deduced from the data length. |
| 155 | Pickle(const char* data, size_t data_len); |
| 156 |
| 157 | // Initializes a Pickle as a deep copy of another Pickle. |
| 158 | Pickle(const Pickle& other); |
| 159 |
| 160 | // Note: There are no virtual methods in this class. This destructor is |
| 161 | // virtual as an element of defensive coding. Other classes have derived from |
| 162 | // this class, and there is a *chance* that they will cast into this base |
| 163 | // class before destruction. At least one such class does have a virtual |
| 164 | // destructor, suggesting at least some need to call more derived destructors. |
| 165 | virtual ~Pickle(); |
| 166 |
| 167 | // Performs a deep copy. |
| 168 | Pickle& operator=(const Pickle& other); |
| 169 |
| 170 | // Returns the number of bytes written in the Pickle, including the header. |
| 171 | size_t size() const { return header_size_ + header_->payload_size; } |
| 172 |
| 173 | // Returns the data for this Pickle. |
| 174 | const void* data() const { return header_; } |
| 175 |
| 176 | // Returns the effective memory capacity of this Pickle, that is, the total |
| 177 | // number of bytes currently dynamically allocated or 0 in the case of a |
| 178 | // read-only Pickle. This should be used only for diagnostic / profiling |
| 179 | // purposes. |
| 180 | size_t GetTotalAllocatedSize() const; |
| 181 |
| 182 | // Methods for adding to the payload of the Pickle. These values are |
| 183 | // appended to the end of the Pickle's payload. When reading values from a |
| 184 | // Pickle, it is important to read them in the order in which they were added |
| 185 | // to the Pickle. |
| 186 |
| 187 | void WriteBool(bool value) { WriteInt(value ? 1 : 0); } |
| 188 | void WriteInt(int value) { WritePOD(value); } |
| 189 | void WriteLong(long value) { |
| 190 | // Always write long as a 64-bit value to ensure compatibility between |
| 191 | // 32-bit and 64-bit processes. |
| 192 | WritePOD(static_cast<int64_t>(value)); |
| 193 | } |
| 194 | void WriteUInt16(uint16_t value) { WritePOD(value); } |
| 195 | void WriteUInt32(uint32_t value) { WritePOD(value); } |
| 196 | void WriteInt64(int64_t value) { WritePOD(value); } |
| 197 | void WriteUInt64(uint64_t value) { WritePOD(value); } |
| 198 | void WriteFloat(float value) { WritePOD(value); } |
| 199 | void WriteDouble(double value) { WritePOD(value); } |
| 200 | void WriteString(const StringPiece& value); |
| 201 | void WriteString16(const StringPiece16& value); |
| 202 | // "Data" is a blob with a length. When you read it out you will be given the |
| 203 | // length. See also WriteBytes. |
| 204 | void WriteData(const char* data, int length); |
| 205 | // "Bytes" is a blob with no length. The caller must specify the length both |
| 206 | // when reading and writing. It is normally used to serialize PoD types of a |
| 207 | // known size. See also WriteData. |
| 208 | void WriteBytes(const void* data, int length); |
| 209 |
| 210 | // WriteAttachment appends |attachment| to the pickle. It returns |
| 211 | // false iff the set is full or if the Pickle implementation does not support |
| 212 | // attachments. |
| 213 | virtual bool WriteAttachment(scoped_refptr<Attachment> attachment); |
| 214 |
| 215 | // ReadAttachment parses an attachment given the parsing state |iter| and |
| 216 | // writes it to |*attachment|. It returns true on success. |
| 217 | virtual bool ReadAttachment(base::PickleIterator* iter, |
| 218 | scoped_refptr<Attachment>* attachment) const; |
| 219 |
| 220 | // Indicates whether the pickle has any attachments. |
| 221 | virtual bool HasAttachments() const; |
| 222 |
| 223 | // Reserves space for upcoming writes when multiple writes will be made and |
| 224 | // their sizes are computed in advance. It can be significantly faster to call |
| 225 | // Reserve() before calling WriteFoo() multiple times. |
| 226 | void Reserve(size_t additional_capacity); |
| 227 |
| 228 | // Payload follows after allocation of Header (header size is customizable). |
| 229 | struct Header { |
| 230 | uint32_t payload_size; // Specifies the size of the payload. |
| 231 | }; |
| 232 |
| 233 | // Returns the header, cast to a user-specified type T. The type T must be a |
| 234 | // subclass of Header and its size must correspond to the header_size passed |
| 235 | // to the Pickle constructor. |
| 236 | template <class T> |
| 237 | T* headerT() { |
| 238 | DCHECK_EQ(header_size_, sizeof(T)); |
| 239 | return static_cast<T*>(header_); |
| 240 | } |
| 241 | template <class T> |
| 242 | const T* headerT() const { |
| 243 | DCHECK_EQ(header_size_, sizeof(T)); |
| 244 | return static_cast<const T*>(header_); |
| 245 | } |
| 246 |
| 247 | // The payload is the pickle data immediately following the header. |
| 248 | size_t payload_size() const { |
| 249 | return header_ ? header_->payload_size : 0; |
| 250 | } |
| 251 |
| 252 | const char* payload() const { |
| 253 | return reinterpret_cast<const char*>(header_) + header_size_; |
| 254 | } |
| 255 |
| 256 | // Returns the address of the byte immediately following the currently valid |
| 257 | // header + payload. |
| 258 | const char* end_of_payload() const { |
| 259 | // This object may be invalid. |
| 260 | return header_ ? payload() + payload_size() : NULL; |
| 261 | } |
| 262 |
| 263 | protected: |
| 264 | // Returns size of the header, which can have default value, set by user or |
| 265 | // calculated by passed raw data. |
| 266 | size_t header_size() const { return header_size_; } |
| 267 |
| 268 | char* mutable_payload() { |
| 269 | return reinterpret_cast<char*>(header_) + header_size_; |
| 270 | } |
| 271 |
| 272 | size_t capacity_after_header() const { |
| 273 | return capacity_after_header_; |
| 274 | } |
| 275 |
| 276 | // Resize the capacity, note that the input value should not include the size |
| 277 | // of the header. |
| 278 | void Resize(size_t new_capacity); |
| 279 |
| 280 | // Claims |num_bytes| bytes of payload. This is similar to Reserve() in that |
| 281 | // it may grow the capacity, but it also advances the write offset of the |
| 282 | // pickle by |num_bytes|. Claimed memory, including padding, is zeroed. |
| 283 | // |
| 284 | // Returns the address of the first byte claimed. |
| 285 | void* ClaimBytes(size_t num_bytes); |
| 286 |
| 287 | // Find the end of the pickled data that starts at range_start. Returns NULL |
| 288 | // if the entire Pickle is not found in the given data range. |
| 289 | static const char* FindNext(size_t header_size, |
| 290 | const char* range_start, |
| 291 | const char* range_end); |
| 292 |
| 293 | // Parse pickle header and return total size of the pickle. Data range |
| 294 | // doesn't need to contain entire pickle. |
| 295 | // Returns true if pickle header was found and parsed. Callers must check |
| 296 | // returned |pickle_size| for sanity (against maximum message size, etc). |
| 297 | // NOTE: when function successfully parses a header, but encounters an |
| 298 | // overflow during pickle size calculation, it sets |pickle_size| to the |
| 299 | // maximum size_t value and returns true. |
| 300 | static bool PeekNext(size_t header_size, |
| 301 | const char* range_start, |
| 302 | const char* range_end, |
| 303 | size_t* pickle_size); |
| 304 |
| 305 | // The allocation granularity of the payload. |
| 306 | static const int kPayloadUnit; |
| 307 |
| 308 | private: |
| 309 | friend class PickleIterator; |
| 310 |
| 311 | Header* header_; |
| 312 | size_t header_size_; // Supports extra data between header and payload. |
| 313 | // Allocation size of payload (or -1 if allocation is const). Note: this |
| 314 | // doesn't count the header. |
| 315 | size_t capacity_after_header_; |
| 316 | // The offset at which we will write the next field. Note: this doesn't count |
| 317 | // the header. |
| 318 | size_t write_offset_; |
| 319 |
| 320 | // Just like WriteBytes, but with a compile-time size, for performance. |
| 321 | template<size_t length> void BASE_EXPORT WriteBytesStatic(const void* data); |
| 322 |
| 323 | // Writes a POD by copying its bytes. |
| 324 | template <typename T> bool WritePOD(const T& data) { |
| 325 | WriteBytesStatic<sizeof(data)>(&data); |
| 326 | return true; |
| 327 | } |
| 328 |
| 329 | inline void* ClaimUninitializedBytesInternal(size_t num_bytes); |
| 330 | inline void WriteBytesCommon(const void* data, size_t length); |
| 331 |
| 332 | FRIEND_TEST_ALL_PREFIXES(PickleTest, DeepCopyResize); |
| 333 | FRIEND_TEST_ALL_PREFIXES(PickleTest, Resize); |
| 334 | FRIEND_TEST_ALL_PREFIXES(PickleTest, PeekNext); |
| 335 | FRIEND_TEST_ALL_PREFIXES(PickleTest, PeekNextOverflow); |
| 336 | FRIEND_TEST_ALL_PREFIXES(PickleTest, FindNext); |
| 337 | FRIEND_TEST_ALL_PREFIXES(PickleTest, FindNextWithIncompleteHeader); |
| 338 | FRIEND_TEST_ALL_PREFIXES(PickleTest, FindNextOverflow); |
| 339 | }; |
| 340 |
| 341 | } // namespace base |
| 342 |
| 343 | #endif // BASE_PICKLE_H_ |
| 344 |