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 namespace google_breakpad {
49 
50 // A buffer holding a series of bytes.
51 struct ByteBuffer {
ByteBufferByteBuffer52   ByteBuffer() : start(0), end(0) { }
ByteBufferByteBuffer53   ByteBuffer(const uint8_t *set_start, size_t set_size)
54       : start(set_start), end(set_start + set_size) { }
~ByteBufferByteBuffer55   ~ByteBuffer() { };
56 
57   // Equality operators. Useful in unit tests, and when we're using
58   // ByteBuffers to refer to regions of a larger buffer.
59   bool operator==(const ByteBuffer &that) const {
60     return start == that.start && end == that.end;
61   }
62   bool operator!=(const ByteBuffer &that) const {
63     return start != that.start || end != that.end;
64   }
65 
66   // Not C++ style guide compliant, but this definitely belongs here.
SizeByteBuffer67   size_t Size() const {
68     assert(start <= end);
69     return end - start;
70   }
71 
72   const uint8_t *start, *end;
73 };
74 
75 // A cursor pointing into a ByteBuffer that can parse numbers of various
76 // widths and representations, strings, and data blocks, advancing through
77 // the buffer as it goes. All ByteCursor operations check that accesses
78 // haven't gone beyond the end of the enclosing ByteBuffer.
79 class ByteCursor {
80  public:
81   // Create a cursor reading bytes from the start of BUFFER. By default, the
82   // cursor reads multi-byte values in little-endian form.
83   ByteCursor(const ByteBuffer *buffer, bool big_endian = false)
buffer_(buffer)84       : buffer_(buffer), here_(buffer->start),
85         big_endian_(big_endian), complete_(true) { }
86 
87   // Accessor and setter for this cursor's endianness flag.
big_endian()88   bool big_endian() const { return big_endian_; }
set_big_endian(bool big_endian)89   void set_big_endian(bool big_endian) { big_endian_ = big_endian; }
90 
91   // Accessor and setter for this cursor's current position. The setter
92   // returns a reference to this cursor.
here()93   const uint8_t *here() const { return here_; }
set_here(const uint8_t * here)94   ByteCursor &set_here(const uint8_t *here) {
95     assert(buffer_->start <= here && here <= buffer_->end);
96     here_ = here;
97     return *this;
98   }
99 
100   // Return the number of bytes available to read at the cursor.
Available()101   size_t Available() const { return size_t(buffer_->end - here_); }
102 
103   // Return true if this cursor is at the end of its buffer.
AtEnd()104   bool AtEnd() const { return Available() == 0; }
105 
106   // When used as a boolean value this cursor converts to true if all
107   // prior reads have been completed, or false if we ran off the end
108   // of the buffer.
109   operator bool() const { return complete_; }
110 
111   // Read a SIZE-byte integer at this cursor, signed if IS_SIGNED is true,
112   // unsigned otherwise, using the cursor's established endianness, and set
113   // *RESULT to the number. If we read off the end of our buffer, clear
114   // this cursor's complete_ flag, and store a dummy value in *RESULT.
115   // Return a reference to this cursor.
116   template<typename T>
Read(size_t size,bool is_signed,T * result)117   ByteCursor &Read(size_t size, bool is_signed, T *result) {
118     if (CheckAvailable(size)) {
119       T v = 0;
120       if (big_endian_) {
121         for (size_t i = 0; i < size; i++)
122           v = (v << 8) + here_[i];
123       } else {
124         // This loop condition looks weird, but size_t is unsigned, so
125         // decrementing i after it is zero yields the largest size_t value.
126         for (size_t i = size - 1; i < size; i--)
127           v = (v << 8) + here_[i];
128       }
129       if (is_signed && size < sizeof(T)) {
130         size_t sign_bit = (T)1 << (size * 8 - 1);
131         v = (v ^ sign_bit) - sign_bit;
132       }
133       here_ += size;
134       *result = v;
135     } else {
136       *result = (T) 0xdeadbeef;
137     }
138     return *this;
139   }
140 
141   // Read an integer, using the cursor's established endianness and
142   // *RESULT's size and signedness, and set *RESULT to the number. If we
143   // read off the end of our buffer, clear this cursor's complete_ flag.
144   // Return a reference to this cursor.
145   template<typename T>
146   ByteCursor &operator>>(T &result) {
147     bool T_is_signed = (T)-1 < 0;
148     return Read(sizeof(T), T_is_signed, &result);
149   }
150 
151   // Copy the SIZE bytes at the cursor to BUFFER, and advance this
152   // cursor to the end of them. If we read off the end of our buffer,
153   // clear this cursor's complete_ flag, and set *POINTER to NULL.
154   // Return a reference to this cursor.
Read(uint8_t * buffer,size_t size)155   ByteCursor &Read(uint8_t *buffer, size_t size) {
156     if (CheckAvailable(size)) {
157       memcpy(buffer, here_, size);
158       here_ += size;
159     }
160     return *this;
161   }
162 
163   // Set STR to a copy of the '\0'-terminated string at the cursor. If the
164   // byte buffer does not contain a terminating zero, clear this cursor's
165   // complete_ flag, and set STR to the empty string. Return a reference to
166   // this cursor.
CString(std::string * str)167   ByteCursor &CString(std::string *str) {
168     const uint8_t *end
169       = static_cast<const uint8_t *>(memchr(here_, '\0', Available()));
170     if (end) {
171       str->assign(reinterpret_cast<const char *>(here_), end - here_);
172       here_ = end + 1;
173     } else {
174       str->clear();
175       here_ = buffer_->end;
176       complete_ = false;
177     }
178     return *this;
179   }
180 
181   // Like CString(STR), but extract the string from a fixed-width buffer
182   // LIMIT bytes long, which may or may not contain a terminating '\0'
183   // byte. Specifically:
184   //
185   // - If there are not LIMIT bytes available at the cursor, clear the
186   //   cursor's complete_ flag and set STR to the empty string.
187   //
188   // - Otherwise, if the LIMIT bytes at the cursor contain any '\0'
189   //   characters, set *STR to a copy of the bytes before the first '\0',
190   //   and advance the cursor by LIMIT bytes.
191   //
192   // - Otherwise, set *STR to a copy of those LIMIT bytes, and advance the
193   //   cursor by LIMIT bytes.
CString(std::string * str,size_t limit)194   ByteCursor &CString(std::string *str, size_t limit) {
195     if (CheckAvailable(limit)) {
196       const uint8_t *end
197         = static_cast<const uint8_t *>(memchr(here_, '\0', limit));
198       if (end)
199         str->assign(reinterpret_cast<const char *>(here_), end - here_);
200       else
201         str->assign(reinterpret_cast<const char *>(here_), limit);
202       here_ += limit;
203     } else {
204       str->clear();
205     }
206     return *this;
207   }
208 
209   // Set *POINTER to point to the SIZE bytes at the cursor, and advance
210   // this cursor to the end of them. If SIZE is omitted, don't move the
211   // cursor. If we read off the end of our buffer, clear this cursor's
212   // complete_ flag, and set *POINTER to NULL. Return a reference to this
213   // cursor.
214   ByteCursor &PointTo(const uint8_t **pointer, size_t size = 0) {
215     if (CheckAvailable(size)) {
216       *pointer = here_;
217       here_ += size;
218     } else {
219       *pointer = NULL;
220     }
221     return *this;
222   }
223 
224   // Skip SIZE bytes at the cursor. If doing so would advance us off
225   // the end of our buffer, clear this cursor's complete_ flag, and
226   // set *POINTER to NULL. Return a reference to this cursor.
Skip(size_t size)227   ByteCursor &Skip(size_t size) {
228     if (CheckAvailable(size))
229       here_ += size;
230     return *this;
231   }
232 
233  private:
234   // If there are at least SIZE bytes available to read from the buffer,
235   // return true. Otherwise, set here_ to the end of the buffer, set
236   // complete_ to false, and return false.
CheckAvailable(size_t size)237   bool CheckAvailable(size_t size) {
238     if (Available() >= size) {
239       return true;
240     } else {
241       here_ = buffer_->end;
242       complete_ = false;
243       return false;
244     }
245   }
246 
247   // The buffer we're reading bytes from.
248   const ByteBuffer *buffer_;
249 
250   // The next byte within buffer_ that we'll read.
251   const uint8_t *here_;
252 
253   // True if we should read numbers in big-endian form; false if we
254   // should read in little-endian form.
255   bool big_endian_;
256 
257   // True if we've been able to read all we've been asked to.
258   bool complete_;
259 };
260 
261 }  // namespace google_breakpad
262 
263 #endif  // COMMON_BYTE_CURSOR_H_
264