1 // Copyright 2014 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
5 #include "mojo/public/cpp/bindings/lib/bounds_checker.h"
6
7 #include "mojo/public/cpp/bindings/lib/bindings_serialization.h"
8 #include "mojo/public/cpp/environment/logging.h"
9 #include "mojo/public/cpp/system/handle.h"
10
11 namespace mojo {
12 namespace internal {
13
BoundsChecker(const void * data,uint32_t data_num_bytes,size_t num_handles)14 BoundsChecker::BoundsChecker(const void* data, uint32_t data_num_bytes,
15 size_t num_handles)
16 : data_begin_(reinterpret_cast<uintptr_t>(data)),
17 data_end_(data_begin_ + data_num_bytes),
18 handle_begin_(0),
19 handle_end_(static_cast<uint32_t>(num_handles)) {
20 if (data_end_ < data_begin_) {
21 // The calculation of |data_end_| overflowed.
22 // It shouldn't happen but if it does, set the range to empty so
23 // IsValidRange() and ClaimMemory() always fail.
24 MOJO_DCHECK(false) << "Not reached";
25 data_end_ = data_begin_;
26 }
27 if (handle_end_ < num_handles) {
28 // Assigning |num_handles| to |handle_end_| overflowed.
29 // It shouldn't happen but if it does, set the handle index range to empty.
30 MOJO_DCHECK(false) << "Not reached";
31 handle_end_ = 0;
32 }
33 }
34
~BoundsChecker()35 BoundsChecker::~BoundsChecker() {
36 }
37
ClaimMemory(const void * position,uint32_t num_bytes)38 bool BoundsChecker::ClaimMemory(const void* position, uint32_t num_bytes) {
39 uintptr_t begin = reinterpret_cast<uintptr_t>(position);
40 uintptr_t end = begin + num_bytes;
41
42 if (!InternalIsValidRange(begin, end))
43 return false;
44
45 data_begin_ = end;
46 return true;
47 }
48
ClaimHandle(const Handle & encoded_handle)49 bool BoundsChecker::ClaimHandle(const Handle& encoded_handle) {
50 uint32_t index = encoded_handle.value();
51 if (index == kEncodedInvalidHandleValue)
52 return true;
53
54 if (index < handle_begin_ || index >= handle_end_)
55 return false;
56
57 // |index| + 1 shouldn't overflow, because |index| is not the max value of
58 // uint32_t (it is less than |handle_end_|).
59 handle_begin_ = index + 1;
60 return true;
61 }
62
IsValidRange(const void * position,uint32_t num_bytes) const63 bool BoundsChecker::IsValidRange(const void* position,
64 uint32_t num_bytes) const {
65 uintptr_t begin = reinterpret_cast<uintptr_t>(position);
66 uintptr_t end = begin + num_bytes;
67
68 return InternalIsValidRange(begin, end);
69 }
70
InternalIsValidRange(uintptr_t begin,uintptr_t end) const71 bool BoundsChecker::InternalIsValidRange(uintptr_t begin, uintptr_t end) const {
72 return end > begin && begin >= data_begin_ && end <= data_end_;
73 }
74
75 } // namespace internal
76 } // namespace mojo
77