1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright (c) 2020 Carlos Neira cneirabustos@gmail.com */
3 
4 #define _GNU_SOURCE
5 #include <test_progs.h>
6 #include "test_ns_current_pid_tgid.skel.h"
7 #include <sys/stat.h>
8 #include <sys/types.h>
9 #include <unistd.h>
10 #include <sys/syscall.h>
11 #include <sched.h>
12 #include <sys/wait.h>
13 #include <sys/mount.h>
14 #include <sys/fcntl.h>
15 
16 #define STACK_SIZE (1024 * 1024)
17 static char child_stack[STACK_SIZE];
18 
test_current_pid_tgid(void * args)19 static int test_current_pid_tgid(void *args)
20 {
21 	struct test_ns_current_pid_tgid__bss  *bss;
22 	struct test_ns_current_pid_tgid *skel;
23 	int err = -1, duration = 0;
24 	pid_t tgid, pid;
25 	struct stat st;
26 
27 	skel = test_ns_current_pid_tgid__open_and_load();
28 	if (CHECK(!skel, "skel_open_load", "failed to load skeleton\n"))
29 		goto cleanup;
30 
31 	pid = syscall(SYS_gettid);
32 	tgid = getpid();
33 
34 	err = stat("/proc/self/ns/pid", &st);
35 	if (CHECK(err, "stat", "failed /proc/self/ns/pid: %d\n", err))
36 		goto cleanup;
37 
38 	bss = skel->bss;
39 	bss->dev = st.st_dev;
40 	bss->ino = st.st_ino;
41 	bss->user_pid = 0;
42 	bss->user_tgid = 0;
43 
44 	err = test_ns_current_pid_tgid__attach(skel);
45 	if (CHECK(err, "skel_attach", "skeleton attach failed: %d\n", err))
46 		goto cleanup;
47 
48 	/* trigger tracepoint */
49 	usleep(1);
50 	ASSERT_EQ(bss->user_pid, pid, "pid");
51 	ASSERT_EQ(bss->user_tgid, tgid, "tgid");
52 	err = 0;
53 
54 cleanup:
55 	 test_ns_current_pid_tgid__destroy(skel);
56 
57 	return err;
58 }
59 
test_ns_current_pid_tgid_new_ns(void)60 static void test_ns_current_pid_tgid_new_ns(void)
61 {
62 	int wstatus, duration = 0;
63 	pid_t cpid;
64 
65 	/* Create a process in a new namespace, this process
66 	 * will be the init process of this new namespace hence will be pid 1.
67 	 */
68 	cpid = clone(test_current_pid_tgid, child_stack + STACK_SIZE,
69 		     CLONE_NEWPID | SIGCHLD, NULL);
70 
71 	if (CHECK(cpid == -1, "clone", "%s\n", strerror(errno)))
72 		return;
73 
74 	if (CHECK(waitpid(cpid, &wstatus, 0) == -1, "waitpid", "%s\n", strerror(errno)))
75 		return;
76 
77 	if (CHECK(WEXITSTATUS(wstatus) != 0, "newns_pidtgid", "failed"))
78 		return;
79 }
80 
81 /* TODO: use a different tracepoint */
serial_test_ns_current_pid_tgid(void)82 void serial_test_ns_current_pid_tgid(void)
83 {
84 	if (test__start_subtest("ns_current_pid_tgid_root_ns"))
85 		test_current_pid_tgid(NULL);
86 	if (test__start_subtest("ns_current_pid_tgid_new_ns"))
87 		test_ns_current_pid_tgid_new_ns();
88 }
89