xref: /freebsd/tools/test/stress2/misc/mprotect3.sh (revision ee3960cba1068e12fb032a68c46d74841d9edab3)
1#!/bin/sh
2
3# Test scenario from:
4# Bug 272585 - calling mprotect in an mmap-ed stack can affect non-target pages
5# Test scenario by: John F. Carr <jfc mit edu>
6
7. ../default.cfg
8set -u
9prog=$(basename "$0" .sh)
10cat > /tmp/$prog.c <<EOF
11/* Test program from:
12   Bug 272585 - calling mprotect in an mmap-ed stack can affect non-target pages
13 */
14#include <err.h>
15#include <stdio.h>
16#include <stdint.h>
17#include <stdlib.h>
18#include <sys/mman.h>
19#include <sysexits.h>
20#include <unistd.h>
21
22#ifndef MAP_GROWSDOWN
23#define MAP_GROWSDOWN 0
24#endif
25#ifndef MAP_STACK
26#define MAP_STACK 0
27#endif
28
29int main(void)
30{
31  long pagesize;
32  char *addr, *guard;
33  size_t alloc_size;
34
35  pagesize = sysconf(_SC_PAGESIZE);
36  if (pagesize < 0)
37    err(EX_OSERR, "getPAGESIZE");
38
39  alloc_size = 0x200000 + pagesize;
40
41  addr = mmap(0, alloc_size, PROT_READ|PROT_WRITE,
42              MAP_GROWSDOWN|MAP_STACK|MAP_PRIVATE|MAP_ANONYMOUS,
43              -1, 0);
44  if (addr == MAP_FAILED) {
45    err(EX_OSERR, "mmap");
46  }
47
48  /* Only 0x20 causes a failure. */
49  guard = addr + alloc_size - 0x20 * pagesize;
50
51  if (mprotect(guard, pagesize, PROT_NONE)) {
52    err(EX_OSERR, "mprotect");
53  }
54
55  printf("mapped %p..%p, guard at %p\n", addr, addr + alloc_size, guard);
56  fflush(stdout);
57
58  ((volatile char *)guard)[-1];
59
60  return 0;
61}
62EOF
63mycc -o /tmp/$prog -Wall -Wextra -O0 /tmp/$prog.c || exit 0
64
65cd /tmp
66./$prog; s=$?
67cd -
68
69rm -f /tmp/$prog /tmp/$prog.c /tmp/$prog.core
70exit $s
71