1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3 * Copyright (c) 2014 Red Hat, Inc.
4 * Copyright (C) 2022 SUSE LLC Andrea Cervesato <andrea.cervesato@suse.com>
5 */
6
7 /*\
8 * [Description]
9 *
10 * Test if SysV IPC shared memory is properly working between two different
11 * namespaces.
12 *
13 * [Algorithm]
14 *
15 * 1. Clones two child processes with CLONE_NEWIPC flag, each child
16 * allocates System V shared memory segment (shm) with the _identical_
17 * key and attaches that segment into its address space.
18 * 2. Child1 writes into the shared memory segment.
19 * 3. Child2 writes into the shared memory segment.
20 * 4. Writes to the shared memory segment with the identical key but from
21 * two different IPC namespaces should not interfere with each other
22 * and so child1 checks whether its shared segment wasn't changed
23 * by child2, if it wasn't test passes, otherwise test fails.
24 */
25
26 #define _GNU_SOURCE
27
28 #include <sys/wait.h>
29 #include <sys/msg.h>
30 #include <sys/types.h>
31 #include "tst_safe_sysv_ipc.h"
32 #include "tst_test.h"
33 #include "common.h"
34
35 #define TESTKEY 124426L
36 #define SHMSIZE 50
37
chld1_shm(LTP_ATTRIBUTE_UNUSED void * arg)38 static int chld1_shm(LTP_ATTRIBUTE_UNUSED void *arg)
39 {
40 int id;
41 char *shmem;
42
43 id = SAFE_SHMGET(TESTKEY, SHMSIZE, IPC_CREAT);
44
45 shmem = SAFE_SHMAT(id, NULL, 0);
46 *shmem = 'A';
47
48 TST_CHECKPOINT_WAKE_AND_WAIT(0);
49
50 if (*shmem != 'A')
51 tst_res(TFAIL, "shared memory leak between namespaces");
52 else
53 tst_res(TPASS, "shared memory didn't leak between namespaces");
54
55 TST_CHECKPOINT_WAKE(0);
56
57 SAFE_SHMDT(shmem);
58 SAFE_SHMCTL(id, IPC_RMID, NULL);
59
60 return 0;
61 }
62
chld2_shm(LTP_ATTRIBUTE_UNUSED void * arg)63 static int chld2_shm(LTP_ATTRIBUTE_UNUSED void *arg)
64 {
65 int id;
66 char *shmem;
67
68 id = SAFE_SHMGET(TESTKEY, SHMSIZE, IPC_CREAT);
69
70 shmem = SAFE_SHMAT(id, NULL, 0);
71
72 TST_CHECKPOINT_WAIT(0);
73
74 *shmem = 'B';
75
76 TST_CHECKPOINT_WAKE_AND_WAIT(0);
77
78 SAFE_SHMDT(shmem);
79 SAFE_SHMCTL(id, IPC_RMID, NULL);
80
81 return 0;
82 }
83
run(void)84 static void run(void)
85 {
86 clone_unshare_test(T_CLONE, CLONE_NEWIPC, chld1_shm, NULL);
87 clone_unshare_test(T_CLONE, CLONE_NEWIPC, chld2_shm, NULL);
88 }
89
setup(void)90 static void setup(void)
91 {
92 check_newipc();
93 }
94
95 static struct tst_test test = {
96 .test_all = run,
97 .setup = setup,
98 .needs_root = 1,
99 .needs_checkpoints = 1,
100 };
101