• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2014 The Chromium Authors. All rights reserved.
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 "sandbox/linux/services/proc_util.h"
6 
7 #include <fcntl.h>
8 #include <unistd.h>
9 
10 #include "base/files/scoped_file.h"
11 #include "base/posix/eintr_wrapper.h"
12 #include "testing/gtest/include/gtest/gtest.h"
13 
14 namespace sandbox {
15 
TEST(ProcUtil,CountOpenFds)16 TEST(ProcUtil, CountOpenFds) {
17   base::ScopedFD proc_fd(open("/proc/", O_RDONLY | O_DIRECTORY));
18   ASSERT_TRUE(proc_fd.is_valid());
19   int fd_count = ProcUtil::CountOpenFds(proc_fd.get());
20   int fd = open("/dev/null", O_RDONLY);
21   ASSERT_LE(0, fd);
22   EXPECT_EQ(fd_count + 1, ProcUtil::CountOpenFds(proc_fd.get()));
23   ASSERT_EQ(0, IGNORE_EINTR(close(fd)));
24   EXPECT_EQ(fd_count, ProcUtil::CountOpenFds(proc_fd.get()));
25 }
26 
TEST(ProcUtil,HasOpenDirectory)27 TEST(ProcUtil, HasOpenDirectory) {
28   // No open directory should exist at startup.
29   EXPECT_FALSE(ProcUtil::HasOpenDirectory());
30   {
31     // Have a "/proc" file descriptor around.
32     int proc_fd = open("/proc/", O_RDONLY | O_DIRECTORY);
33     base::ScopedFD proc_fd_closer(proc_fd);
34     EXPECT_TRUE(ProcUtil::HasOpenDirectory());
35   }
36   EXPECT_FALSE(ProcUtil::HasOpenDirectory());
37 }
38 
TEST(ProcUtil,HasOpenDirectoryWithFD)39 TEST(ProcUtil, HasOpenDirectoryWithFD) {
40   int proc_fd = open("/proc/", O_RDONLY | O_DIRECTORY);
41   base::ScopedFD proc_fd_closer(proc_fd);
42   ASSERT_LE(0, proc_fd);
43 
44   // Don't pass |proc_fd|, an open directory (proc_fd) should
45   // be detected.
46   EXPECT_TRUE(ProcUtil::HasOpenDirectory());
47   // Pass |proc_fd| and no open directory should be detected.
48   EXPECT_FALSE(ProcUtil::HasOpenDirectory(proc_fd));
49 
50   {
51     // Have a directory file descriptor around.
52     int open_directory_fd = open("/proc/self/", O_RDONLY | O_DIRECTORY);
53     base::ScopedFD open_directory_fd_closer(open_directory_fd);
54     EXPECT_TRUE(ProcUtil::HasOpenDirectory(proc_fd));
55   }
56 
57   // The "/proc/" file descriptor should now be closed, |proc_fd| is the
58   // only directory file descriptor open.
59   EXPECT_FALSE(ProcUtil::HasOpenDirectory(proc_fd));
60 }
61 
62 }  // namespace sandbox
63