Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
aos
GitHub Repository: aos/firecracker
Path: blob/main/tests/host_tools/readmem.c
1956 views
1
// Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
// SPDX-License-Identifier: Apache-2.0
3
4
// This is a balloon device helper tool, which allocates an amount of
5
// memory, given as the first starting parameter, and then tries to find
6
// 4 consecutive occurences of an integer, given as the second starting
7
// parameter, in that memory chunk. The program returns 1 if it succeeds
8
// in finding these occurences, 0 otherwise. After performing a deflate
9
// operation on the balloon device, we run this program with the second
10
// starting parameter equal to `1`, which is the value we are using to
11
// write in memory when dirtying it with `fillmem`. If the memory is
12
// indeed scrubbed, we won't be able to find any 4 consecutive occurences
13
// of the integer `1` in newly allocated memory.
14
15
#define _GNU_SOURCE
16
17
#include <stdio.h>
18
#include <stdlib.h>
19
#include <string.h>
20
#include <sys/mman.h>
21
22
#define MB (1024 * 1024)
23
24
25
int read_mem(int mb_count, int value) {
26
int i;
27
char *ptr = NULL;
28
int *cur = NULL;
29
int buf[4] = { value };
30
31
do {
32
ptr = mmap(
33
NULL,
34
mb_count * MB * sizeof(char),
35
PROT_READ | PROT_WRITE,
36
MAP_ANONYMOUS | MAP_PRIVATE,
37
-1,
38
0
39
);
40
} while (ptr == MAP_FAILED);
41
42
cur = (int *) ptr;
43
// We will go through all the memory allocated with an `int` pointer,
44
// so we have to divide the amount of bytes available by the size of
45
// `int`. Furthermore, we compare 4 `int`s at a time, so we will
46
// divide the upper limit of the loop by 4 and also increment the index
47
// by 4.
48
for (i = 0; i < (mb_count * MB * sizeof(char)) / (4 * sizeof(int)); i += 4) {
49
if (memcmp(cur, buf, 4 * sizeof(int)) == 0) {
50
return 1;
51
}
52
}
53
54
return 0;
55
}
56
57
58
int main(int argc, char *const argv[]) {
59
60
if (argc != 3) {
61
printf("Usage: ./readmem mb_count value\n");
62
return -1;
63
}
64
65
int mb_count = atoi(argv[1]);
66
int value = atoi(argv[2]);
67
68
return read_mem(mb_count, value);
69
}
70
71