Skip to content

Instantly share code, notes, and snippets.

@azat

azat/test_vma.c

Created Dec 8, 2020
Embed
What would you like to do?
#include <sys/mman.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <assert.h>
#include <string.h>
void* mmap_hint()
{
#ifdef MMAP_HINT
return rand() * 1<<16;
#else
return 0;
#endif
}
size_t subchr_count(const char *str, char s)
{
size_t n = 0;
char *begin = (char *)str;
while ((begin = strchr(begin, s)) != NULL) {
++begin;
++n;
}
return n;
}
size_t get_vmas()
{
size_t n = 0;
/// NOTE: cannot use fopen() since it creates buffer via mmap
int fd = open("/proc/self/maps", O_RDONLY);
assert(fd >= 0);
char buffer[4096];
while (read(fd, buffer, sizeof(buffer)) > 0) {
n += subchr_count(buffer, '\n');
}
close(fd);
return n;
}
int main()
{
void *addr;
for (size_t i = 0; i < 100; ++i) {
addr = mmap(mmap_hint(), 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
fprintf(stdout, "vmas: %zu\n", get_vmas());
}
return 0;
}
$ /tmp/test_vma | uniq -c
1 vmas: 22
99 vmas: 23
$ gcc -g3 -o /tmp/test_vma_hint -DMMAP_HINT /tmp/test_vma.c
$ /tmp/test_vma_hint | uniq -c | head
1 vmas: 22
1 vmas: 24
1 vmas: 25
2 vmas: 26
2 vmas: 27
1 vmas: 28
1 vmas: 29
1 vmas: 30
2 vmas: 31
1 vmas: 32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment