File: stack_prot.c

package info (click to toggle)
valgrind 1%3A3.16.1-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 158,568 kB
  • sloc: ansic: 746,130; exp: 26,134; xml: 22,708; asm: 13,570; cpp: 7,691; makefile: 6,177; perl: 5,965; sh: 5,665; javascript: 929
file content (65 lines) | stat: -rw-r--r-- 1,483 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <procfs.h>
#include <stdio.h>

#define ARRAY_LENGTH(array) (sizeof((array)) / sizeof(0[(array)]))

int main(void)
{
   int res = 1;
   FILE *fi = NULL;
   prxmap_t map[32];
   int found = 0;
   int done = 0;
   /* Obtain an address inside the stack using a dirty trick. */
   uintptr_t local = (uintptr_t)&fi;

   /* Open /proc/self/xmap for reading. */
   fi = fopen("/proc/self/xmap", "r");
   if (!fi) {
      perror("fopen");
      goto out;
   }

   /* Read the file until EOF or the stack is found. */
   while (!done && !found) {
      size_t i, items;

      items = fread(map, sizeof(map[0]), ARRAY_LENGTH(map), fi);
      if (items != ARRAY_LENGTH(map)) {
         if (ferror(fi)) {
            perror("fread");
            goto out;
         }
         done = 1;
      }

      /* Scan the read mappings. */
      for (i = 0; i < items; i++)
         if (map[i].pr_vaddr <= local
             && local < map[i].pr_vaddr + map[i].pr_size) {
            /* Stack was found, validate it. */
            found = 1;
            if ((map[i].pr_mflags & (MA_READ | MA_WRITE | MA_EXEC))
                != (MA_READ | MA_WRITE)) {
               fprintf(stderr, "Incorrect stack mapping detected.\n");
               goto out;
            }
         }
   }

   /* Check if the stack was indeed found. */
   if (!found) {
      fprintf(stderr, "Stack not found.\n");
      goto out;
   }

   res = 0;

out:
   /* Cleanup. */
   if (fi)
      fclose(fi);

   return res;
}