11 ms·
Stack size invisibility in C and the effects on "portability"
- ghoward 5y agoTFA is right, sadly. One of the projects I was to go in the future is implement boringcc [1], and this sounds like something I would want in it. The question then becomes: would it even be possible to do? [1]: https://groups.google.com/g/boring-crypto/c/48qa1kWignU/m/o8GGp2K1DAAJ https://groups.google.com/g/boring-crypto/c/48qa1kWignU/m/o8...
- miloshadzic 5y agoThe spam on that thread is really something.
- qsort 5y agoWouldn't the majority of it just be, effectively, "all pointers are now fat"? It could disable some (many?) optimizations, but I don't see it as a particularly hard thing to do (at least conceptually).
- ghoward 5y agoNo, not a hard thing to make a boringcc compiler, but I was referring specifically to querying stack size.
- hdjjhhvvhga 5y agoProbably the only way is to use platform-specific quirks, but that's basically the same with everything else. The portability only works for some generic code, pretty much any non-trivial/real-world software uses a lot of platform-specific code.
- cryptonector 5y agoTFA is wrong. The C run-time's call frame allocation method and actual resource limits leak past the C function call and variable-length-array (VLA) abstractions. You can write portable code to force defined (by the platform, not by the C spec) resource exhaustion behavior sooner than undefined behavior caused by memory corruption caused by use of much-larger-than-the-stack stack allocations.
- ghoward 5y agoCan you really? If you depend on a SIGSEGV handler, that handler needs stack space unless you set up a separate stack for it, and I am not sure that is portable.
- cryptonector 5y agoThe point is to cause a defined (by the platform) stack exhaustion failure mode before possibly causing undefined behavior by corrupting memory. The C specs do not define any resource exhaustion failure modes. But actual operating systems, ABIs, platforms -- they do. If you are on a system that gives you a SIGSEGV but no way to catch it on an alternate stack -or if you don't catch or ignore it- then your process will crash. This is fine. It's better than memory corruption.
- ghoward 5y agoCan you give me an example of a platform where your program cannot cause memory corruption if you access an array on the stack out of bounds far enough to corrupt actual existing memory on the heap? Because a SIGSEGV is the best case scenario; the other scenarios are not helped at all by platforms.
- cryptonector 5y agoSay you alloca(1GB), and alloca() is naive and gives it to you even though that 1GB spans several other stacks, and now you write somewhere in the middle. If you're lucky you'll hit unmapped space and trigger a segfault. If you're unlucky you'll scribble over another thread's stack or whatever. But if you progressively write into the alloca()ed area in the direction of stack growth then you cannot corrupt other mappings, and you can only segfault if you exceed your stack's maximum size. Of course, there can be platforms with no SIGSEGV or whatever.
- trasz 5y agoWhat’s the point of a low stack limit, apart from places like the kernel?
- jameshart 5y agoA microcontroller programmer says: "What kernel?"
- m_eiman 5y ago… and embedded, of course. The main problem is that there IS a limit, and you have no idea what the limit is. The only way you find out is when you crash.
- trasz 5y agoThere is - in embedded (also kernel), but not in general purpose systems, like the Unix userspace. And the same piece of software very rarely runs on both. So, again, what’s the point of this exercise?
- StillBored 5y agoPeople have differing opinions of "embedded" but I would claim that most embedded uses cases the stack is actually specified by the programmer via linker scripts and/or manually setting it up during early bootstrap. Plus, its not exactly hard in most of these environments to write target and/or compiler specific macros which detects top of stack and can runtime check it via DEBUG() like macros or modifying function entry macros. None of this is of course portable, but neither is code designed to run in 1-16k of RAM and a few more K of flash. OTOH, there seem to be a lot of "we don't control anything" IoT devices which are random overly powerful processors with random uboot+linux kernels+rootfs's running my_first_c_program.c level applications. All of it tossed together with very little engineering effort, and frequently less low level knowledge, and left to rot because its basically unmaintainable, even if it happens to be the 1% of devices that can get over the air updates.
- formerly_proven 5y ago
- QuadrupleA 5y agoNever thought about it but yes, what a huge (and easily implementable) oversight - stackSize(), stackUsed(), stackTopPtr() would be a few asm instructions in most cases.
- lifthrasiir 5y agoAs mentioned in the OP though, there is zero guarantee about the stack usage by library functions.
- OskarS 5y agoNo, but that's a pretty weak argument not to have them: they're better than nothing. Not all code uses libraries. And if it was part of the C standard, libraries could use them as well: libraries could fail gracefully instead of blowing the stack. Many libraries already do this when malloc fails, after all.
- saagarjha 5y agoI have yet to see a library that fails gracefully when malloc fails. Many claim to be able to do so, but usually keel over when actually presented with a failure.
- PerkinWarwick 5y ago...or much of anything else. I've seen commercial libraries monkey with processor state in some nasty ways.
- nybble41 5y agoThere is also no guarantee that the stack is contiguous—see the "-fsplit-stack" GCC option, or search for "segmented stacks". Libraries for coroutines and delimited continuations also routinely segment the stack. A simple API based around easy access to "top of stack", "bottom of stack", and "current stack pointer" addresses is thus non-universal. There may not be a meaningful limit to the amount of stack available, aside from available heap memory or address space. And this can change over time in response to actions other than allocating or freeing memory on the stack.
- skitter 5y agoWhat are the advantages of low maximum stack size limits (given growable stacks)?
- PerkinWarwick 5y agoOne obvious area is in small embedded systems. It's surprising how hard it can be to track down a stack-caused bug when you've got a bunch of interrupts banging on it. Generally it's a little unnerving to just pray that you've got enough stack given it's hidden usage and the possibility for things like recursion. Kind of a shame considering what a slick way it is to deal with memory leak avoidance.
- deleted 5y ago[deleted]
- DrJokepu 5y agoThis is speculation, but maybe it catches unintended infinite recursion earlier? I’m willing to bet that the vast majority of stack overflows happen due to programming errors rather than genuine uses running out of stack.
- projektfu 5y agoThis is the best answer I could think of. We have to assume the question is about Alpine Linux, not about embedded systems per se. Small thread stacks run out of space quickly (fail fast), help prevent a malicious process from gobbling up lots of VM, and force you to program in a style that doesn't use much stack space, although that's questionable because most memory leaks are heap-based. It's worth noting that the limits are adjustable on a per-package basis in Alpine based on the compiler-time link options.
- jart 5y agoBeing able to build web servers with 10,000 threads w/ clean imperative code rather than event-driven yo-yo pattern finite state machines. It's what Google does. They limit stack size to 60kb for just that reason.
- CJefferson 5y agoThe lack of stack size is one of my continual irritations. It makes it difficult to write tree-searches in the obvious recursive way, because there is a good chance one day you will have an input big enough to overflow the stack. I wish on modern, 64-bit OSes the default thread's stack size was just made a decent size (128MB or even 1GB) -- would it really cost that much (as until the memory was touched it wouldn't really be allocated). Your choices are: * Make a "stack" yourself, in heap memory, and implement your algorithm to manually push/pop from the stack you implemented (often not hard to do, but feels like reimplementing for no reason). * Spawn a new thread, where in most languages you can set the stack size. This is what I tend to do, although it does seem like a waste to have an extra thread for no reason other than to get more stack. You can (in principle) set the stack size when you compile a program, but how to do it seems to differ between OSes and compilers, so I prefer the new thread strategy as an in-language option.
- likeabbas 5y agoCould also be solved if the compiler supported Tail calls optimization
- dnautics 5y agoI don't think tail call will help depth-first ("obvious recursive way") tree algos.
- aidenn0 5y agoIt doesn't help with breadth-first searches either. A non-degenerate tree of depth N will use O(N) space, and that space will be on the call-stack if you use a recursive algorithm to access it. As long as you use less than 1 page per activation record though, most modern libc implementations behave safely under unbounded recursion as they will allocate a guard-page around each stack. [edit] It would also be useful if the compiler could warn about activation records larger than 1 page. Absent alloca (and deprecated c99 VLAs), that should be statically knowable.
- yholio 5y agoSeems like a moot point on any 64 bit platform, where you can effectively reserve GBytes of virtual memory for each of thousands of threads, and page in physical memory as required. It's the only sane interpretation I can give to a standard that hides any way to manage stack usage - the compiler/OS layer takes responsibility.
- noobermin 5y agoIf it's the OS's responsibility then Alpine Linux shouldn't blame developers or say their code isn't "portable."
- aidenn0 5y agoGigabytes for thousands of threads is just barely true; if you reserved say 8GB each for 16k threads, you would just about use up the 47 bits of address space reserved for userland on Linux leaving nothing for text or heap. Certainly a few MB per thread isn't too crazy though; at 8MB per thread, you can have a million threads and use only a tiny fraction of the address space available.
- yholio 5y agoYou could reserve, say, 46 bits for heap and 46 for stack, 70 terabytes each ought to be enough for anybody. Then start allocating thread stack in successive halvings: 2 threads get 35TB each, 65536 threads get 1GB each etc. Effectively, you can make sure the program runs out of available memory long before a stack exhaustion issue, unless the stack usage pattern is severely unbalanced for some thread.
- cryptonector 5y agoAs long as there's a guard page and as long as you can assume that page is at least 4KB in size, you can detect C stack boundaries safely. Basically, don't use alloca() or C99 VLAs, or huge automatics, or, if you do, touch a byte every 4KB in the direction of stack growth before you use bulky stack allocations. I have a macro for this somewhere. Also, this isn't limited to C... The real problem is not that the stack size is invisible to the program, or that you can run out. The real problem is that you can make a stack allocation so large that you might miss the end of the stack and scribble over some other memory. This is why you need to touch a byte ever guard-page-size bytes (in the direction of stack growth) in large stack allocations before using those allocations. What's specific to C is alloca() and C99 VLAs. Not that other languages don't have those, but that in their absence it's extremely unlikely that any function would have a frame so large as to run past the guard page. A maximum frame size can be computed by the compiler in the absence of alloca() or VLAs. Also, the compiler could (and arguably should) generate code to do this touching of a byte every guard-size-bytes thing for dynamically sized stack allocations, which would make the problem disappear. (You could still run out of stack space, but more safely.)
- chrisseaton 5y ago> As long as there's a guard page and as long as you can assume that page is at least 4KB in size, you can detect C stack boundaries safely. How do you do this in pure C?
- cryptonector 5y agoYou're gonna make me dig it out, ain't ya. I don't know where I put it, but I've written a macro and function that does this. Basically, given a pointer and allocation size, if it's smaller than 4KB, do nothing, if it's larger, loop for allocation size div 4KB touching a byte from one end of the allocation to the other. The tricky things are: determining in which direction the stack grows, and the page size (which, arguably, you can hard-code to 4KB) if you really don't want to hard-code 4KB. You can determine stack growth direction by having one function call another with a pointer to a local variable in the former and then compare that to a pointer to a local variable in the latter. To do this correctly you have to cast to uintptr_t. And, yes, pure C does not even assume a stack, much less a bounded stack. In pure C it's possible to have every call frame allocated on the heap, which means that assuming that they are allocated contiguously is not safe. Moreover, even with stacks, the run-time could allocate a second stack when the first is exhausted and push new call frames on the second rather than die. In pure C the only assumptions about limits have to do with the size of size_t. The real world intrudes though, and in practice all C run-times allocate call frames on bounded stacks.
- Spivak 5y agoI don't get Alpine's reasoning here. In order to be portable does every C program have to work with any stack size limit? How could that even work? Without a guaranteed minimum there's nothing to do except "portable to common platforms-ish."
- gpderetta 5y agoDo you know about the shortest fully conforming C compiler? #include <stdio.h> int main(int argc, char*argv[]) { printf("ERROR: resources exhausted!"); return -1; }
- pikhq 5y agoThis article is a bit strange. It's referring to the thread stack size but acting as though it's the main stack size. It's true there's no portable C API for doing anything with the main stack size, but musl libc doesn't behave any differently than glibc here -- the main stack is allocated by the kernel. The thread stack size on musl is small, yes, but the only way to even end up in a thread involves using the pthread API. The pthread API exposes an API for configuring the stack size for a thread; it's called pthread_attr_setstacksize. You can find it here: https://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_attr_setstacksize.html https://pubs.opengroup.org/onlinepubs/9699919799/functions/p... Granted, it is maddening that C does not offer any great ways to reason about what stack size is needed, but it is simply nonsense to imply (as people seem to be inferring here) that there's no way for an application to handle running into musl's stack size limits.
- 12thwonder 5y agomy understanding is that the author is talking about stack usage at runtime not the size of an entire stack which can be set by the pthread API you mentioned. it's confusing because the article starts with a discussion of how default stack size differs depending on a platform.
- titzer 5y agoI just wrestled with this. You cannot effectively handle stack overflow situations if you use the system stack on Linux, because stack segments are in magical "MAP_GROWSDOWN" regions. These regions are managed by the kernel itself. There is a base address and a size, and the kernel initially only maps some small number of pages near the upper end (high addresses). Faulting accesses to addresses that are not mapped, but in the region, just below what is currently mapped cause the kernel to map in new pages automatically, "growing down". The customary way to handle stack overflow gracefully in userland is to install a SIGSEGV handler and check the faulting address to see if it is near the stack segment end, handling the signal on an alternate stack. Except that determining if the access was in the stack segment requires knowing the stack segment start. The signal API doesn't allow querying that; you'd have to query the process's mappings by other means. It's also not robust because a program with big frames might just stride too far and confuse the kernel's automatic growing, causing spurious SIGSEGVs when in fact, there is stack remaining. I found it was just easier to allocate my own stack segment and immediately switch to it and just leave the loader-provided stack segment alone. Virgil does this in the first 50 or so instructions upon entry. This also makes stack overflow very deterministic (only depends on the program) and controllable--there is a compiler option to set the stack size in KiB. There's no need for the compiler to insert strided accesses either, as the whole segment is mapped, and you can have more than a single guard page at the beginning (think: 1MiB guard region). Stack segments in C (and Linux) are madness if you use very much and want anything to be robust to overflow.
- jeffbee 5y agoManaging your own pthread stacks can make thread more costly though, can't it? Use of pthread_set_stack requires stack_size at least PTHREAD_STACK_MIN which on glibc linux tends to be 16384, four times larger than the initial cost of a demand-paged stack map. I understand that on musl this is 2048, so that's nice.
- titzer 5y agoYeah, I think there would be some overhead, because it doesn't look like pthread_create allows specifying a stack segment. But I wouldn't be using pthread_create (or any C library for that matter), because Virgil goes all the way down to kernel; there is no C environment. I only experimented briefly[1] with getting Virgil threads to run on Linux. You need to call SYS_clone, which forks a lightweight process (i.e. shares all virtual memory), and specify a stack segment. The segment in question would of course, be mapped by Virgil and not have MAP_GROWSDOWN, so it could be made robust to stack overflow along the lines above. [1] https://github.com/titzer/virgil/blob/master/apps/Multi/Multi.v3 https://github.com/titzer/virgil/blob/master/apps/Multi/Mult...
- unwind 5y agoIt's interesting that nobody has mentioned the fact that "stack" is a word that is not mentioned in the C standard (caveat: I don't own it. but I just checked in a draft copy). In other words, there is no assumption/guarantee that a C compiler will rely on the machine stack in order to implement certain fetures (i.e. automatic variables, parameter passing, and function call/return). So I guess that means that an imaginary API to query these things should not talk about "stack", since that is making an assumption that is a bit out of line. That does not make naming any easier ... and, as pointed out by vasama, it would be hard to use an API that queries about the current function only. Perhaps something like "autosizeof f" where f is a function could return, at compile-time, the projected "automatic storage size" of the given function (perhaps making it into a compilation error if f() uses VLAs, or calls functions that do), and a runtime "autoleft()" function could be used to determine how much space is left. Uh, no, probably not. These things are hard, and I'm making assumptions about code analysis capabilities that are probably not realistic.
- Joker_vD 5y agoLLVM-MOS targets 6502 and so goes out of its way to use as few of the hardware stack as possible: it does global program optimization, figuring out what calls what, and what functions don't need to be reentrant so it could allocate as many of activation records as possible statically, FORTRAN-style.
- silon42 5y agoI can easily imagine compiler+linker being able to forbid recursion and statically calculate maximum stack needed. Probably you need to ban general function invocation via pointers... methods on objects could be fine, you just evaluate all virtual method override combinations.
- noneeeed 5y agoThe SPARK Ada language prevents recursion by only allowing you to call methods that are defined above the method you are in. It has a similar rule to prevent recursive calls between packages although I forget the details of that. From this you can calculate the worst case stack size. As all other memory has to be statically allocated you can always caclculate the maximum memory footprint of any progam. Obviously those restrictions mean you have to write your code without recursion, but in practice the uses that SPARK is put to don't tend to need it. A statically allocated stack in your code and a loop can solve a lot of problems (along with suitable logic for gracefully handling that stack filling up).
- zabzonk 5y agoHow can you predict how much stack you need? Isn't this basically the halting problem?
- phkahler 5y agoWith the exception of recursion, static analysis can answer that question.
- Verdex 5y agoAs far as I know, there aren't any languages which provide a way to do this out of the box. If a language wants to provide an environment where no stack overflows can happen, then it needs to provide a runtime where the stack programs use is transplanted over to the heap as it gets too large (or maybe it just starts out there). At this point the answer is that you only need a stack big enough to hold your runtime (which you can engineer to be sufficiently small always). Of course you can imagine a language where your function signature includes how much stack space it takes up. The stack size being recursively calculated by looking at all the functions your function calls etc. If recursion is included, then you're correct that this would require solving the halting problem. The obvious solution would be to just not allow recursion. Although, if you also consider languages like Idris (which are technically sometimes not turing complete) you can setup a termination checker and then certain rules can give you an upper bound on how long a recursive function will run (and therefore how much stack it takes up).
- deleted 5y ago[deleted]
- grumpyprole 5y agoA brilliantly written article. Couldn't have said it better myself.
- Koshkin 5y agoHow do functional languages and, in general, the languages where the use of recursion is pervasive - how do they deal with this?
- elipsitz 5y agoIn many cases, with tail call optimization, turning specific types of recursion into iteration (which doesn’t use more than a constant amount of stack space).
- masklinn 5y agoNot tail call optimisation, tail call elimination. If the language is based on recursion, you can't just hope it happens commonly enough, it has to happen all the time, even for corecursive functions. Except I've never been super clear on Haskell having TCE or not, because laziness means there are limited opportunities for it to even fire.
- tome 5y agoBecause function evaluation is lazy all Haskell (well, GHC) calls are tail calls. The only thing that consumes stack is case.
- Verdex 5y agoSo, you can't answer "in general" because things are handled differently depending on the language. I believe Scheme basically only uses the heap (which is necessary because of call/cc iirc). Haskell uses a variation of a G machine (looks like a spineless tagless g machine to be specific). The way that works is that they convert your program into a giant lambda term and then they work on reducing it. This of course looks nothing like a traditional call stack, so you can replace that whole thing with the G machine. Recursion (at least of the non-tail recursive variety) will look like a lambda term slowly getting bigger in heap space. And then I also heard of someone (I forget which language) talking about setting up some logic to look for stack overflows and then throw all the current stack onto a heap and then start over.
- zwieback 5y agoKids these days - let grandpa tell you a story about writing OS/2 1.x device drivers pre-virtual memory. Stack was obsessively monitored, especially in interrupt handlers where you were called with just a few hundred bytes of stack or so. If running low you had to manually switch to your own stack and keep track which one you were on. Excellent point being made about C, though. Amazing how we've lived with this limitation for so long. I get that C is supposed to be portable assembler but the cases where stack wasn't used for return address and local var frames are rare so some support should have been added early on.
- scoutt 5y agoWanna feel that thrill again? Do some bare-metal embedded.
- zwieback 5y agoYeah, I do that quite a bit actually, when I write code for smaller embedded systems I get the same rush I got back on my old Apple ][.
- silon42 5y agoI believe even later, userspace code had to grow stack page by page, no skipping.
- Joker_vD 5y agoThis also makes Chicken Scheme basically guess the stack size: it guesses it's 1 MiB on 64-bit platforms, and 256 KiB on 32-bit ones. Of course, you can also manually override it, at your own risk.
- shadowgovt 5y agoI once worked on a project where we were building a browser plugin in IE (back when plugins existed) and found ourselves needing to use Open Dynamics Engine within the plugin. Under the hood, ODE uses `alloca` a lot... Once per frame to set aside enough RAM to compute a Jacobian that solves for all active collisions. But on Windows, you can configure "redzone protection" to fault the program if the stack takes a flying leap of a (relatively) paltry few kB off the current top of the stack, relative to the default configuration of redzone protection on most single-threaded Windows apps. From ODE's point of view this was fine; they didn't really care about the "compiling on Windows" use case at all and considered our problem to be ours. But this proved disastrous in the context of running on Windows in a thread, and since we were running in IE's process context, we couldn't change the thread allocation rules because they're baked into the process itself. The nice thing about C++ is that the preprocessor is a monster. We #define'd all references to alloca in the ODE codebase away into calls to our own function that returned, instead of a bare pointer, an object with the right pointer-dereference semantics to act like a bare pointer but that was really a reference to a slice of a colossal chunk of heap memory. When the context of the alloca call closed, the returned object was destroyed, and its destructor moved our imaginary "stack" pointer in the big chunk of heap memory back into place. Ugliest thing I ever wrote. ;)
- JoeAltmaier 5y agoTime to abandon stack as a 'display'? That's why they overflow (mostly) - lots of large items or lots of recursion and local variables. Also having the addressable method arguments in the same space as the return address, allows a whole host of other bugs and cracks. I have long thought, the return stack should be a memory region un-addressable by the code except via call and return. Local method arguments could then revert to ordinary allocations or some other check-able allocation, and have normal error recovery.
- rurban 5y agoWell, there's still libsigsegv and its stackoverflow_install_handler. You won't get the size, but get the overflows.
- jeff-davis 5y agoHow does something like Ada help you measure and control stack usage?
- nagisa 5y agoMeasuring of stack requirements is typically implemented by the way of walking the call graph and adding up functions' stack sizes (for usual function these are well known at compile time). There are “only” a couple problematic cases where this algorithm fails: recursion, `alloca` and the likes, and indirect calls. For all of these problems there are more complex analyses that can be done to determine e.g. maximum recursion depth or possible functions that an indirect call could resolve to. And failing all of these there is usually a way for an engineer to override or provide this information.
- coldacid 5y agoYet another feature of Amiga that we don't have in more "modern" systems. You can actually tell the OS how big of a stack to provide to a new task and it'll provide it.
- kragen 5y agoOn Linux you do that with ulimit -s.
- Const-me 5y agoLinux kernel APIs are interesting. Couple days ago I was writing code which needs sendmsg/recvmsg. The manual page says this: Ancillary data should only be accessed by the macros defined in cmsg(3). The problem being, the code I was writing was in C# which can't consume C headers or evaluate these macros.
- kragen 5y agoCan't you write C functions that invoke the cmsg macros and call them from C#?
- Const-me 5y agoSure, but that complicates things. I have reverse-engineered the macros instead. They aren't terribly complicated, they simply rounding up some of the pointers by sizeof(void*).
- kragen 5y agoThat's probably reasonable. The Linux kernel has historically been very good about not breaking existing compiled code by changing ABIs like this.
- mrcode007 5y agoStack size is visible and settable. This article describes a non-issue. A programmer just has to be knowledgable about the tools at his disposal. Here's an example cat <<EOF>demo.c #include <sys/resource.h> #include <stdio.h> #include <unistd.h> int main(int argc, char *argv[], char *envp[]) { struct rlimit rlp = { 0 }; getrlimit(RLIMIT_STACK, &rlp); printf("stack size=%llu\n", rlp.rlim_cur); if (rlp.rlim_cur < rlp.rlim_max) { printf("setting stack size to %llu\n", rlp.rlim_max); rlp.rlim_cur = rlp.rlim_max; setrlimit(RLIMIT_STACK, &rlp); execve(argv[0], argv, envp); } } EOF make demo ./demo Similarly, there is pthread_attr_setstacksize(3), which does the obvious thing for threads.