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