#include #include #include #ifndef PAGE_SIZE #include #define PAGE_SIZE sysconf(_SC_PAGE_SIZE) #endif /* get the stack [start,end] of the main thread: start is heuristic (smallest possible based on current rlimit and current mappings, but stack size is limited for sanity) end is precise, parsing /proc may fail */ static int getstack(size_t *start, size_t *end) { size_t limit, prevend; struct rlimit r; FILE *f; char buf[PATH_MAX+80], s[8]; int n; f = fopen("/proc/self/maps", "re"); if (!f) return -1; n = 0; while (fgets(buf, sizeof buf, f)) { n = sscanf(buf, "%zx-%zx %*s %*s %*s %*s %7s", start, end, s); if (n >= 2) { if (n == 3 && strcmp(s, "[stack]") == 0) break; prevend = *end; } n = 0; } fclose(f); if (n == 0) return -1; limit = 100 << 20; /* 100MB stack limit */ if (getrlimit(RLIMIT_STACK, &r)==0 && r.rlim_cur < limit) limit = r.rlim_cur & -PAGE_SIZE; if (limit > *end) limit = *end; if (prevend < *end - limit) prevend = *end - limit; if (*start > prevend) *start = prevend; return 0; } int main() { size_t s,e; if (getstack(&s, &e)) { printf("getstack failed\n"); return -1; } printf("%zx-%zx %zu\n", s, e, e-s); return 0; }