test_utils.cc 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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. #include "sandbox/linux/tests/test_utils.h"
  5. #include <errno.h>
  6. #include <sys/mman.h>
  7. #include <sys/stat.h>
  8. #include <sys/types.h>
  9. #include <sys/wait.h>
  10. #include <unistd.h>
  11. #include "base/check_op.h"
  12. #include "base/memory/page_size.h"
  13. #include "base/posix/eintr_wrapper.h"
  14. namespace sandbox {
  15. bool TestUtils::CurrentProcessHasChildren() {
  16. siginfo_t process_info;
  17. int ret = HANDLE_EINTR(
  18. waitid(P_ALL, 0, &process_info, WEXITED | WNOHANG | WNOWAIT));
  19. if (-1 == ret) {
  20. PCHECK(ECHILD == errno);
  21. return false;
  22. } else {
  23. return true;
  24. }
  25. }
  26. void TestUtils::HandlePostForkReturn(pid_t pid) {
  27. const int kChildExitCode = 1;
  28. if (pid > 0) {
  29. int status = 0;
  30. PCHECK(pid == HANDLE_EINTR(waitpid(pid, &status, 0)));
  31. CHECK(WIFEXITED(status));
  32. CHECK_EQ(kChildExitCode, WEXITSTATUS(status));
  33. } else if (pid == 0) {
  34. _exit(kChildExitCode);
  35. }
  36. }
  37. void* TestUtils::MapPagesOrDie(size_t num_pages) {
  38. void* addr = mmap(nullptr, num_pages * base::GetPageSize(),
  39. PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
  40. PCHECK(addr);
  41. return addr;
  42. }
  43. void TestUtils::MprotectLastPageOrDie(char* addr, size_t num_pages) {
  44. size_t last_page_offset = (num_pages - 1) * base::GetPageSize();
  45. PCHECK(mprotect(addr + last_page_offset, base::GetPageSize(), PROT_NONE) >=
  46. 0);
  47. }
  48. } // namespace sandbox