• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2023 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #pragma once
18 
19 #include <signal.h>
20 #include <sys/types.h>
21 #include <sys/wait.h>
22 #include <unistd.h>
23 
24 #include <functional>
25 
26 #include <gtest/gtest.h>
27 
28 #include "PidUtils.h"
29 #include "TestUtils.h"
30 
31 namespace unwindstack {
32 
33 class ForkTest : public ::testing::Test {
34  protected:
SetForkFunc(std::function<void ()> fork_func)35   void SetForkFunc(std::function<void()> fork_func) { fork_func_ = fork_func; }
36 
Fork(std::function<void ()> fork_func)37   void Fork(std::function<void()> fork_func) {
38     SetForkFunc(fork_func);
39     Fork();
40   }
41 
Fork()42   void Fork() {
43     for (size_t i = 0; i < kMaxRetries; i++) {
44       if ((pid_ = fork()) == 0) {
45         fork_func_();
46         _exit(1);
47       }
48       ASSERT_NE(-1, pid_);
49       if (Attach(pid_)) {
50         return;
51       }
52       kill(pid_, SIGKILL);
53       waitpid(pid_, nullptr, 0);
54       pid_ = -1;
55     }
56     FAIL() << "Unable to fork and attach to process.";
57   }
58 
ForkAndWaitForPidState(const std::function<PidRunEnum ()> & state_check_func)59   void ForkAndWaitForPidState(const std::function<PidRunEnum()>& state_check_func) {
60     for (size_t i = 0; i < kMaxRetries; i++) {
61       ASSERT_NO_FATAL_FAILURE(Fork());
62 
63       if (WaitForPidStateAfterAttach(pid_, state_check_func)) {
64         return;
65       }
66       kill(pid_, SIGKILL);
67       waitpid(pid_, nullptr, 0);
68       pid_ = -1;
69     }
70     FAIL() << "Process never got to expected state.";
71   }
72 
TearDown()73   void TearDown() override {
74     if (pid_ == -1) {
75       return;
76     }
77     Detach(pid_);
78     kill(pid_, SIGKILL);
79     waitpid(pid_, nullptr, 0);
80   }
81 
82   pid_t pid_ = -1;
83   bool should_detach_ = true;
84   // Default to a run forever function.
85   std::function<void()> fork_func_ = []() {
86     while (true)
87       ;
88   };
89 
90   static constexpr size_t kMaxRetries = 3;
91 };
92 
93 }  // namespace unwindstack
94