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() call with PROT_READ and a file descriptor which is
12f08c3bdfSopenharmony_ci * open for read only, succeeds to map a file creating mapped memory with
13f08c3bdfSopenharmony_ci * read access.
14f08c3bdfSopenharmony_ci */
15f08c3bdfSopenharmony_ci
16f08c3bdfSopenharmony_ci#include <stdlib.h>
17f08c3bdfSopenharmony_ci#include "tst_test.h"
18f08c3bdfSopenharmony_ci
19f08c3bdfSopenharmony_ci#define TEMPFILE "mmapfile"
20f08c3bdfSopenharmony_cistatic ssize_t page_sz;
21f08c3bdfSopenharmony_cistatic int fd;
22f08c3bdfSopenharmony_cistatic char *addr;
23f08c3bdfSopenharmony_cistatic char *buf;
24f08c3bdfSopenharmony_ci
25f08c3bdfSopenharmony_cistatic void setup(void)
26f08c3bdfSopenharmony_ci{
27f08c3bdfSopenharmony_ci	page_sz = getpagesize();
28f08c3bdfSopenharmony_ci	buf = SAFE_MALLOC(page_sz);
29f08c3bdfSopenharmony_ci	memset(buf, 'A', page_sz);
30f08c3bdfSopenharmony_ci
31f08c3bdfSopenharmony_ci	fd = SAFE_OPEN(TEMPFILE, O_RDWR | O_CREAT, 0666);
32f08c3bdfSopenharmony_ci	SAFE_WRITE(SAFE_WRITE_ALL, fd, buf, page_sz);
33f08c3bdfSopenharmony_ci
34f08c3bdfSopenharmony_ci	SAFE_FCHMOD(fd, 0444);
35f08c3bdfSopenharmony_ci	SAFE_CLOSE(fd);
36f08c3bdfSopenharmony_ci	fd = SAFE_OPEN(TEMPFILE, O_RDONLY);
37f08c3bdfSopenharmony_ci}
38f08c3bdfSopenharmony_ci
39f08c3bdfSopenharmony_cistatic void run(void)
40f08c3bdfSopenharmony_ci{
41f08c3bdfSopenharmony_ci	addr = SAFE_MMAP(NULL, page_sz, PROT_READ, MAP_FILE | MAP_SHARED, fd, 0);
42f08c3bdfSopenharmony_ci
43f08c3bdfSopenharmony_ci	if (memcmp(buf, addr, page_sz) == 0)
44f08c3bdfSopenharmony_ci		tst_res(TPASS, "mmap() functionality successful");
45f08c3bdfSopenharmony_ci	else
46f08c3bdfSopenharmony_ci		tst_res(TFAIL, "mapped memory area contains invalid data");
47f08c3bdfSopenharmony_ci
48f08c3bdfSopenharmony_ci	SAFE_MUNMAP(addr, page_sz);
49f08c3bdfSopenharmony_ci}
50f08c3bdfSopenharmony_ci
51f08c3bdfSopenharmony_cistatic void cleanup(void)
52f08c3bdfSopenharmony_ci{
53f08c3bdfSopenharmony_ci	if (fd > 0)
54f08c3bdfSopenharmony_ci		SAFE_CLOSE(fd);
55f08c3bdfSopenharmony_ci
56f08c3bdfSopenharmony_ci	free(buf);
57f08c3bdfSopenharmony_ci}
58f08c3bdfSopenharmony_ci
59f08c3bdfSopenharmony_cistatic struct tst_test test = {
60f08c3bdfSopenharmony_ci	.setup = setup,
61f08c3bdfSopenharmony_ci	.cleanup = cleanup,
62f08c3bdfSopenharmony_ci	.test_all = run,
63f08c3bdfSopenharmony_ci	.needs_tmpdir = 1
64f08c3bdfSopenharmony_ci};
65