1 /*
2 * Copyright (c) 2016-2018 The strace developers.
3 * All rights reserved.
4 *
5 * SPDX-License-Identifier: GPL-2.0-or-later
6 */
7
8 #include "tests.h"
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <sys/shm.h>
12
13 static int id = -1;
14
15 static void
16 cleanup(void)
17 {
18 shmctl(id, IPC_RMID, NULL);
19 id = -1;
20 }
21
22 #ifdef __alpha__
23 # define SHMAT "osf_shmat"
24 #else
25 # define SHMAT "shmat"
26 #endif
27
28 #ifndef SHM_EXEC
29 # define SHM_EXEC 0100000
30 #endif
31
32 int
33 main(void)
34 {
35 static const int bogus_shmid = 0xfdb97531;
36 static const void * const bogus_shmaddr =
37 (void *) (unsigned long) 0xdec0ded1dec0ded2ULL;
38 static const int bogus_shmflg = 0xffffface;
39
40 long rc;
41
42 id = shmget(IPC_PRIVATE, 1, 0600);
43 if (id < 0)
44 perror_msg_and_skip("shmget");
45 atexit(cleanup);
46
47 rc = (long) shmat(bogus_shmid, bogus_shmaddr, bogus_shmflg);
48 printf("%s(%d, %p, SHM_RDONLY|SHM_RND|SHM_REMAP|SHM_EXEC|%#x) = %s\n",
49 SHMAT, bogus_shmid, bogus_shmaddr, bogus_shmflg & ~0xf000,
50 sprintrc(rc));
51
52 shmat(id, NULL, SHM_REMAP);
53 printf("%s(%d, NULL, SHM_REMAP) = -1 %s (%m)\n",
54 SHMAT, id, errno2name());
55
56 void *shmaddr = shmat(id, NULL, SHM_RDONLY);
57 if (shmaddr == (void *)(-1))
58 perror_msg_and_skip("shmat SHM_RDONLY");
59 printf("%s(%d, NULL, SHM_RDONLY) = %p\n", SHMAT, id, shmaddr);
60
61 rc = shmdt(NULL);
62 printf("shmdt(NULL) = %s\n", sprintrc(rc));
63
64 rc = shmdt(shmaddr);
65 printf("shmdt(%p) = %s\n", shmaddr, sprintrc(rc));
66
67 ++shmaddr;
68 void *shmaddr2 = shmat(id, shmaddr, SHM_RND);
69 if (shmaddr2 == (void *)(-1))
70 printf("%s(%d, %p, SHM_RND) = -1 %s (%m)\n",
71 SHMAT, id, shmaddr, errno2name());
72 else {
73 printf("%s(%d, %p, SHM_RND) = %p\n",
74 SHMAT, id, shmaddr, shmaddr2);
75 rc = shmdt(shmaddr2);
76 printf("shmdt(%p) = %s\n", shmaddr2, sprintrc(rc));
77 }
78
79 shmaddr = shmat(id, NULL, SHM_RDONLY|SHM_EXEC);
80 if (shmaddr == (void *)(-1))
81 printf("%s(%d, NULL, SHM_RDONLY|SHM_EXEC) = %s\n",
82 SHMAT, id, sprintrc(-1));
83 else {
84 printf("%s(%d, NULL, SHM_RDONLY|SHM_EXEC) = %p\n",
85 SHMAT, id, shmaddr);
86 rc = shmdt(shmaddr);
87 printf("shmdt(%p) = %s\n", shmaddr, sprintrc(rc));
88 }
89
90 puts("+++ exited with 0 +++");
91 return 0;
92 }