Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0
0002 /* Copyright (c) 2020 Carlos Neira cneirabustos@gmail.com */
0003 
0004 #define _GNU_SOURCE
0005 #include <test_progs.h>
0006 #include "test_ns_current_pid_tgid.skel.h"
0007 #include <sys/stat.h>
0008 #include <sys/types.h>
0009 #include <unistd.h>
0010 #include <sys/syscall.h>
0011 #include <sched.h>
0012 #include <sys/wait.h>
0013 #include <sys/mount.h>
0014 #include <sys/fcntl.h>
0015 
0016 #define STACK_SIZE (1024 * 1024)
0017 static char child_stack[STACK_SIZE];
0018 
0019 static int test_current_pid_tgid(void *args)
0020 {
0021     struct test_ns_current_pid_tgid__bss  *bss;
0022     struct test_ns_current_pid_tgid *skel;
0023     int err = -1, duration = 0;
0024     pid_t tgid, pid;
0025     struct stat st;
0026 
0027     skel = test_ns_current_pid_tgid__open_and_load();
0028     if (CHECK(!skel, "skel_open_load", "failed to load skeleton\n"))
0029         goto cleanup;
0030 
0031     pid = syscall(SYS_gettid);
0032     tgid = getpid();
0033 
0034     err = stat("/proc/self/ns/pid", &st);
0035     if (CHECK(err, "stat", "failed /proc/self/ns/pid: %d\n", err))
0036         goto cleanup;
0037 
0038     bss = skel->bss;
0039     bss->dev = st.st_dev;
0040     bss->ino = st.st_ino;
0041     bss->user_pid = 0;
0042     bss->user_tgid = 0;
0043 
0044     err = test_ns_current_pid_tgid__attach(skel);
0045     if (CHECK(err, "skel_attach", "skeleton attach failed: %d\n", err))
0046         goto cleanup;
0047 
0048     /* trigger tracepoint */
0049     usleep(1);
0050     ASSERT_EQ(bss->user_pid, pid, "pid");
0051     ASSERT_EQ(bss->user_tgid, tgid, "tgid");
0052     err = 0;
0053 
0054 cleanup:
0055      test_ns_current_pid_tgid__destroy(skel);
0056 
0057     return err;
0058 }
0059 
0060 static void test_ns_current_pid_tgid_new_ns(void)
0061 {
0062     int wstatus, duration = 0;
0063     pid_t cpid;
0064 
0065     /* Create a process in a new namespace, this process
0066      * will be the init process of this new namespace hence will be pid 1.
0067      */
0068     cpid = clone(test_current_pid_tgid, child_stack + STACK_SIZE,
0069              CLONE_NEWPID | SIGCHLD, NULL);
0070 
0071     if (CHECK(cpid == -1, "clone", "%s\n", strerror(errno)))
0072         return;
0073 
0074     if (CHECK(waitpid(cpid, &wstatus, 0) == -1, "waitpid", "%s\n", strerror(errno)))
0075         return;
0076 
0077     if (CHECK(WEXITSTATUS(wstatus) != 0, "newns_pidtgid", "failed"))
0078         return;
0079 }
0080 
0081 /* TODO: use a different tracepoint */
0082 void serial_test_ns_current_pid_tgid(void)
0083 {
0084     if (test__start_subtest("ns_current_pid_tgid_root_ns"))
0085         test_current_pid_tgid(NULL);
0086     if (test__start_subtest("ns_current_pid_tgid_new_ns"))
0087         test_ns_current_pid_tgid_new_ns();
0088 }