1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
|
// One of everything the kernel can report about a program, in this order:
// fresh pages touched one by one (argv[1] of them, default 64), a global
// written and a function called (argv[2] times, default 100), a block
// allocated, a file opened and written, a sleep, a thread that calls the
// function three more times.
#include <fcntl.h>
#include <pthread.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <time.h>
#include <unistd.h>
volatile unsigned long counter;
__attribute__((noinline)) unsigned long step(unsigned long i, unsigned long acc) {
counter = acc + i;
return acc + i;
}
static void *worker(void *arg) {
unsigned long acc = 0;
for (unsigned long i = 1000; i < 1003; i++) acc = step(i, acc);
return arg;
}
int main(int argc, char **argv) {
unsigned long pages = argc > 1 ? strtoul(argv[1], 0, 0) : 64;
unsigned long steps = argc > 2 ? strtoul(argv[2], 0, 0) : 100;
volatile char *fresh = mmap(0, pages * 4096, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
// A page a fault, however many: no huge ones.
madvise((void *)fresh, pages * 4096, MADV_NOHUGEPAGE);
for (unsigned long i = 0; i < pages; i++) fresh[i * 4096] = 1;
unsigned long acc = 0;
for (unsigned long i = 0; i < steps; i++) acc = step(i, acc);
void *volatile block = malloc(1000 + steps);
free(block);
int fd = open("/dev/null", O_WRONLY);
if (write(fd, "hello", 5) != 5) return 1;
close(fd);
nanosleep(&(struct timespec){.tv_nsec = 2000000}, 0);
pthread_t thread;
pthread_create(&thread, 0, worker, 0);
pthread_join(thread, 0);
return acc == steps * (steps - 1) / 2 ? 0 : 1;
}
|