• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /**
2  * Copyright (c) 2023 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 <signal.h>
17 #include <stdio.h>
18 #include <sys/wait.h>
19 #include "gwp_asan_test.h"
20 #include "test.h"
21 
22 #define SIZE 100
23 
24 typedef struct {
25     char vars[SIZE];
26 } thread_data;
27 
28 __thread thread_data threads;
29 
use_after_free_handler()30 void use_after_free_handler()
31 {
32     find_and_check_file(GWP_ASAN_LOG_DIR, GWP_ASAN_LOG_TAG, "Use After Free at", false);
33     find_and_check_file(GWP_ASAN_LOG_DIR, GWP_ASAN_LOG_TAG, "#2", false);
34     find_and_check_file(GWP_ASAN_LOG_DIR, GWP_ASAN_LOG_TAG, "#0.*?gwp_asan", true);
35     clear_log(GWP_ASAN_LOG_DIR, GWP_ASAN_LOG_TAG);
36     cancel_gwp_asan_environment(true);
37     _exit(0);
38 }
install_sigv_handler()39 static void install_sigv_handler()
40 {
41     struct sigaction sigv = {
42         .sa_handler = use_after_free_handler,
43         .sa_flags = 0,
44     };
45     sigaction(SIGSEGV, &sigv, NULL);
46 }
47 
use_after_free_test()48 void use_after_free_test()
49 {
50     config_gwp_asan_environment(true);
51     clear_log(GWP_ASAN_LOG_DIR, GWP_ASAN_LOG_TAG);
52     install_sigv_handler();
53 
54     char *ptr = (char *)(malloc(10));
55     if (!ptr) {
56         t_error("malloc failed.");
57         return;
58     }
59     if (!libc_gwp_asan_ptr_is_mine(ptr)) {
60         t_error("Memory is not allocated by gwp_asan.");
61         return;
62     }
63     free(ptr);
64     threads.vars[SIZE - 1] = *ptr;
65     printf("c:%c", threads.vars[SIZE - 1]);
66 }
67 
main()68 int main()
69 {
70     pid_t pid = fork();
71     if (pid < 0) {
72         t_error("FAIL fork failed.");
73     } else if (pid == 0) { // child process
74         use_after_free_test();
75     } else { // parent process
76         int status;
77         if (waitpid(pid, &status, 0) != pid) {
78             t_error("gwp_asan_invalid_free_right_test waitpid failed.");
79         }
80 
81         if (WIFEXITED(status) && WEXITSTATUS(status) != 0) {
82             t_error("gwp_asan_invalid_free_right_test failed.");
83         }
84 
85         cancel_gwp_asan_environment(true);
86     }
87 
88     return t_status;
89 }
90