xref: /netbsd-src/external/gpl3/gdb/dist/gdbsupport/scoped_mmap.cc (revision 5ba1f45f2a09259cc846f20c7c5501604d633c90)
18dffb485Schristos /* scoped_mmap, automatically unmap files
28dffb485Schristos 
3*5ba1f45fSchristos    Copyright (C) 2018-2024 Free Software Foundation, Inc.
48dffb485Schristos 
58dffb485Schristos    This file is part of GDB.
68dffb485Schristos 
78dffb485Schristos    This program is free software; you can redistribute it and/or modify
88dffb485Schristos    it under the terms of the GNU General Public License as published by
98dffb485Schristos    the Free Software Foundation; either version 3 of the License, or
108dffb485Schristos    (at your option) any later version.
118dffb485Schristos 
128dffb485Schristos    This program is distributed in the hope that it will be useful,
138dffb485Schristos    but WITHOUT ANY WARRANTY; without even the implied warranty of
148dffb485Schristos    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
158dffb485Schristos    GNU General Public License for more details.
168dffb485Schristos 
178dffb485Schristos    You should have received a copy of the GNU General Public License
188dffb485Schristos    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
198dffb485Schristos 
208dffb485Schristos #include "scoped_mmap.h"
218dffb485Schristos #include "scoped_fd.h"
228dffb485Schristos #include "gdbsupport/filestuff.h"
238dffb485Schristos 
248dffb485Schristos #ifdef HAVE_SYS_MMAN_H
258dffb485Schristos 
268dffb485Schristos scoped_mmap
278dffb485Schristos mmap_file (const char *filename)
288dffb485Schristos {
294b169a6bSchristos   scoped_fd fd = gdb_open_cloexec (filename, O_RDONLY, 0);
308dffb485Schristos   if (fd.get () < 0)
318dffb485Schristos     perror_with_name (("open"));
328dffb485Schristos 
338dffb485Schristos   off_t size = lseek (fd.get (), 0, SEEK_END);
348dffb485Schristos   if (size < 0)
358dffb485Schristos     perror_with_name (("lseek"));
368dffb485Schristos 
378dffb485Schristos   /* We can't map an empty file.  */
388dffb485Schristos   if (size == 0)
398dffb485Schristos     error (_("file to mmap is empty"));
408dffb485Schristos 
418dffb485Schristos   scoped_mmap mmapped_file (nullptr, size, PROT_READ, MAP_PRIVATE, fd.get (), 0);
428dffb485Schristos   if (mmapped_file.get () == MAP_FAILED)
438dffb485Schristos     perror_with_name (("mmap"));
448dffb485Schristos 
458dffb485Schristos   return mmapped_file;
468dffb485Schristos }
478dffb485Schristos 
488dffb485Schristos #endif /* HAVE_SYS_MMAN_H */
49