1 #include <procfs.h> 2 #include <stdio.h> 3 4 #define ARRAY_LENGTH(array) (sizeof((array)) / sizeof(0[(array)])) 5 main(void)6int main(void) 7 { 8 int res = 1; 9 FILE *fi = NULL; 10 prxmap_t map[32]; 11 int found = 0; 12 int done = 0; 13 /* Obtain an address inside the stack using a dirty trick. */ 14 uintptr_t local = (uintptr_t)&fi; 15 16 /* Open /proc/self/xmap for reading. */ 17 fi = fopen("/proc/self/xmap", "r"); 18 if (!fi) { 19 perror("fopen"); 20 goto out; 21 } 22 23 /* Read the file until EOF or the stack is found. */ 24 while (!done && !found) { 25 size_t i, items; 26 27 items = fread(map, sizeof(map[0]), ARRAY_LENGTH(map), fi); 28 if (items != ARRAY_LENGTH(map)) { 29 if (ferror(fi)) { 30 perror("fread"); 31 goto out; 32 } 33 done = 1; 34 } 35 36 /* Scan the read mappings. */ 37 for (i = 0; i < items; i++) 38 if (map[i].pr_vaddr <= local 39 && local < map[i].pr_vaddr + map[i].pr_size) { 40 /* Stack was found, validate it. */ 41 found = 1; 42 if ((map[i].pr_mflags & (MA_READ | MA_WRITE | MA_EXEC)) 43 != (MA_READ | MA_WRITE)) { 44 fprintf(stderr, "Incorrect stack mapping detected.\n"); 45 goto out; 46 } 47 } 48 } 49 50 /* Check if the stack was indeed found. */ 51 if (!found) { 52 fprintf(stderr, "Stack not found.\n"); 53 goto out; 54 } 55 56 res = 0; 57 58 out: 59 /* Cleanup. */ 60 if (fi) 61 fclose(fi); 62 63 return res; 64 } 65 66