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 #include <stdlib.h>
17 #include <unistd.h>
18 #include <sys/wait.h>
19 #include <signal.h>
20 #include <sigchain.h>
21 #include <errno.h>
22 #include <string.h>
23 #include "test.h"
24
handler(int s)25 static void handler(int s)
26 {
27 }
28
child(void)29 static int child(void)
30 {
31 void *ptr = malloc(10);
32 if (!ptr) {
33 t_error("Malloc failed:%s\n", strerror(errno));
34 return -1;
35 }
36
37 /* Double free the pointer to trigger double-free check */
38 free(ptr);
39 free(ptr);
40 return 0;
41 }
42
start_child(void)43 static pid_t start_child(void)
44 {
45 pid_t pid;
46 int ret;
47 pid = fork();
48 if (pid == 0) {
49 ret = child();
50 t_error("child process normally out with %d\n", ret);
51 return ret;
52 }
53 return pid;
54 }
55
main(int argc,char * argv[])56 int main(int argc, char *argv[])
57 {
58 sigset_t set;
59 int status;
60 pid_t pid;
61 int flag = 0;
62
63 sigemptyset(&set);
64 sigaddset(&set, SIGCHLD);
65 sigprocmask(SIG_BLOCK, &set, 0);
66 signal(SIGCHLD, handler);
67 remove_all_special_handler(SIGSEGV);
68
69 pid = start_child();
70 if (pid == -1) {
71 t_error("%s fork failed: %s\n", argv[0], strerror(errno));
72 return -1;
73 }
74 if (sigtimedwait(&set, 0, &(struct timespec){5, 0}) == -1) { /* Wait for 5 seconds */
75 if (errno == EAGAIN)
76 flag = 1;
77 else
78 t_error("%s sigtimedwait failed: %s\n", argv[0], strerror(errno));
79 if (kill(pid, SIGKILL) == -1)
80 t_error("%s kill failed: %s\n", argv[0], strerror(errno));
81 }
82
83 if (waitpid(pid, &status, 0) != pid) {
84 t_error("%s waitpid failed: %s\n", argv[0], strerror(errno));
85 return -1;
86 }
87
88 if (flag) {
89 t_error("Child process time out\n");
90 }
91
92 if (WIFSIGNALED(status)) {
93 if (WTERMSIG(status) != SIGSEGV && WTERMSIG(status) != SIGILL) {
94 t_error("%s child process out with %s\n", argv[0], strsignal(WTERMSIG(status)));
95 return -1;
96 }
97 } else {
98 t_error("%s child process finished normally\n", argv[0]);
99 }
100 return t_status;
101 }
102