1 /* Self tests for scoped_mmap for GDB, the GNU debugger.
3 Copyright (C) 2018-2019 Free Software Foundation, Inc.
5 This file is part of GDB.
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.
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.
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/>. */
22 #include "common/filestuff.h"
23 #include "common/scoped_mmap.h"
26 #if defined(HAVE_SYS_MMAN_H)
28 #include "common/selftest.h"
29 #include "common/gdb_unlinker.h"
34 namespace scoped_mmap {
36 /* Test that the file is unmapped. */
44 ::scoped_mmap smmap (nullptr, sysconf (_SC_PAGESIZE), PROT_WRITE,
45 MAP_ANONYMOUS | MAP_PRIVATE, 0, 0);
48 SELF_CHECK (mem != nullptr);
51 SELF_CHECK (msync (mem, sysconf (_SC_PAGESIZE), 0) == -1 && errno == ENOMEM);
54 /* Test that the memory can be released. */
62 ::scoped_mmap smmap (nullptr, sysconf (_SC_PAGESIZE), PROT_WRITE,
63 MAP_ANONYMOUS | MAP_PRIVATE, 0, 0);
65 mem = smmap.release ();
66 SELF_CHECK (mem != nullptr);
69 SELF_CHECK (msync (mem, sysconf (_SC_PAGESIZE), 0) == 0 || errno != ENOMEM);
71 munmap (mem, sysconf (_SC_PAGESIZE));
82 } /* namespace scoped_mmap */
87 /* Test the standard usage of mmap_file. */
91 char filename[] = "scoped_mmapped_file-selftest-XXXXXX";
92 int fd = gdb_mkostemp_cloexec (filename);
95 SELF_CHECK (write (fd, "Hello!", 7) == 7);
98 gdb::unlinker unlink_test_file (filename);
101 ::scoped_mmap m = ::mmap_file (filename);
103 SELF_CHECK (m.get () != MAP_FAILED);
104 SELF_CHECK (m.size () == 7);
105 SELF_CHECK (0 == strcmp ((char *) m.get (), "Hello!"));
109 /* Calling mmap_file with a non-existent file should throw an exception. */
111 test_invalid_filename ()
116 ::scoped_mmap m = ::mmap_file ("/this/file/should/not/exist");
117 } catch (gdb_exception &e) {
130 test_invalid_filename ();
133 } /* namespace mmap_file */
134 } /* namespace selftests */
136 #endif /* !defined(HAVE_SYS_MMAN_H) */
139 _initialize_scoped_mmap_selftests ()
141 #if defined(HAVE_SYS_MMAN_H)
142 selftests::register_test ("scoped_mmap",
143 selftests::scoped_mmap::run_tests);
144 selftests::register_test ("mmap_file",
145 selftests::mmap_file::run_tests);