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.
5 #include "mojo/public/cpp/bindings/lib/bounds_checker.h"
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"
14 BoundsChecker::BoundsChecker(const void* data
, uint32_t data_num_bytes
,
16 : data_begin_(reinterpret_cast<uintptr_t>(data
)),
17 data_end_(data_begin_
+ data_num_bytes
),
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_
;
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";
35 BoundsChecker::~BoundsChecker() {
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
;
42 if (!InternalIsValidRange(begin
, end
))
49 bool BoundsChecker::ClaimHandle(const Handle
& encoded_handle
) {
50 uint32_t index
= encoded_handle
.value();
51 if (index
== kEncodedInvalidHandleValue
)
54 if (index
< handle_begin_
|| index
>= handle_end_
)
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;
63 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
;
68 return InternalIsValidRange(begin
, end
);
71 bool BoundsChecker::InternalIsValidRange(uintptr_t begin
, uintptr_t end
) const {
72 return end
> begin
&& begin
>= data_begin_
&& end
<= data_end_
;
75 } // namespace internal