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.
5 #include "sandbox/linux/services/proc_util.h"
10 #include "base/files/scoped_file.h"
11 #include "base/posix/eintr_wrapper.h"
12 #include "testing/gtest/include/gtest/gtest.h"
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
);
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()));
27 TEST(ProcUtil
, HasOpenDirectory
) {
28 // No open directory should exist at startup.
29 EXPECT_FALSE(ProcUtil::HasOpenDirectory(-1));
31 // Have a "/dev" file descriptor around.
32 int dev_fd
= open("/dev", O_RDONLY
| O_DIRECTORY
);
33 base::ScopedFD
dev_fd_closer(dev_fd
);
34 EXPECT_TRUE(ProcUtil::HasOpenDirectory(-1));
36 EXPECT_FALSE(ProcUtil::HasOpenDirectory(-1));
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
);
44 // Don't pass |proc_fd|, an open directory (proc_fd) should
46 EXPECT_TRUE(ProcUtil::HasOpenDirectory(-1));
47 // Pass |proc_fd| and no open directory should be detected.
48 EXPECT_FALSE(ProcUtil::HasOpenDirectory(proc_fd
));
51 // Have a "/dev" file descriptor around.
52 int dev_fd
= open("/dev", O_RDONLY
| O_DIRECTORY
);
53 base::ScopedFD
dev_fd_closer(dev_fd
);
54 EXPECT_TRUE(ProcUtil::HasOpenDirectory(proc_fd
));
57 // The "/dev" file descriptor should now be closed, |proc_fd| is the only
58 // directory file descriptor open.
59 EXPECT_FALSE(ProcUtil::HasOpenDirectory(proc_fd
));
62 } // namespace sandbox