• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2014 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "base/files/scoped_file.h"
6 
7 #include "base/check.h"
8 #include "build/build_config.h"
9 
10 #if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
11 #include <errno.h>
12 #include <unistd.h>
13 
14 #include "base/posix/eintr_wrapper.h"
15 #endif
16 
17 namespace base::internal {
18 
19 #if BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
20 
21 // static
Free(int fd)22 void ScopedFDCloseTraits::Free(int fd) {
23   // It's important to crash here if something goes wrong.
24   //
25   // There are security implications to not closing a file descriptor
26   // properly. As file descriptors are "capabilities", keeping them open
27   // would make the current process keep access to a resource. Much of
28   // Chrome relies on being able to "drop" such access.
29   //
30   // It's especially problematic on Linux with the setuid sandbox, where
31   // a single open directory would bypass the entire security model.
32   int ret = IGNORE_EINTR(close(fd));
33 
34 #if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_APPLE) || \
35     BUILDFLAG(IS_FUCHSIA) || BUILDFLAG(IS_ANDROID)
36   // NB: Some file descriptors can return errors from close() e.g. network
37   // filesystems such as NFS and Linux input devices. On Linux, macOS, and
38   // Fuchsia's POSIX layer, errors from close other than EBADF do not indicate
39   // failure to actually close the fd.
40   if (ret != 0 && errno != EBADF) {
41     ret = 0;
42   }
43 #endif
44 
45   PCHECK(0 == ret);
46 }
47 
48 #endif  // BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
49 
50 }  // namespace base::internal
51