Skip to content

Instantly share code, notes, and snippets.

@srpatcha
Created August 29, 2019 02:53
Show Gist options
  • Save srpatcha/d6e24d5676e329c2f63cf74e7ce5c597 to your computer and use it in GitHub Desktop.
Save srpatcha/d6e24d5676e329c2f63cf74e7ce5c597 to your computer and use it in GitHub Desktop.
growing downwards on a fault" behavior for virtual memory can be requested by arbitrary user programs with the MAP_GROWSDOWN flag being passed to the mmap syscall.
/* find the pid of the program (via ps) and look at /proc/$THIS_PID/maps */
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/mman.h>
int main() {
long page_size = sysconf(_SC_PAGE_SIZE);
void *mem = mmap(NULL, page_size, PROT_READ|PROT_WRITE, MAP_GROWSDOWN|MAP_ANONYMOUS|MAP_PRIVATE, -1, 0);
if (MAP_FAILED == mem) {
perror("failed to create growsdown mapping");
return EXIT_FAILURE;
}
volatile char *tos = (char *) mem + page_size;
int i;
for (i = 1; i < 10 * page_size; ++i)
tos[-i] = 42;
fprintf(stderr, "inspect mappping for originally page-sized %p in /proc... press any key to continue...\n", mem);
(void) getchar();
if (munmap(mem, page_size))
perror("failed munmap");
return EXIT_SUCCESS;
}
@srpatcha
Copy link
Author

stack grow dynamically.
It is in the top of the memory growing downwards towards the heap.

@srpatcha
Copy link
Author

/* it can help to get PID of processor*/

#include/asm/smp.h
static int my_cpu() {
return smp_processor_id();
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment