Home | History | Annotate | Download | only in tests
      1 // Copyright (c) 2012 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 <fcntl.h>
      6 #include <poll.h>
      7 #include <signal.h>
      8 #include <stdio.h>
      9 #include <sys/resource.h>
     10 #include <sys/time.h>
     11 #include <unistd.h>
     12 
     13 #include "base/file_util.h"
     14 #include "base/third_party/valgrind/valgrind.h"
     15 #include "build/build_config.h"
     16 #include "sandbox/linux/tests/unit_tests.h"
     17 
     18 namespace {
     19 std::string TestFailedMessage(const std::string& msg) {
     20   return msg.empty() ? std::string() : "Actual test failure: " + msg;
     21 }
     22 
     23 int GetSubProcessTimeoutTimeInSeconds() {
     24   // 10s ought to be enough for anybody.
     25   return 10;
     26 }
     27 
     28 // Returns the number of threads of the current process or -1.
     29 int CountThreads() {
     30   struct stat task_stat;
     31   int task_d = stat("/proc/self/task", &task_stat);
     32   // task_stat.st_nlink should be the number of tasks + 2 (accounting for
     33   // "." and "..".
     34   if (task_d != 0 || task_stat.st_nlink < 3)
     35     return -1;
     36   const int num_threads = task_stat.st_nlink - 2;
     37   return num_threads;
     38 }
     39 
     40 }  // namespace
     41 
     42 namespace sandbox {
     43 
     44 bool IsAndroid() {
     45 #if defined(OS_ANDROID)
     46   return true;
     47 #else
     48   return false;
     49 #endif
     50 }
     51 
     52 bool IsArchitectureArm() {
     53 #if defined(ARCH_CPU_ARM_FAMILY)
     54   return true;
     55 #else
     56   return false;
     57 #endif
     58 }
     59 
     60 // TODO(jln): figure out why base/.../dynamic_annotations.h's
     61 // RunningOnValgrind() cannot link.
     62 bool IsRunningOnValgrind() {
     63   return RUNNING_ON_VALGRIND;
     64 }
     65 
     66 static const int kExpectedValue = 42;
     67 static const int kIgnoreThisTest = 43;
     68 static const int kExitWithAssertionFailure = 1;
     69 static const int kExitForTimeout = 2;
     70 
     71 static void SigAlrmHandler(int) {
     72     const char failure_message[] = "Timeout reached!\n";
     73     // Make sure that we never block here.
     74     if (!fcntl(2, F_SETFL,  O_NONBLOCK)) {
     75       if (write(2, failure_message, sizeof(failure_message) - 1) < 0) {
     76       }
     77     }
     78     _exit(kExitForTimeout);
     79 }
     80 
     81 // Set a timeout with a handler that will automatically fail the
     82 // test.
     83 static void SetProcessTimeout(int time_in_seconds) {
     84   struct sigaction act = {};
     85   act.sa_handler = SigAlrmHandler;
     86   SANDBOX_ASSERT(sigemptyset(&act.sa_mask) == 0);
     87   act.sa_flags = 0;
     88 
     89   struct sigaction old_act;
     90   SANDBOX_ASSERT(sigaction(SIGALRM, &act, &old_act) == 0);
     91 
     92   // We don't implemenet signal chaining, so make sure that nothing else
     93   // is expecting to handle SIGALRM.
     94   SANDBOX_ASSERT((old_act.sa_flags & SA_SIGINFO) == 0);
     95   SANDBOX_ASSERT(old_act.sa_handler == SIG_DFL);
     96   sigset_t sigalrm_set;
     97   SANDBOX_ASSERT(sigemptyset(&sigalrm_set) == 0);
     98   SANDBOX_ASSERT(sigaddset(&sigalrm_set, SIGALRM) == 0);
     99   SANDBOX_ASSERT(sigprocmask(SIG_UNBLOCK, &sigalrm_set, NULL) == 0);
    100   SANDBOX_ASSERT(alarm(time_in_seconds) == 0);  // There should be no previous
    101                                                 // alarm.
    102 }
    103 
    104 // Runs a test in a sub-process. This is necessary for most of the code
    105 // in the BPF sandbox, as it potentially makes global state changes and as
    106 // it also tends to raise fatal errors, if the code has been used in an
    107 // insecure manner.
    108 void UnitTests::RunTestInProcess(UnitTests::Test test, void *arg,
    109                                  DeathCheck death, const void *death_aux) {
    110   // We need to fork(), so we can't be multi-threaded, as threads could hold
    111   // locks.
    112   int num_threads = CountThreads();
    113 #if defined(THREAD_SANITIZER)
    114   // Under TSAN, there is a special helper thread. It should be completely
    115   // invisible to our testing, so we ignore it. It should be ok to fork()
    116   // with this thread. It's currently buggy, but it's the best we can do until
    117   // there is a way to delay the start of the thread
    118   // (https://code.google.com/p/thread-sanitizer/issues/detail?id=19).
    119   num_threads--;
    120 #endif
    121   ASSERT_EQ(1, num_threads) << "Running sandbox tests with multiple threads "
    122                             << "is not supported and will make the tests "
    123                             << "flaky.\n";
    124   int fds[2];
    125   ASSERT_EQ(0, pipe(fds));
    126   // Check that our pipe is not on one of the standard file descriptor.
    127   SANDBOX_ASSERT(fds[0] > 2 && fds[1] > 2);
    128 
    129   pid_t pid;
    130   ASSERT_LE(0, (pid = fork()));
    131   if (!pid) {
    132     // In child process
    133     // Redirect stderr to our pipe. This way, we can capture all error
    134     // messages, if we decide we want to do so in our tests.
    135     SANDBOX_ASSERT(dup2(fds[1], 2) == 2);
    136     SANDBOX_ASSERT(!close(fds[0]));
    137     SANDBOX_ASSERT(!close(fds[1]));
    138 
    139     // Don't set a timeout if running on Valgrind, since it's generally much
    140     // slower.
    141     if (!IsRunningOnValgrind()) {
    142       SetProcessTimeout(GetSubProcessTimeoutTimeInSeconds());
    143     }
    144 
    145     // Disable core files. They are not very useful for our individual test
    146     // cases.
    147     struct rlimit no_core = { 0 };
    148     setrlimit(RLIMIT_CORE, &no_core);
    149 
    150     test(arg);
    151     _exit(kExpectedValue);
    152   }
    153 
    154   (void)HANDLE_EINTR(close(fds[1]));
    155   std::vector<char> msg_buf;
    156   ssize_t rc;
    157 
    158   // Make sure read() will never block as we'll use poll() to
    159   // block with a timeout instead.
    160   const int fcntl_ret = fcntl(fds[0], F_SETFL,  O_NONBLOCK);
    161   ASSERT_EQ(fcntl_ret, 0);
    162   struct pollfd poll_fd = { fds[0], POLLIN | POLLRDHUP, 0 };
    163 
    164   int poll_ret;
    165   // We prefer the SIGALRM timeout to trigger in the child than this timeout
    166   // so we double the common value here.
    167   int poll_timeout = GetSubProcessTimeoutTimeInSeconds() * 2 * 1000;
    168   while ((poll_ret = poll(&poll_fd, 1, poll_timeout) > 0)) {
    169     const size_t kCapacity = 256;
    170     const size_t len = msg_buf.size();
    171     msg_buf.resize(len + kCapacity);
    172     rc = HANDLE_EINTR(read(fds[0], &msg_buf[len], kCapacity));
    173     msg_buf.resize(len + std::max(rc, static_cast<ssize_t>(0)));
    174     if (rc <= 0)
    175       break;
    176   }
    177   ASSERT_NE(poll_ret, -1) << "poll() failed";
    178   ASSERT_NE(poll_ret, 0) << "Timeout while reading child state";
    179   (void)HANDLE_EINTR(close(fds[0]));
    180   std::string msg(msg_buf.begin(), msg_buf.end());
    181 
    182   int status = 0;
    183   int waitpid_returned = HANDLE_EINTR(waitpid(pid, &status, 0));
    184   ASSERT_EQ(pid, waitpid_returned) << TestFailedMessage(msg);
    185 
    186   // At run-time, we sometimes decide that a test shouldn't actually
    187   // run (e.g. when testing sandbox features on a kernel that doesn't
    188   // have sandboxing support). When that happens, don't attempt to
    189   // call the "death" function, as it might be looking for a
    190   // death-test condition that would never have triggered.
    191   if (!WIFEXITED(status) || WEXITSTATUS(status) != kIgnoreThisTest ||
    192       !msg.empty()) {
    193     // We use gtest's ASSERT_XXX() macros instead of the DeathCheck
    194     // functions.  This means, on failure, "return" is called. This
    195     // only works correctly, if the call of the "death" callback is
    196     // the very last thing in our function.
    197     death(status, msg, death_aux);
    198   }
    199 }
    200 
    201 void UnitTests::DeathSuccess(int status, const std::string& msg,
    202                              const void *) {
    203   std::string details(TestFailedMessage(msg));
    204 
    205   bool subprocess_terminated_normally = WIFEXITED(status);
    206   ASSERT_TRUE(subprocess_terminated_normally) << details;
    207   int subprocess_exit_status = WEXITSTATUS(status);
    208   ASSERT_EQ(kExpectedValue, subprocess_exit_status) << details;
    209   bool subprocess_exited_but_printed_messages = !msg.empty();
    210   EXPECT_FALSE(subprocess_exited_but_printed_messages) << details;
    211 }
    212 
    213 void UnitTests::DeathMessage(int status, const std::string& msg,
    214                              const void *aux) {
    215   std::string details(TestFailedMessage(msg));
    216   const char *expected_msg = static_cast<const char *>(aux);
    217 
    218   bool subprocess_terminated_normally = WIFEXITED(status);
    219   ASSERT_TRUE(subprocess_terminated_normally) << details;
    220   int subprocess_exit_status = WEXITSTATUS(status);
    221   ASSERT_EQ(kExitWithAssertionFailure, subprocess_exit_status) << details;
    222   bool subprocess_exited_without_matching_message =
    223     msg.find(expected_msg) == std::string::npos;
    224   EXPECT_FALSE(subprocess_exited_without_matching_message) << details;
    225 }
    226 
    227 void UnitTests::DeathExitCode(int status, const std::string& msg,
    228                               const void *aux) {
    229   int expected_exit_code = static_cast<int>(reinterpret_cast<intptr_t>(aux));
    230   std::string details(TestFailedMessage(msg));
    231 
    232   bool subprocess_terminated_normally = WIFEXITED(status);
    233   ASSERT_TRUE(subprocess_terminated_normally) << details;
    234   int subprocess_exit_status = WEXITSTATUS(status);
    235   ASSERT_EQ(subprocess_exit_status, expected_exit_code) << details;
    236 }
    237 
    238 void UnitTests::DeathBySignal(int status, const std::string& msg,
    239                               const void *aux) {
    240   int expected_signo = static_cast<int>(reinterpret_cast<intptr_t>(aux));
    241   std::string details(TestFailedMessage(msg));
    242 
    243   bool subprocess_terminated_by_signal = WIFSIGNALED(status);
    244   ASSERT_TRUE(subprocess_terminated_by_signal) << details;
    245   int subprocess_signal_number = WTERMSIG(status);
    246   ASSERT_EQ(subprocess_signal_number, expected_signo) << details;
    247 }
    248 
    249 void UnitTests::AssertionFailure(const char *expr, const char *file,
    250                                  int line) {
    251   fprintf(stderr, "%s:%d:%s", file, line, expr);
    252   fflush(stderr);
    253   _exit(kExitWithAssertionFailure);
    254 }
    255 
    256 void UnitTests::IgnoreThisTest() {
    257   fflush(stderr);
    258   _exit(kIgnoreThisTest);
    259 }
    260 
    261 }  // namespace
    262