1f08c3bdfSopenharmony_ci// SPDX-License-Identifier: GPL-2.0-or-later
2f08c3bdfSopenharmony_ci/*
3f08c3bdfSopenharmony_ci * Copyright (c) International Business Machines  Corp., 2001
4f08c3bdfSopenharmony_ci *  07/2001 Ported by Wayne Boyer
5f08c3bdfSopenharmony_ci * Copyright (c) 2023 SUSE LLC Avinesh Kumar <avinesh.kumar@suse.com>
6f08c3bdfSopenharmony_ci */
7f08c3bdfSopenharmony_ci
8f08c3bdfSopenharmony_ci/*\
9f08c3bdfSopenharmony_ci * [Description]
10f08c3bdfSopenharmony_ci *
11f08c3bdfSopenharmony_ci * verify that, mmap() calls fails with errno EBADF when a file mapping
12f08c3bdfSopenharmony_ci * is requested but the fd is not a valid file descriptor.
13f08c3bdfSopenharmony_ci */
14f08c3bdfSopenharmony_ci
15f08c3bdfSopenharmony_ci#include <stdlib.h>
16f08c3bdfSopenharmony_ci#include "tst_test.h"
17f08c3bdfSopenharmony_ci
18f08c3bdfSopenharmony_ci#define TEMPFILE "mmapfile"
19f08c3bdfSopenharmony_cistatic size_t page_sz;
20f08c3bdfSopenharmony_cistatic int fd;
21f08c3bdfSopenharmony_ci
22f08c3bdfSopenharmony_cistatic void setup(void)
23f08c3bdfSopenharmony_ci{
24f08c3bdfSopenharmony_ci	fd = SAFE_OPEN(TEMPFILE, O_RDWR | O_CREAT, 0666);
25f08c3bdfSopenharmony_ci	SAFE_CLOSE(fd);
26f08c3bdfSopenharmony_ci}
27f08c3bdfSopenharmony_ci
28f08c3bdfSopenharmony_cistatic void run(void)
29f08c3bdfSopenharmony_ci{
30f08c3bdfSopenharmony_ci	TESTPTR(mmap(NULL, page_sz, PROT_WRITE, MAP_FILE | MAP_SHARED, fd, 0));
31f08c3bdfSopenharmony_ci
32f08c3bdfSopenharmony_ci	if (TST_RET_PTR != MAP_FAILED) {
33f08c3bdfSopenharmony_ci		tst_res(TFAIL, "mmap() passed unexpectedly");
34f08c3bdfSopenharmony_ci		SAFE_MUNMAP(TST_RET_PTR, page_sz);
35f08c3bdfSopenharmony_ci	} else if (TST_ERR == EBADF) {
36f08c3bdfSopenharmony_ci		tst_res(TPASS, "mmap() failed with EBADF");
37f08c3bdfSopenharmony_ci	} else {
38f08c3bdfSopenharmony_ci		tst_res(TFAIL | TERRNO, "mmap() failed with an invalid errno");
39f08c3bdfSopenharmony_ci	}
40f08c3bdfSopenharmony_ci}
41f08c3bdfSopenharmony_ci
42f08c3bdfSopenharmony_cistatic void cleanup(void)
43f08c3bdfSopenharmony_ci{
44f08c3bdfSopenharmony_ci	if (fd > 0)
45f08c3bdfSopenharmony_ci		SAFE_CLOSE(fd);
46f08c3bdfSopenharmony_ci}
47f08c3bdfSopenharmony_ci
48f08c3bdfSopenharmony_cistatic struct tst_test test = {
49f08c3bdfSopenharmony_ci	.setup = setup,
50f08c3bdfSopenharmony_ci	.cleanup = cleanup,
51f08c3bdfSopenharmony_ci	.test_all = run,
52f08c3bdfSopenharmony_ci	.needs_tmpdir = 1
53f08c3bdfSopenharmony_ci};
54