1 /*
2 * Copyright (c) 2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 /* This files contains process dump module unittest. */
17
18 #include "dfx_func_hook_unittest.h"
19
20 #include <csignal>
21 #include <sys/wait.h>
22 #include <unistd.h>
23
24 #include "dfx_exit_hook.h"
25
26 using namespace OHOS::HiviewDFX;
27 using namespace testing::ext;
28 using namespace std;
SetUpTestCase(void)29 void DfxFuncHookUnitTest::SetUpTestCase(void)
30 {
31 }
32
TearDownTestCase(void)33 void DfxFuncHookUnitTest::TearDownTestCase(void)
34 {
35 }
36
SetUp(void)37 void DfxFuncHookUnitTest::SetUp(void)
38 {
39 StartHookExitFunc();
40 }
41
TearDown(void)42 void DfxFuncHookUnitTest::TearDown(void)
43 {
44 }
45
46 namespace {
47 /**
48 * @tc.name: FuncHookTest001
49 * @tc.desc: fork a child process and exit with calling _exit
50 * @tc.type: FUNC
51 */
52 HWTEST_F(DfxFuncHookUnitTest, FuncHookTest001, TestSize.Level3)
53 {
54 GTEST_LOG_(INFO) << "FuncHookTest001: start.";
55 const int retCode = 99;
56 pid_t pid = fork();
57 if (pid < 0) {
58 return;
59 }
60
61 if (pid == 0) {
62 exit(retCode);
63 } else {
64 int status;
65 int ret = waitpid(pid, &status, 0);
66 printf("child ret with pid:%d status:%d\n", ret, status);
67 if (WIFEXITED(status)) {
68 int code = WEXITSTATUS(status);
69 printf("Exit code was %d\n", code);
70 EXPECT_EQ(code, retCode);
71 }
72 }
73 GTEST_LOG_(INFO) << "FuncHookTest001: end.";
74 }
75
76 /**
77 * @tc.name: FuncHookTest002
78 * @tc.desc: fork a child process and kill it in parent process
79 * @tc.type: FUNC
80 */
81 HWTEST_F(DfxFuncHookUnitTest, FuncHookTest002, TestSize.Level3)
82 {
83 GTEST_LOG_(INFO) << "FuncHookTest002: start.";
84 pid_t pid = fork();
85 if (pid < 0) {
86 return;
87 }
88
89 if (pid == 0) {
90 while (true) {
91 sleep(1);
92 }
93 } else {
94 printf("child pid:%d\n", pid);
95 kill(pid, SIGKILL);
96 int status;
97 int ret = waitpid(pid, &status, 0);
98 printf("child ret with pid:%d status:%d\n", ret, status);
99 if (WIFSIGNALED(status)) {
100 int signal = WTERMSIG(status);
101 printf("Exit signal was %d\n", signal);
102 EXPECT_EQ(signal, SIGKILL);
103 }
104 }
105 GTEST_LOG_(INFO) << "FuncHookTest002: end.";
106 }
107 }
108