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(void)38 static void chld1_shm(void)
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
chld2_shm(void)61 static void chld2_shm(void)
62 {
63 int id;
64 char *shmem;
65
66 id = SAFE_SHMGET(TESTKEY, SHMSIZE, IPC_CREAT);
67
68 shmem = SAFE_SHMAT(id, NULL, 0);
69
70 TST_CHECKPOINT_WAIT(0);
71
72 *shmem = 'B';
73
74 TST_CHECKPOINT_WAKE_AND_WAIT(0);
75
76 SAFE_SHMDT(shmem);
77 SAFE_SHMCTL(id, IPC_RMID, NULL);
78 }
79
run(void)80 static void run(void)
81 {
82 clone_unshare_test(T_CLONE, CLONE_NEWIPC, chld1_shm);
83 clone_unshare_test(T_CLONE, CLONE_NEWIPC, chld2_shm);
84 }
85
86 static struct tst_test test = {
87 .test_all = run,
88 .needs_root = 1,
89 .needs_checkpoints = 1,
90 .forks_child = 1,
91 };
92