xref: /aosp_15_r20/external/ltp/testcases/kernel/syscalls/mmap/mmap08.c (revision 49cdfc7efb34551c7342be41a7384b9c40d7cab7)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Copyright (c) International Business Machines  Corp., 2001
4  *  07/2001 Ported by Wayne Boyer
5  * Copyright (c) 2023 SUSE LLC Avinesh Kumar <[email protected]>
6  */
7 
8 /*\
9  * [Description]
10  *
11  * Verify that, mmap() calls fails with errno EBADF when a file mapping
12  * is requested but the fd is not a valid file descriptor.
13  */
14 
15 #include <stdlib.h>
16 #include "tst_test.h"
17 
18 #define TEMPFILE "mmapfile"
19 static size_t page_sz;
20 static int fd;
21 
setup(void)22 static void setup(void)
23 {
24 	fd = SAFE_OPEN(TEMPFILE, O_RDWR | O_CREAT, 0666);
25 	SAFE_CLOSE(fd);
26 }
27 
run(void)28 static void run(void)
29 {
30 	TST_EXP_FAIL_PTR_VOID(mmap(NULL, page_sz, PROT_WRITE,
31 				   MAP_FILE | MAP_SHARED, fd, 0), EBADF);
32 
33 	if (TST_RET_PTR != MAP_FAILED)
34 		SAFE_MUNMAP(TST_RET_PTR, page_sz);
35 }
36 
cleanup(void)37 static void cleanup(void)
38 {
39 	if (fd > 0)
40 		SAFE_CLOSE(fd);
41 }
42 
43 static struct tst_test test = {
44 	.setup = setup,
45 	.cleanup = cleanup,
46 	.test_all = run,
47 	.needs_tmpdir = 1
48 };
49