/ src / common / byte_cursor.h
byte_cursor.h
  1  // -*- mode: c++ -*-
  2  
  3  // Copyright 2010 Google LLC
  4  //
  5  // Redistribution and use in source and binary forms, with or without
  6  // modification, are permitted provided that the following conditions are
  7  // met:
  8  //
  9  //     * Redistributions of source code must retain the above copyright
 10  // notice, this list of conditions and the following disclaimer.
 11  //     * Redistributions in binary form must reproduce the above
 12  // copyright notice, this list of conditions and the following disclaimer
 13  // in the documentation and/or other materials provided with the
 14  // distribution.
 15  //     * Neither the name of Google LLC nor the names of its
 16  // contributors may be used to endorse or promote products derived from
 17  // this software without specific prior written permission.
 18  //
 19  // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 20  // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 21  // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 22  // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 23  // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 24  // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 25  // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 26  // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 27  // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 28  // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 29  // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 30  
 31  // Original author: Jim Blandy <jimb@mozilla.com> <jimb@red-bean.com>
 32  
 33  // byte_cursor.h: Classes for parsing values from a buffer of bytes.
 34  // The ByteCursor class provides a convenient interface for reading
 35  // fixed-size integers of arbitrary endianness, being thorough about
 36  // checking for buffer overruns.
 37  
 38  #ifndef COMMON_BYTE_CURSOR_H_
 39  #define COMMON_BYTE_CURSOR_H_
 40  
 41  #include <assert.h>
 42  #include <stdint.h>
 43  #include <stdlib.h>
 44  #include <string.h>
 45  #include <string>
 46  
 47  #include "common/using_std_string.h"
 48  
 49  namespace google_breakpad {
 50  
 51  // A buffer holding a series of bytes.
 52  struct ByteBuffer {
 53    ByteBuffer() : start(0), end(0) { }
 54    ByteBuffer(const uint8_t* set_start, size_t set_size)
 55        : start(set_start), end(set_start + set_size) { }
 56    ~ByteBuffer() { };
 57  
 58    // Equality operators. Useful in unit tests, and when we're using
 59    // ByteBuffers to refer to regions of a larger buffer.
 60    bool operator==(const ByteBuffer& that) const {
 61      return start == that.start && end == that.end;
 62    }
 63    bool operator!=(const ByteBuffer& that) const {
 64      return start != that.start || end != that.end;
 65    }
 66  
 67    // Not C++ style guide compliant, but this definitely belongs here.
 68    size_t Size() const {
 69      assert(start <= end);
 70      return end - start;
 71    }
 72  
 73    const uint8_t* start;
 74    const uint8_t* 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)
 86        : buffer_(buffer), here_(buffer->start),
 87          big_endian_(big_endian), complete_(true) { }
 88  
 89    // Accessor and setter for this cursor's endianness flag.
 90    bool big_endian() const { return 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.
 95    const uint8_t* here() const { return 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.
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.
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>
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.
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.
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.
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.
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.
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_