common: add scoped_mmap
[deliverable/binutils-gdb.git] / gdb / common / scoped_mmap.h
CommitLineData
84696f37
MM
1/* scoped_mmap, automatically unmap files
2
3 Copyright (C) 2018 Free Software Foundation, Inc.
4
5 This file is part of GDB.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
19
20#ifndef SCOPED_MMAP_H
21#define SCOPED_MMAP_H
22
23#include "config.h"
24
25#ifdef HAVE_SYS_MMAN_H
26
27#include <sys/mman.h>
28
29/* A smart-pointer-like class to mmap() and automatically munmap() a memory
30 mapping. */
31
32class scoped_mmap
33{
34public:
35 scoped_mmap () noexcept : m_mem (MAP_FAILED), m_length (0) {}
36 scoped_mmap (void *addr, size_t length, int prot, int flags, int fd,
37 off_t offset) noexcept : m_length (length)
38 {
39 m_mem = mmap (addr, m_length, prot, flags, fd, offset);
40 }
41 ~scoped_mmap ()
42 {
43 if (m_mem != MAP_FAILED)
44 munmap (m_mem, m_length);
45 }
46
47 DISABLE_COPY_AND_ASSIGN (scoped_mmap);
48
49 void *release () noexcept
50 {
51 void *mem = m_mem;
52 m_mem = MAP_FAILED;
53 m_length = 0;
54 return mem;
55 }
56
57 void reset (void *addr, size_t length, int prot, int flags, int fd,
58 off_t offset) noexcept
59 {
60 if (m_mem != MAP_FAILED)
61 munmap (m_mem, m_length);
62
63 m_length = length;
64 m_mem = mmap (addr, m_length, prot, flags, fd, offset);
65 }
66
67 size_t size () const noexcept { return m_length; }
68 void *get () const noexcept { return m_mem; }
69
70private:
71 void *m_mem;
72 size_t m_length;
73};
74
75#endif /* HAVE_SYS_MMAN_H */
76#endif /* SCOPED_MMAP_H */
This page took 0.026013 seconds and 4 git commands to generate.