Created
January 29, 2014 01:04
-
-
Save graphitemaster/8679762 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 <sys/types.h> | |
| #include <sys/stat.h> | |
| #include <sys/file.h> | |
| #include <sys/mman.h> | |
| #include <sys/wait.h> | |
| #include <fcntl.h> | |
| #include <unistd.h> | |
| #include <stdio.h> | |
| #include <stdlib.h> | |
| #include <string.h> | |
| #include <errno.h> | |
| static void fail_(const char *message, const char *file, size_t line) { | |
| fprintf(stderr, "failed: %s %s (%s:%zu)\n", message, strerror(errno), file, line); | |
| abort(); | |
| } | |
| #define fail(X) fail_((X), __FILE__, __LINE__) | |
| int main(int argc, char **argv) { | |
| // got restart, grab the fd and print leet | |
| if (!strncmp(*argv, "-r", 2)) { | |
| argv++; | |
| struct stat buf; | |
| int fd; | |
| char *scan = &argv[0][2]; | |
| sscanf(scan, "%d", &fd); | |
| if (fstat(fd, &buf) != 0) fail("fstat"); | |
| void *mem = mmap(0, buf.st_size, PROT_READ, MAP_SHARED, fd, 0); | |
| if (mem == MAP_FAILED) fail("mmap"); | |
| if (munmap(mem, buf.st_size) != 0) fail("munmap"); | |
| if (shm_unlink("test_case") != 0) fail("shm_unlink"); | |
| printf("%d!\n", *((int*)mem)); | |
| return EXIT_SUCCESS; | |
| } | |
| // get shared memory (create trun read/write) | |
| int fd = shm_open("test_case", O_CREAT | O_TRUNC | O_RDWR, 0666); | |
| if (fd == -1) fail("shm_open"); | |
| // unset FD_CLOEXEC | |
| int flags = fcntl(fd, F_GETFD); | |
| flags &= ~FD_CLOEXEC; | |
| fcntl(fd, F_SETFD, flags); | |
| // rounded to nearest page multiply alloc (sizeof(int) chars for testcase) | |
| // will become PAGE_SIZE in this case. | |
| size_t size = sizeof(int); | |
| const size_t pagesize = sysconf(_SC_PAGE_SIZE); | |
| size = ((size + pagesize - 1) / pagesize) * pagesize; | |
| // truncate | |
| int truncate = ftruncate(fd, size); | |
| if (truncate != 0) fail("ftruncate"); | |
| // grab the memory | |
| void *memory = mmap(0, pagesize, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); | |
| if (memory == MAP_FAILED) fail("mmap"); | |
| // write leet | |
| *((int*)memory) = 1337; | |
| // run the process now | |
| char buffer[1024]; | |
| snprintf(buffer, sizeof(buffer), "-r%d", fd); | |
| execv(*argv, (char *[]){ buffer, *argv, (char *)0 }); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment