Skip to content

Instantly share code, notes, and snippets.

@timtadh
Last active November 19, 2015 18:31
Show Gist options
  • Save timtadh/3d6ab5681a85ab00801c to your computer and use it in GitHub Desktop.
Save timtadh/3d6ab5681a85ab00801c to your computer and use it in GitHub Desktop.
mmap-test
*swp
*swo
*.o
mmtest
%.o:%.c
gcc -c -g -m32 -o $@ $<
mmtest: mmtest.o
gcc -g -m32 -o $@ $^
mmtest.o: mmtest.c
.PHONY: clean
clean:
-@rm *.o main &> /dev/null
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int pmap() {
char buf[4096];
snprintf(buf, 4096, "vmmap %d", getpid()); // darwin version
// snprintf(buf, 4096, "pmap %d", getpid()); // linux version
system(buf);
}
int main(int argc, char **argv) {
size_t LEN = 4096;
void *addr = NULL;
void *addr2 = NULL;
int err = 0;
int *arr = NULL;
int i = 0;
addr = mmap( NULL, LEN, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_SHARED, -1, 0);
fprintf(stderr, "mmap addr %p\n", addr);
if (addr == MAP_FAILED) {
int err = errno;
char *msg = NULL;
errno = 0;
msg = strerror(err);
fprintf(stderr, "mmap error %s\n", msg);
return -1;
}
arr = (int *)addr;
for (i = 0; i < LEN/4; i++) {
arr[i] = i;
}
fprintf(stderr, "expected mmap addr2 %p\n", addr + LEN);
addr2 = mmap(addr + LEN, LEN, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_SHARED | MAP_FIXED, -1, 0);
if (addr2 == MAP_FAILED) {
int err = errno;
char *msg = NULL;
errno = 0;
msg = strerror(err);
fprintf(stderr, "mmap error %s\n", msg);
return -1;
}
fprintf(stderr, "mmap addr2 %p\n", addr2);
pmap();
for (i = LEN/4; i < (LEN*2)/4; i++) {
arr[i] = 0xff;
}
for (i = 0; i < (LEN*2)/4; i++) {
fprintf(stdout, "arr %d %d\n", i, arr[i]);
}
err = munmap(addr, LEN * 2);
if (err != 0) {
int err = errno;
char *msg = NULL;
errno = 0;
msg = strerror(err);
fprintf(stderr, "munmap error %s\n", msg);
return -1;
}
pmap();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment