]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blame - gdb/common/scoped_fd.h
Fix unsigned overflow in minsyms reader.
[thirdparty/binutils-gdb.git] / gdb / common / scoped_fd.h
CommitLineData
ea4a0888
MM
1/* scoped_fd, automatically close a file descriptor
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_FD_H
21#define SCOPED_FD_H
22
ea4a0888 23#include <unistd.h>
36033ef5 24#include "filestuff.h"
ea4a0888
MM
25
26/* A smart-pointer-like class to automatically close a file descriptor. */
27
28class scoped_fd
29{
30public:
31 explicit scoped_fd (int fd = -1) noexcept : m_fd (fd) {}
32 ~scoped_fd ()
33 {
34 if (m_fd >= 0)
35 close (m_fd);
36 }
37
38 DISABLE_COPY_AND_ASSIGN (scoped_fd);
39
40 int release () noexcept
41 {
42 int fd = m_fd;
43 m_fd = -1;
44 return fd;
45 }
46
36033ef5
TT
47 /* Like release, but return a gdb_file_up that owns the file
48 descriptor. On success, this scoped_fd will be released. On
49 failure, return NULL and leave this scoped_fd in possession of
50 the fd. */
51 gdb_file_up to_file (const char *mode) noexcept
52 {
53 gdb_file_up result (fdopen (m_fd, mode));
54 if (result != nullptr)
55 m_fd = -1;
56 return result;
57 }
58
ea4a0888
MM
59 int get () const noexcept
60 {
61 return m_fd;
62 }
63
64private:
65 int m_fd;
66};
67
ea4a0888 68#endif /* SCOPED_FD_H */