1/*
2 *  This program is free software; you can redistribute it and/or modify
3 *  it under the terms of the GNU General Public License version 2.
4 *
5 *  This program is distributed in the hope that it will be useful,
6 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
7 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
8 *  GNU General Public License for more details.
9 *
10 * Test that shm_open open the shared memory object for reading when calling
11 * shm_open even if the mode don't set read permission.
12 *
13 * The test use mmap to check the object is open for reading.
14 */
15
16/* ftruncate was formerly an XOPEN extension. We define _XOPEN_SOURCE here to
17   avoid warning if the implementation does not program ftruncate as a base
18   interface */
19#define _XOPEN_SOURCE 600
20
21#include <stdio.h>
22#include <sys/mman.h>
23#include <sys/stat.h>
24#include <unistd.h>
25#include <fcntl.h>
26#include <errno.h>
27#include "posixtest.h"
28
29#define BUF_SIZE 8
30#define SHM_NAME "posixtest_20-3"
31
32int main(void)
33{
34	int fd, result;
35	void *ptr;
36
37	result = shm_unlink(SHM_NAME);
38	if (result != 0 && errno != ENOENT) {
39		/* The shared memory object exist and shm_unlink can not
40		   remove it. */
41		perror("An error occurs when calling shm_unlink()");
42		return PTS_UNRESOLVED;
43	}
44
45	fd = shm_open(SHM_NAME, O_RDWR | O_CREAT, 0);
46	if (fd == -1) {
47		perror("An error occurs when calling shm_open()");
48		return PTS_UNRESOLVED;
49	}
50
51	if (ftruncate(fd, BUF_SIZE) != 0) {
52		perror("An error occurs when calling ftruncate()");
53		shm_unlink(SHM_NAME);
54		return PTS_UNRESOLVED;
55	}
56
57	ptr = mmap(NULL, BUF_SIZE, PROT_NONE, MAP_SHARED, fd, 0);
58	if (ptr != MAP_FAILED) {
59		printf("Test PASSED\n");
60		shm_unlink(SHM_NAME);
61		return PTS_PASS;
62	} else if (errno == EACCES) {
63		printf("The shared memory object is not opened for reading.\n");
64		shm_unlink(SHM_NAME);
65		return PTS_FAIL;
66	}
67
68	perror("mmap");
69	shm_unlink(SHM_NAME);
70	return PTS_FAIL;
71}
72