Stack directions
Writeups for this fancy problem #
The problem is:
How would you compute that the stack grows downwards/upwards (in C/C++).
Credits: LowLevelLearning (YouTube)
Inline Assembly #
The following code is applicable to a x64-bit machine.
As the function get_rsp
has a constant stack frame, we can rely on the number to deduce whether the stack grows upwards/downwards.
uint64_t get_rsp() {
asm("movq %rsp, %rax");
}
int main(int argc, char** argv) {
uint64_t rsp1 = get_rsp();
printf("rsp = %p\n", rsp1);
asm("pushq $0xa");
uint64_t rsp2 = get_rsp();
printf("rsp = %p\n", rsp2);
printf("Stack grows downwards, so : %d\n", rsp1 > rsp2);
asm("popq %rax");
}
Recursion #
The following code is cross-platform. It uses recursion to obtain a new stack frame on top of the original stack frame and obtains the pointer of the old number and does comparision.
bool up_or_down(int* ptr) {
int x = 1;
if (ptr != NULL) {
return &x < ptr;
} else {
return up_or_down(&x);
}
}
int main(int argc, char** argv) {
if (up_or_down(NULL)) {
printf("Stack grows downwards");
} else {
printf("Stack grows upwards");
}
}
Alloca #
The following code uses alloca
to get two seperate regions on the stack at runtime.
int main(int argc, char** argv) {
int* x = alloca(0xf);
int* y = alloca(0xf);
printf("x = %p, y = %p\n", x, y);
if (&x > &y) {
printf("Stack grows downwards!");
} else {
printf("Stack grows upwards");
}
}
More solutions coming soon!