Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
aos
GitHub Repository: aos/firecracker
Path: blob/main/tests/host_tools/fillmem.c
1956 views
1
// Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
// SPDX-License-Identifier: Apache-2.0
3
4
#define _GNU_SOURCE
5
6
#include <stdio.h>
7
#include <stdlib.h>
8
#include <string.h>
9
#include <unistd.h>
10
#include <errno.h>
11
#include <sys/types.h>
12
#include <sys/wait.h>
13
#include <sys/stat.h>
14
#include <sys/mman.h>
15
#include <fcntl.h>
16
17
18
#define MB (1024 * 1024)
19
20
21
int fill_mem(int mb_count) {
22
int i, j;
23
char *ptr = NULL;
24
for(j = 0; j < mb_count; j++) {
25
do {
26
// We can't map the whole chunk of memory at once because
27
// in case the system is already in a memory pressured
28
// state and we are trying to achieve a process death by
29
// OOM killer, a large allocation is far less likely to
30
// succeed than more granular ones.
31
ptr = mmap(
32
NULL,
33
MB * sizeof(char),
34
PROT_READ | PROT_WRITE,
35
MAP_ANONYMOUS | MAP_PRIVATE,
36
-1,
37
0
38
);
39
} while (ptr == MAP_FAILED);
40
memset(ptr, 1, MB * sizeof(char));
41
}
42
43
return 0;
44
}
45
46
47
int main(int argc, char *const argv[]) {
48
49
if (argc != 2) {
50
printf("Usage: ./fillmem mb_count\n");
51
return -1;
52
}
53
54
int mb_count = atoi(argv[1]);
55
56
int pid = fork();
57
if (pid == 0) {
58
return fill_mem(mb_count);
59
} else {
60
int status;
61
wait(&status);
62
int fd = open("/tmp/fillmem_output.txt", O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IXUSR);
63
if (fd < 0) {
64
return -1;
65
}
66
67
if (WIFSIGNALED(status)) {
68
char buf[200];
69
sprintf(buf, "OOM Killer stopped the program with signal %d, exit code %d\n", WTERMSIG(status), WEXITSTATUS(status));
70
write(fd, buf, strlen(buf) + 1);
71
} else {
72
write(fd, "Memory filling was successful\n", 31);
73
}
74
75
close(fd);
76
return 0;
77
}
78
}
79
80