Skip to content

Instantly share code, notes, and snippets.

@thestinger
Last active September 26, 2019 20:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thestinger/200cfcb6a53e177902e17ef526ed2bab to your computer and use it in GitHub Desktop.
Save thestinger/200cfcb6a53e177902e17ef526ed2bab to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <unistd.h>
// Alternatively, /dev/shm/test, /var/tmp/test, /home/username/test, /home/.local/share/appname/test, etc.
static const char *const path = "/tmp/test";
static const char code[] = "\xeb\x1e\x5e\x48\x31\xc0\xb0\x01\x48\x89\xc7\x48\x89\xfa\x48\x83\xc2\x0e\x0f\x05\x48\x31\xc0\x48\x83\xc0\x3c\x48\x31\xff\x0f\x05\xe8\xdd\xff\xff\xff\x48\x65\x6c\x6c\x6f\x2c\x20\x77\x6f\x72\x6c\x64\x21\x0a";
int main(void) {
size_t len = 4096;
int fd = open("/tmp/test", O_RDWR|O_CREAT, 0700);
if (fd == -1) {
perror("shm_open");
return 1;
}
if (ftruncate(fd, len) == -1) {
perror("ftruncate");
return 1;
}
void *rw = mmap(NULL, len, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
if (rw == MAP_FAILED) {
perror("mmap");
return 1;
}
void *rx = mmap(NULL, len, PROT_READ|PROT_EXEC, MAP_SHARED, fd, 0);
if (rx == MAP_FAILED) {
perror("mmap");
return 1;
}
memcpy(rw, code, sizeof(code));
(*(void(*)()) rx)();
close(fd);
if (unlink("/tmp/test") == -1) {
perror("unlink");
return 1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment