Last active
September 28, 2022 05:16
-
-
Save shepgoba/d5e602782456b59fd370675de2886765 to your computer and use it in GitHub Desktop.
Using heap memory as the stack in C (little experiment on amd64 in C)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdlib.h> | |
#include <stdio.h> | |
#include <stdint.h> | |
__attribute__((noinline)) | |
void _main() { | |
int troll; | |
printf("sussy, %p\n", &troll); | |
} | |
static uint64_t old_sp; | |
int main() { | |
register volatile uint64_t rsp asm("rsp"); | |
old_sp = rsp; | |
void *new_stack = malloc(33554432); | |
if (!new_stack) { | |
printf("Failed to allocate new stack\n"); | |
return -1; | |
} | |
volatile void *new_sp = new_stack + 33554432; | |
asm volatile("movq %0, %%rsp" | |
:: "r" (new_sp) | |
); | |
_main(); | |
asm volatile("movq %0, %%rsp" | |
:: "r" (old_sp) | |
); | |
free(new_stack); | |
printf("stack @ %p retained, with new sp @ %p!\n", old_sp, new_sp); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment