// Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.1// SPDX-License-Identifier: Apache-2.023// This is a balloon device helper tool, which allocates an amount of4// memory, given as the first starting parameter, and then tries to find5// 4 consecutive occurences of an integer, given as the second starting6// parameter, in that memory chunk. The program returns 1 if it succeeds7// in finding these occurences, 0 otherwise. After performing a deflate8// operation on the balloon device, we run this program with the second9// starting parameter equal to `1`, which is the value we are using to10// write in memory when dirtying it with `fillmem`. If the memory is11// indeed scrubbed, we won't be able to find any 4 consecutive occurences12// of the integer `1` in newly allocated memory.1314#define _GNU_SOURCE1516#include <stdio.h>17#include <stdlib.h>18#include <string.h>19#include <sys/mman.h>2021#define MB (1024 * 1024)222324int read_mem(int mb_count, int value) {25int i;26char *ptr = NULL;27int *cur = NULL;28int buf[4] = { value };2930do {31ptr = mmap(32NULL,33mb_count * MB * sizeof(char),34PROT_READ | PROT_WRITE,35MAP_ANONYMOUS | MAP_PRIVATE,36-1,37038);39} while (ptr == MAP_FAILED);4041cur = (int *) ptr;42// We will go through all the memory allocated with an `int` pointer,43// so we have to divide the amount of bytes available by the size of44// `int`. Furthermore, we compare 4 `int`s at a time, so we will45// divide the upper limit of the loop by 4 and also increment the index46// by 4.47for (i = 0; i < (mb_count * MB * sizeof(char)) / (4 * sizeof(int)); i += 4) {48if (memcmp(cur, buf, 4 * sizeof(int)) == 0) {49return 1;50}51}5253return 0;54}555657int main(int argc, char *const argv[]) {5859if (argc != 3) {60printf("Usage: ./readmem mb_count value\n");61return -1;62}6364int mb_count = atoi(argv[1]);65int value = atoi(argv[2]);6667return read_mem(mb_count, value);68}697071