Android-cuttlefish cvd tool
scoped_mmap.h
Go to the documentation of this file.
1/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#ifndef CUTTLEFISH_COMMON_COMMON_LIBS_FS_SCOPED_MMAP_H
18#define CUTTLEFISH_COMMON_COMMON_LIBS_FS_SCOPED_MMAP_H
19
20#include <stddef.h>
21#include <sys/mman.h>
22
23namespace cuttlefish {
24
25// Provides RAII semantics for memory mappings, preventing memory leaks. It does
26// not however prevent use-after-free errors since the underlying pointer can be
27// extracted and could survive this object.
29 public:
30 ScopedMMap();
31 ScopedMMap(void* ptr, size_t len);
32 ScopedMMap(const ScopedMMap& other) = delete;
33 ScopedMMap& operator=(const ScopedMMap& other) = delete;
34 ScopedMMap(ScopedMMap&& other);
35
37
38 void* get() { return ptr_; }
39 const void* get() const { return ptr_; }
40 size_t len() const { return len_; }
41
42 operator bool() const { return ptr_ != MAP_FAILED; }
43
44 // Checks whether the interval [offset, offset + length) is contained within
45 // [0, len_)
46 bool WithinBounds(size_t offset, size_t length) const {
47 // Don't add offset + len to avoid overflow
48 return offset < len_ && len_ - offset >= length;
49 }
50
51 private:
52 void* ptr_ = MAP_FAILED;
53 size_t len_;
54};
55
56} // namespace cuttlefish
57
58#endif // CUTTLEFISH_COMMON_COMMON_LIBS_FS_SCOPED_MMAP_H
Definition: scoped_mmap.h:28
bool WithinBounds(size_t offset, size_t length) const
Definition: scoped_mmap.h:46
void * get()
Definition: scoped_mmap.h:38
ScopedMMap & operator=(const ScopedMMap &other)=delete
const void * get() const
Definition: scoped_mmap.h:39
ScopedMMap()
Definition: scoped_mmap.cc:26
ScopedMMap(const ScopedMMap &other)=delete
size_t len() const
Definition: scoped_mmap.h:40
~ScopedMMap()
Definition: scoped_mmap.cc:34
size_t len_
Definition: scoped_mmap.h:53
void * ptr_
Definition: scoped_mmap.h:52
Definition: alloc_driver.h:20