xref: /llvm-project/compiler-rt/test/scudo/secondary.c (revision f7c5c0d87b8ae5e55006fd3a31994cd68d64f102)
1*f7c5c0d8SMitch Phillips // RUN: %clang_scudo %s -o %t
2*f7c5c0d8SMitch Phillips // RUN: %run %t after  2>&1 | FileCheck %s
3*f7c5c0d8SMitch Phillips // RUN: %run %t before 2>&1 | FileCheck %s
4*f7c5c0d8SMitch Phillips 
5*f7c5c0d8SMitch Phillips // Test that we hit a guard page when writing past the end of a chunk
6*f7c5c0d8SMitch Phillips // allocated by the Secondary allocator, or writing too far in front of it.
7*f7c5c0d8SMitch Phillips 
8*f7c5c0d8SMitch Phillips #include <assert.h>
9*f7c5c0d8SMitch Phillips #include <malloc.h>
10*f7c5c0d8SMitch Phillips #include <signal.h>
11*f7c5c0d8SMitch Phillips #include <stdlib.h>
12*f7c5c0d8SMitch Phillips #include <string.h>
13*f7c5c0d8SMitch Phillips #include <unistd.h>
14*f7c5c0d8SMitch Phillips 
handler(int signo,siginfo_t * info,void * uctx)15*f7c5c0d8SMitch Phillips void handler(int signo, siginfo_t *info, void *uctx) {
16*f7c5c0d8SMitch Phillips   if (info->si_code == SEGV_ACCERR) {
17*f7c5c0d8SMitch Phillips     fprintf(stderr, "SCUDO SIGSEGV\n");
18*f7c5c0d8SMitch Phillips     exit(0);
19*f7c5c0d8SMitch Phillips   }
20*f7c5c0d8SMitch Phillips   exit(1);
21*f7c5c0d8SMitch Phillips }
22*f7c5c0d8SMitch Phillips 
main(int argc,char ** argv)23*f7c5c0d8SMitch Phillips int main(int argc, char **argv) {
24*f7c5c0d8SMitch Phillips   // The size must be large enough to be serviced by the secondary allocator.
25*f7c5c0d8SMitch Phillips   long page_size = sysconf(_SC_PAGESIZE);
26*f7c5c0d8SMitch Phillips   size_t size = (1U << 17) + page_size;
27*f7c5c0d8SMitch Phillips   struct sigaction a;
28*f7c5c0d8SMitch Phillips 
29*f7c5c0d8SMitch Phillips   assert(argc == 2);
30*f7c5c0d8SMitch Phillips   memset(&a, 0, sizeof(a));
31*f7c5c0d8SMitch Phillips   a.sa_sigaction = handler;
32*f7c5c0d8SMitch Phillips   a.sa_flags = SA_SIGINFO;
33*f7c5c0d8SMitch Phillips 
34*f7c5c0d8SMitch Phillips   char *p = (char *)malloc(size);
35*f7c5c0d8SMitch Phillips   assert(p);
36*f7c5c0d8SMitch Phillips   memset(p, 'A', size); // This should not trigger anything.
37*f7c5c0d8SMitch Phillips   // Set up the SIGSEGV handler now, as the rest should trigger an AV.
38*f7c5c0d8SMitch Phillips   sigaction(SIGSEGV, &a, NULL);
39*f7c5c0d8SMitch Phillips   if (!strcmp(argv[1], "after")) {
40*f7c5c0d8SMitch Phillips     for (int i = 0; i < page_size; i++)
41*f7c5c0d8SMitch Phillips       p[size + i] = 'A';
42*f7c5c0d8SMitch Phillips   }
43*f7c5c0d8SMitch Phillips   if (!strcmp(argv[1], "before")) {
44*f7c5c0d8SMitch Phillips     for (int i = 1; i < page_size; i++)
45*f7c5c0d8SMitch Phillips       p[-i] = 'A';
46*f7c5c0d8SMitch Phillips   }
47*f7c5c0d8SMitch Phillips   free(p);
48*f7c5c0d8SMitch Phillips 
49*f7c5c0d8SMitch Phillips   return 1; // A successful test means we shouldn't reach this.
50*f7c5c0d8SMitch Phillips }
51*f7c5c0d8SMitch Phillips 
52*f7c5c0d8SMitch Phillips // CHECK: SCUDO SIGSEGV
53