Improve memory safety

This commit makes numerous refinements to cosmopolitan memory handling.

The default stack size has been reduced from 2mb to 128kb. A new macro
is now provided so you can easily reconfigure the stack size to be any
value you want. Work around the breaking change by adding to your main:

    STATIC_STACK_SIZE(0x00200000);  // 2mb stack

If you're not sure how much stack you need, then you can use:

    STATIC_YOINK("stack_usage_logging");

After which you can `sort -nr o/$MODE/stack.log`. Based on the unit test
suite, nothing in the Cosmopolitan repository (except for Python) needs
a stack size greater than 30kb. There are also new macros for detecting
the size and address of the stack at runtime, e.g. GetStackAddr(). We
also now support sigaltstack() so if you want to see nice looking crash
reports whenever a stack overflow happens, you can put this in main():

    ShowCrashReports();

Under `make MODE=dbg` and `make MODE=asan` the unit testing framework
will now automatically print backtraces of memory allocations when
things like memory leaks happen. Bugs are now fixed in ASAN global
variable overrun detection. The memtrack and asan runtimes also handle
edge cases now. The new tools helped to identify a few memory leaks,
which are fixed by this change.

This change should fix an issue reported in #288 with ARG_MAX limits.
Fixing this doubled the performance of MKDEPS.COM and AR.COM yet again.
This commit is contained in:
Justine Tunney 2021-10-13 17:27:13 -07:00
parent a0b39f886c
commit 226aaf3547
317 changed files with 6474 additions and 3993 deletions

View file

@ -21,6 +21,7 @@
#include "libc/sysv/consts/nr.h"
#include "libc/sysv/consts/map.h"
#include "libc/macros.internal.h"
#include "libc/sysv/consts/prot.h"
#include "libc/nexgen32e/macros.h"
/*
@ -349,6 +350,34 @@ _init_systemfive_stack: # determinism ftw!
syscall
2: test %rax,%rax
js 1b
// prevent operating system from auto-mapping stack
// we guarantee stack overflows are always detected
// so long as you never use -DSTACK_FRAME_UNLIMITED
// TODO: Why does this fail sometimes with FreeBSD?
testb IsFreebsd()
jnz 9f
push %rax
push %rdx
push %r11
mov __NR_mprotect,%eax
mov $PAGESIZE,%esi
xor %edx,%edx # PROT_NONE
syscall
pop %r11
pop %rdx
pop %rax
9:
// update the memory intervals
// m.i 0 4
// m.n 8 4
// m.p 16 8
// m.p[0].x 24 4
// m.p[0].y 28 4
// m.p[0].h 32 8
// m.p[0].prot 40 4
// m.p[0].flags 44 4
.weak _mmi
ezlea _mmi,cx
test %rcx,%rcx
@ -360,12 +389,14 @@ _init_systemfive_stack: # determinism ftw!
movb $1,(%rcx) # _mmi.i
mov %r11d,24(%rcx) # _mmi.s[0].x
mov %r9d,28(%rcx) # _mmi.s[0].y
mov %edx,36(%rcx) # _mmi.s[0].prot
mov %r10d,40(%rcx) # _mmi.s[0].flags
orq $-1,32(%rcx) # _mmi.s[0].h
mov %edx,40(%rcx) # _mmi.s[0].prot
mov %r10d,44(%rcx) # _mmi.s[0].flags
3: pop %r9 # restore stack size
pop %rsi
pop %rdi
leave
// switch stacks
pop %rcx
lea (%rax,%r9),%rsp
sub $ape_stack_align,%rsp # openbsd:stackbound