logoalt Hacker News

12_throw_awayyesterday at 7:07 PM5 repliesview on HN

> The obvious issue is that you can't know how much space is left on the stack [...]

Oh, huh. I've never actually tried it, but I always assumed it would be possible to calculate this, at least for a given OS / arch. You just need 3 quantities, right? `remaining_stack_space = $stack_address - $rsp - $system_stack_size`.

But I guess there's no API for a program to get its own stack address unless it has access to `/proc/$pid/maps` or similar?


Replies

chuckadamsyesterday at 7:30 PM

If your API includes inline assembly, then it's trivial. Go's internals would need it to swap stacks like it does. But I doubt any of that is exposed at the language level.

fluntcapsyesterday at 8:26 PM

You can do something like:

    void *get_sp(void) {
        volatile char c;
        return (void *)&c;
    }
Or, in GCC and Clang:

    void *get_sp(void) {
        return __builtin_frame_address(0);
    }
Which gets you close enough.
Joker_vDyesterday at 7:35 PM

> $system_stack_size

Does such thing even exist? And non-64 bit platforms the address space is small enough that with several threads of execution you may just be unable to grow your stack even up to $system_stack_size because it'd bump into something else.

show 1 reply
wat10000yesterday at 9:06 PM

It's certainly possible on some systems. Even then, you have to fudge, as you don't know exactly how much stack space you need to save for other things.

Stack memory is weird in general. It's usually a fixed amount determined when the thread starts, with the size typically determined by vibes or "seems to work OK." Most programmers don't have much of a notion of how much stack space their code needs, or how much their program needs overall. We know that unbounded non-tail recursion can overflow the stack, but how about bounded-but-large? At what point do you need to start considering such things? A hundred recursive calls? A thousand? A million?

It's all kind of sketchy, but it works well enough in practice, I suppose.

show 1 reply