Created
November 11, 2014 16:46
-
-
Save weissi/50930f3898bdc18c63e0 to your computer and use it in GitHub Desktop.
Program to leak shared memory on OS X
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 <stdio.h> | |
#include <sys/mman.h> | |
#include <string.h> | |
#include <unistd.h> | |
#include <fcntl.h> | |
#include <errno.h> | |
int main() | |
{ | |
int err = 0; | |
const size_t size = 100 * 1024 * 1024; | |
char *shm_name = NULL; | |
asprintf(&shm_name, "shm-foo-%d", getpid()); | |
printf("shm name: '%s'\n", shm_name); | |
int fd = shm_open(shm_name, O_CREAT | O_RDWR, 0644); | |
if (fd < 0) { | |
perror("shm_open"); | |
return 1; | |
} | |
err = shm_unlink(shm_name); | |
if (err) { | |
perror("shm_unlink"); | |
return 1; | |
} | |
err = ftruncate(fd, size); | |
if (err) { | |
perror("ftruncate"); | |
return 1; | |
} | |
char *mem = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_FILE | MAP_SHARED, fd, 0); | |
if (MAP_FAILED == mem) { | |
perror("mmap"); | |
close(fd); | |
return 1; | |
} | |
if ('A' == *mem) { | |
printf("FILLED\n"); | |
} else { | |
printf("not filled (%c)\n", *mem); | |
} | |
memset(mem, 'A', size); | |
pid_t pid = fork(); | |
if (pid > 0) { | |
/* parent */ | |
} else if (0 == pid) { | |
/* child */ | |
sleep(10); | |
err = close(fd); | |
if (err) { | |
perror("close child"); | |
return 1; | |
} | |
err = munmap(mem, size); | |
if (err) { | |
perror("munmap child"); | |
return 1; | |
} | |
printf("should be freed now\n"); | |
return 0; | |
} else { | |
perror("fork"); | |
return 1; | |
} | |
err = close(fd); | |
if (err) { | |
perror("close"); | |
return 1; | |
} | |
err = munmap(mem, size); | |
if (err) { | |
perror("munmap"); | |
close(fd); | |
return 1; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment