• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // -*- mode: c++ -*-
2 
3 // Copyright (c) 2010, Google Inc.
4 // All rights reserved.
5 //
6 // Redistribution and use in source and binary forms, with or without
7 // modification, are permitted provided that the following conditions are
8 // met:
9 //
10 //     * Redistributions of source code must retain the above copyright
11 // notice, this list of conditions and the following disclaimer.
12 //     * Redistributions in binary form must reproduce the above
13 // copyright notice, this list of conditions and the following disclaimer
14 // in the documentation and/or other materials provided with the
15 // distribution.
16 //     * Neither the name of Google Inc. nor the names of its
17 // contributors may be used to endorse or promote products derived from
18 // this software without specific prior written permission.
19 //
20 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 
32 // Original author: Jim Blandy <jimb@mozilla.com> <jimb@red-bean.com>
33 
34 // byte_cursor.h: Classes for parsing values from a buffer of bytes.
35 // The ByteCursor class provides a convenient interface for reading
36 // fixed-size integers of arbitrary endianness, being thorough about
37 // checking for buffer overruns.
38 
39 #ifndef COMMON_BYTE_CURSOR_H_
40 #define COMMON_BYTE_CURSOR_H_
41 
42 #include <assert.h>
43 #include <stdint.h>
44 #include <stdlib.h>
45 #include <string.h>
46 #include <string>
47 
48 #include "common/using_std_string.h"
49 
50 namespace google_breakpad {
51 
52 // A buffer holding a series of bytes.
53 struct ByteBuffer {
ByteBufferByteBuffer54   ByteBuffer() : start(0), end(0) { }
ByteBufferByteBuffer55   ByteBuffer(const uint8_t *set_start, size_t set_size)
56       : start(set_start), end(set_start + set_size) { }
~ByteBufferByteBuffer57   ~ByteBuffer() { };
58 
59   // Equality operators. Useful in unit tests, and when we're using
60   // ByteBuffers to refer to regions of a larger buffer.
61   bool operator==(const ByteBuffer &that) const {
62     return start == that.start && end == that.end;
63   }
64   bool operator!=(const ByteBuffer &that) const {
65     return start != that.start || end != that.end;
66   }
67 
68   // Not C++ style guide compliant, but this definitely belongs here.
SizeByteBuffer69   size_t Size() const {
70     assert(start <= end);
71     return end - start;
72   }
73 
74   const uint8_t *start, *end;
75 };
76 
77 // A cursor pointing into a ByteBuffer that can parse numbers of various
78 // widths and representations, strings, and data blocks, advancing through
79 // the buffer as it goes. All ByteCursor operations check that accesses
80 // haven't gone beyond the end of the enclosing ByteBuffer.
81 class ByteCursor {
82  public:
83   // Create a cursor reading bytes from the start of BUFFER. By default, the
84   // cursor reads multi-byte values in little-endian form.
85   ByteCursor(const ByteBuffer *buffer, bool big_endian = false)
buffer_(buffer)86       : buffer_(buffer), here_(buffer->start),
87         big_endian_(big_endian), complete_(true) { }
88 
89   // Accessor and setter for this cursor's endianness flag.
big_endian()90   bool big_endian() const { return big_endian_; }
set_big_endian(bool big_endian)91   void set_big_endian(bool big_endian) { big_endian_ = big_endian; }
92 
93   // Accessor and setter for this cursor's current position. The setter
94   // returns a reference to this cursor.
here()95   const uint8_t *here() const { return here_; }
set_here(const uint8_t * here)96   ByteCursor &set_here(const uint8_t *here) {
97     assert(buffer_->start <= here && here <= buffer_->end);
98     here_ = here;
99     return *this;
100   }
101 
102   // Return the number of bytes available to read at the cursor.
Available()103   size_t Available() const { return size_t(buffer_->end - here_); }
104 
105   // Return true if this cursor is at the end of its buffer.
AtEnd()106   bool AtEnd() const { return Available() == 0; }
107 
108   // When used as a boolean value this cursor converts to true if all
109   // prior reads have been completed, or false if we ran off the end
110   // of the buffer.
111   operator bool() const { return complete_; }
112 
113   // Read a SIZE-byte integer at this cursor, signed if IS_SIGNED is true,
114   // unsigned otherwise, using the cursor's established endianness, and set
115   // *RESULT to the number. If we read off the end of our buffer, clear
116   // this cursor's complete_ flag, and store a dummy value in *RESULT.
117   // Return a reference to this cursor.
118   template<typename T>
Read(size_t size,bool is_signed,T * result)119   ByteCursor &Read(size_t size, bool is_signed, T *result) {
120     if (CheckAvailable(size)) {
121       T v = 0;
122       if (big_endian_) {
123         for (size_t i = 0; i < size; i++)
124           v = (v << 8) + here_[i];
125       } else {
126         // This loop condition looks weird, but size_t is unsigned, so
127         // decrementing i after it is zero yields the largest size_t value.
128         for (size_t i = size - 1; i < size; i--)
129           v = (v << 8) + here_[i];
130       }
131       if (is_signed && size < sizeof(T)) {
132         size_t sign_bit = (T)1 << (size * 8 - 1);
133         v = (v ^ sign_bit) - sign_bit;
134       }
135       here_ += size;
136       *result = v;
137     } else {
138       *result = (T) 0xdeadbeef;
139     }
140     return *this;
141   }
142 
143   // Read an integer, using the cursor's established endianness and
144   // *RESULT's size and signedness, and set *RESULT to the number. If we
145   // read off the end of our buffer, clear this cursor's complete_ flag.
146   // Return a reference to this cursor.
147   template<typename T>
148   ByteCursor &operator>>(T &result) {
149     bool T_is_signed = (T)-1 < 0;
150     return Read(sizeof(T), T_is_signed, &result);
151   }
152 
153   // Copy the SIZE bytes at the cursor to BUFFER, and advance this
154   // cursor to the end of them. If we read off the end of our buffer,
155   // clear this cursor's complete_ flag, and set *POINTER to NULL.
156   // Return a reference to this cursor.
Read(uint8_t * buffer,size_t size)157   ByteCursor &Read(uint8_t *buffer, size_t size) {
158     if (CheckAvailable(size)) {
159       memcpy(buffer, here_, size);
160       here_ += size;
161     }
162     return *this;
163   }
164 
165   // Set STR to a copy of the '\0'-terminated string at the cursor. If the
166   // byte buffer does not contain a terminating zero, clear this cursor's
167   // complete_ flag, and set STR to the empty string. Return a reference to
168   // this cursor.
CString(string * str)169   ByteCursor &CString(string *str) {
170     const uint8_t *end
171       = static_cast<const uint8_t *>(memchr(here_, '\0', Available()));
172     if (end) {
173       str->assign(reinterpret_cast<const char *>(here_), end - here_);
174       here_ = end + 1;
175     } else {
176       str->clear();
177       here_ = buffer_->end;
178       complete_ = false;
179     }
180     return *this;
181   }
182 
183   // Like CString(STR), but extract the string from a fixed-width buffer
184   // LIMIT bytes long, which may or may not contain a terminating '\0'
185   // byte. Specifically:
186   //
187   // - If there are not LIMIT bytes available at the cursor, clear the
188   //   cursor's complete_ flag and set STR to the empty string.
189   //
190   // - Otherwise, if the LIMIT bytes at the cursor contain any '\0'
191   //   characters, set *STR to a copy of the bytes before the first '\0',
192   //   and advance the cursor by LIMIT bytes.
193   //
194   // - Otherwise, set *STR to a copy of those LIMIT bytes, and advance the
195   //   cursor by LIMIT bytes.
CString(string * str,size_t limit)196   ByteCursor &CString(string *str, size_t limit) {
197     if (CheckAvailable(limit)) {
198       const uint8_t *end
199         = static_cast<const uint8_t *>(memchr(here_, '\0', limit));
200       if (end)
201         str->assign(reinterpret_cast<const char *>(here_), end - here_);
202       else
203         str->assign(reinterpret_cast<const char *>(here_), limit);
204       here_ += limit;
205     } else {
206       str->clear();
207     }
208     return *this;
209   }
210 
211   // Set *POINTER to point to the SIZE bytes at the cursor, and advance
212   // this cursor to the end of them. If SIZE is omitted, don't move the
213   // cursor. If we read off the end of our buffer, clear this cursor's
214   // complete_ flag, and set *POINTER to NULL. Return a reference to this
215   // cursor.
216   ByteCursor &PointTo(const uint8_t **pointer, size_t size = 0) {
217     if (CheckAvailable(size)) {
218       *pointer = here_;
219       here_ += size;
220     } else {
221       *pointer = NULL;
222     }
223     return *this;
224   }
225 
226   // Skip SIZE bytes at the cursor. If doing so would advance us off
227   // the end of our buffer, clear this cursor's complete_ flag, and
228   // set *POINTER to NULL. Return a reference to this cursor.
Skip(size_t size)229   ByteCursor &Skip(size_t size) {
230     if (CheckAvailable(size))
231       here_ += size;
232     return *this;
233   }
234 
235  private:
236   // If there are at least SIZE bytes available to read from the buffer,
237   // return true. Otherwise, set here_ to the end of the buffer, set
238   // complete_ to false, and return false.
CheckAvailable(size_t size)239   bool CheckAvailable(size_t size) {
240     if (Available() >= size) {
241       return true;
242     } else {
243       here_ = buffer_->end;
244       complete_ = false;
245       return false;
246     }
247   }
248 
249   // The buffer we're reading bytes from.
250   const ByteBuffer *buffer_;
251 
252   // The next byte within buffer_ that we'll read.
253   const uint8_t *here_;
254 
255   // True if we should read numbers in big-endian form; false if we
256   // should read in little-endian form.
257   bool big_endian_;
258 
259   // True if we've been able to read all we've been asked to.
260   bool complete_;
261 };
262 
263 }  // namespace google_breakpad
264 
265 #endif  // COMMON_BYTE_CURSOR_H_
266