xref: /aosp_15_r20/external/ltp/testcases/kernel/syscalls/mmap/mmap09.c (revision 49cdfc7efb34551c7342be41a7384b9c40d7cab7)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 
3 /*
4  * Copyright (c) International Business Machines  Corp., 2003
5  * Author: by Paul Larson
6  * Copyright (C) 2024 SUSE LLC Andrea Manzini <[email protected]>
7  */
8 
9 /*\
10  * [Description]
11  *
12  * Verify that truncating a mmaped file works correctly.
13  *
14  * Use ftruncate to:
15  *
16  * 1. shrink the file while it is mapped
17  * 2. grow the file while it is mapped
18  * 3. zero the size of the file while it is mapped
19  */
20 
21 #include "tst_test.h"
22 
23 /* size of the test file = 64 KB */
24 #define MAPSIZE (64 * 1024)
25 
26 static int fd;
27 static char *maddr;
28 
29 static struct test_case
30 {
31 	off_t newsize;
32 	char *desc;
33 } tcases[] = {
34 	{MAPSIZE - 8192, "ftruncate mmaped file to a smaller size"},
35 	{MAPSIZE + 1024, "ftruncate mmaped file to a larger size"},
36 	{0, "ftruncate mmaped file to 0 size"},
37 };
38 
verify_mmap(unsigned int nr)39 static void verify_mmap(unsigned int nr)
40 {
41 	struct test_case *tc = &tcases[nr];
42 
43 	TST_EXP_PASS(ftruncate(fd, tc->newsize), "%s", tc->desc);
44 }
45 
setup(void)46 static void setup(void)
47 {
48 	fd = SAFE_OPEN("/tmp/mmaptest", O_RDWR | O_CREAT, 0666);
49 
50 	/* set the file to initial size */
51 	SAFE_FTRUNCATE(fd, MAPSIZE);
52 	maddr = SAFE_MMAP(0, MAPSIZE, PROT_READ | PROT_WRITE, MAP_FILE | MAP_SHARED, fd, 0);
53 
54 	/* fill up the file with A's */
55 	memset(maddr, 'A', MAPSIZE);
56 }
57 
cleanup(void)58 static void cleanup(void)
59 {
60 	if (maddr)
61 		SAFE_MUNMAP(maddr, MAPSIZE);
62 
63 	if (fd)
64 		SAFE_CLOSE(fd);
65 }
66 
67 static struct tst_test test = {
68 	.setup = setup,
69 	.cleanup = cleanup,
70 	.test = verify_mmap,
71 	.tcnt = ARRAY_SIZE(tcases),
72 	.needs_tmpdir = 1,
73 };
74