pickle.h 14 KB

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