1 /*
2  * Copyright (C) 2017 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 #ifndef _LIBUNWINDSTACK_TESTS_TEST_UTILS_H
18 #define _LIBUNWINDSTACK_TESTS_TEST_UTILS_H
19 
20 #include <signal.h>
21 #include <sys/ptrace.h>
22 #include <sys/types.h>
23 #include <sys/wait.h>
24 #include <unistd.h>
25 
26 namespace unwindstack {
27 
28 class TestScopedPidReaper {
29  public:
TestScopedPidReaper(pid_t pid)30   TestScopedPidReaper(pid_t pid) : pid_(pid) {}
~TestScopedPidReaper()31   ~TestScopedPidReaper() {
32     kill(pid_, SIGKILL);
33     waitpid(pid_, nullptr, 0);
34   }
35 
36  private:
37   pid_t pid_;
38 };
39 
TestQuiescePid(pid_t pid)40 inline bool TestQuiescePid(pid_t pid) {
41   siginfo_t si;
42   bool ready = false;
43   // Wait for up to 5 seconds.
44   for (size_t i = 0; i < 5000; i++) {
45     if (ptrace(PTRACE_GETSIGINFO, pid, 0, &si) == 0) {
46       ready = true;
47       break;
48     }
49     usleep(1000);
50   }
51   return ready;
52 }
53 
TestAttach(pid_t pid)54 inline bool TestAttach(pid_t pid) {
55   if (ptrace(PTRACE_ATTACH, pid, 0, 0) == -1) {
56     return false;
57   }
58 
59   return TestQuiescePid(pid);
60 }
61 
TestDetach(pid_t pid)62 inline bool TestDetach(pid_t pid) {
63   return ptrace(PTRACE_DETACH, pid, 0, 0) == 0;
64 }
65 
66 void TestCheckForLeaks(void (*unwind_func)(void*), void* data);
67 
68 }  // namespace unwindstack
69 
70 #endif  // _LIBUNWINDSTACK_TESTS_TEST_UTILS_H
71