1 // Regression test for https://crbug.com/502974, where ASan was unable to read
2 // the binary name because of sandbox restrictions.
3 // This test uses seccomp-BPF to restrict the readlink() system call and makes
4 // sure ASan is still able to
5 // RUN: not ls /usr/include/linux/seccomp.h || ( %clang_asan %s -o %t && ( not %run %t 2>&1 ) | FileCheck %s )
6 // REQUIRES: shell
7 // UNSUPPORTED: android
8 
9 #include <errno.h>
10 #include <stddef.h>
11 #include <stdlib.h>
12 #include <stdio.h>
13 #include <sys/prctl.h>
14 #include <sys/syscall.h>
15 #include <linux/filter.h>
16 #include <linux/seccomp.h>
17 
18 #ifndef __NR_readlink
19 # define __NR_readlink __NR_readlinkat
20 #endif
21 
22 #define syscall_nr (offsetof(struct seccomp_data, nr))
23 
24 void corrupt() {
25   void *p = malloc(10);
26   free(p);
27   free(p);
28 }
29 
30 int main() {
31   prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0);
32 
33   struct sock_filter filter[] = {
34     /* Grab the system call number */
35     BPF_STMT(BPF_LD + BPF_W + BPF_ABS, syscall_nr),
36     // If this is __NR_readlink,
37     BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, __NR_readlink, 0, 1),
38     // return with EPERM,
39     BPF_STMT(BPF_RET + BPF_K, SECCOMP_RET_ERRNO | EPERM),
40     // otherwise allow the syscall.
41     BPF_STMT(BPF_RET + BPF_K, SECCOMP_RET_ALLOW)
42   };
43   struct sock_fprog prog;
44   prog.len = (unsigned short)(sizeof(filter)/sizeof(filter[0]));
45   prog.filter = filter;
46 
47   int res = prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, &prog, 0, 0);
48   if (res != 0) {
49     fprintf(stderr, "PR_SET_SECCOMP unsupported!\n");
50   }
51   corrupt();
52   // CHECK: AddressSanitizer
53   // CHECK-NOT: reading executable name failed
54   return 0;
55 }
56