1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3 * Copyright (c) International Business Machines Corp., 2009
4 * Veerendra C <[email protected]>
5 * Copyright (C) 2022 SUSE LLC Andrea Cervesato <[email protected]>
6 */
7
8 /*\
9 * [Description]
10 *
11 * Test SysV IPC semaphore usage between namespaces.
12 *
13 * [Algorithm]
14 *
15 * In parent process create a new semaphore with a specific key.
16 * In cloned process, try to access the created semaphore
17 *
18 * Test PASS if the semaphore is readable when flag is None.
19 * Test FAIL if the semaphore is readable when flag is Unshare or Clone.
20 */
21
22 #define _GNU_SOURCE
23
24 #include <sys/wait.h>
25 #include <sys/msg.h>
26 #include <sys/types.h>
27 #include <sys/sem.h>
28 #include "tst_safe_sysv_ipc.h"
29 #include "tst_test.h"
30 #include "common.h"
31
32 #define MY_KEY 154326L
33
34 static char *str_op;
35 static int use_clone;
36 static int ipc_id = -1;
37
check_semaphore(void)38 static void check_semaphore(void)
39 {
40 int id;
41
42 id = semget(MY_KEY, 1, 0);
43
44 if (id < 0) {
45 if (use_clone == T_NONE)
46 tst_res(TFAIL, "Plain cloned process didn't find semaphore");
47 else
48 tst_res(TPASS, "%s: container didn't find semaphore", str_op);
49
50 return;
51 }
52
53 tst_res(TINFO, "PID %d: fetched existing semaphore..id = %d", getpid(), id);
54
55 if (use_clone == T_NONE)
56 tst_res(TPASS, "Plain cloned process found semaphore inside container");
57 else
58 tst_res(TFAIL, "%s: Container init process found semaphore", str_op);
59 }
60
run(void)61 static void run(void)
62 {
63 clone_unshare_test(use_clone, CLONE_NEWIPC, check_semaphore);
64 }
65
setup(void)66 static void setup(void)
67 {
68 use_clone = get_clone_unshare_enum(str_op);
69 ipc_id = SAFE_SEMGET(MY_KEY, 1, IPC_CREAT | IPC_EXCL | 0666);
70 }
71
cleanup(void)72 static void cleanup(void)
73 {
74 if (ipc_id != -1) {
75 tst_res(TINFO, "Destroying semaphore");
76 SAFE_SEMCTL(ipc_id, IPC_RMID, 0);
77 }
78 }
79
80 static struct tst_test test = {
81 .test_all = run,
82 .setup = setup,
83 .cleanup = cleanup,
84 .needs_root = 1,
85 .forks_child = 1,
86 .options = (struct tst_option[]) {
87 { "m:", &str_op, "Test execution mode <clone|unshare|none>" },
88 {},
89 },
90 };
91