Skip to contentSkip to conversation

introduce PIDFD_SELF* sentinels

PATCH Superseded Lorenzo Stoakes 2 participants 7 messages Oct 10, 2024 – Oct 16, 2024

Subsystems (5)

v1 of 7 Superseded Latest is v7 →

lore
Share & tools
lore
#0 lore raw

cover introduce PIDFD_SELF* sentinels

If you wish to utilise a pidfd interface to refer to the current process or thread it is rather cumbersome, requiring something like:

	int pidfd = pidfd_open(getpid(), 0 or PIDFD_THREAD);

	...

	close(pidfd);

Or the equivalent call opening /proc/self. It is more convenient to use a sentinel value to indicate to an interface that accepts a pidfd that we simply wish to refer to the current process thread.

This series introduces sentinels for this purposes which can be passed as the pidfd in this instance rather than having to establish a dummy fd for this purpose.

It is useful to refer to both the current thread from the userland's perspective for which we use PIDFD_SELF, and the current process from the userland's perspective, for which we use PIDFD_SELF_PROCESS.

There is unfortunately some confusion between the kernel and userland as to what constitutes a process - a thread from the userland perspective is a process in userland, and a userland process is a thread group (more specifically the thread group leader from the kernel perspective). We therefore alias things thusly:

* PIDFD_SELF_THREAD aliased by PIDFD_SELF - use PIDTYPE_PID.
* PIDFD_SELF_THREAD_GROUP alised by PIDFD_SELF_PROCESS - use PIDTYPE_TGID.

In all of the kernel code we refer to PIDFD_SELF_THREAD and PIDFD_SELF_THREAD_GROUP. However we expect users to use PIDFD_SELF and PIDFD_SELF_PROCESS.

This matters for cases where, for instance, a user unshare()'s FDs or does thread-specific signal handling and where the user would be hugely confused if the FDs referenced or signal processed referred to the thread group leader rather than the individual thread.

We ensure that pidfd_send_signal() and pidfd_getfd() work correctly, and assert as much in selftests. All other interfaces except setns() will work implicitly with this new interface, however it doesn't make sense to test waitid(P_PIDFD, ...) as waiting on ourselves is a blocking operation.

In the case of setns() we explicitly disallow use of PIDFD_SELF* as it doesn't make sense to obtain the namespaces of our own process, and it would require work to implement this functionality there that would be of no use.

We also do not provide the ability to utilise PIDFD_SELF* in ordinary fd operations such as open() or poll(), as this would require extensive work and be of no real use.

Non-RFC v1:
* Removed RFC tag - there seems to be general consensus that this change is a good idea, but perhaps some debate to be had on implementation. It seems sensible then to move forward with the RFC flag removed.
* Introduced PIDFD_SELF_THREAD, PIDFD_SELF_THREAD_GROUP and their aliases PIDFD_SELF and PIDFD_SELF_PROCESS respectively.
* Updated testing accordingly.

RFC version:
https://lore.kernel.org/linux-mm/[email protected]/

Lorenzo Stoakes (3):
pidfd: extend pidfd_get_pid() and de-duplicate pid lookup
pidfd: add PIDFD_SELF_* sentinels to refer to own thread/process
selftests: pidfd: add tests for PIDFD_SELF_*

 include/linux/pid.h                           |  43 +++++-
 include/uapi/linux/pidfd.h                    |  15 ++
 kernel/exit.c                                 |   3 +-
 kernel/nsproxy.c                              |   1 +
 kernel/pid.c                                  |  73 +++++++---
 kernel/signal.c                               |  22 +--
 tools/testing/selftests/pidfd/pidfd.h         |   8 ++
 .../selftests/pidfd/pidfd_getfd_test.c        | 136 ++++++++++++++++++
 .../selftests/pidfd/pidfd_setns_test.c        |  11 ++
 tools/testing/selftests/pidfd/pidfd_test.c    |  67 +++++++--
 10 files changed, 330 insertions(+), 49 deletions(-)

--
2.46.2

#1 lore raw

PATCH 1/3 pidfd: extend pidfd_get_pid() and de-duplicate pid lookup

The means by which a pid is determined from a pidfd is duplicated, with some callers holding a reference to the (pid)fd, and others explicitly pinning the pid.

Introduce __pidfd_get_pid() which abstracts both approaches and provide optional output parameters for file->f_flags and the fd (the latter of which, if provided, prevents the function from decrementing the fd's refernce count).

Additionally, allow the ability to open a pidfd by opening a /proc/<pid> directory, utilised by the pidfd_send_signal() system call, providing a pidfd_get_pid_proc() helper function to do so.

Doing this allows us to eliminate open-coded pidfd pid lookup and to consistently handle this in one place.

This lays the groundwork for a subsequent patch which adds a new sentinel pidfd to explicitly reference the current process (i.e. thread group leader) without the need for a pidfd.

---
 include/linux/pid.h | 42 +++++++++++++++++++++++++++++++-
 kernel/pid.c        | 58 ++++++++++++++++++++++++++++++---------------
 kernel/signal.c     | 22 ++++-------------
 3 files changed, 84 insertions(+), 38 deletions(-)
include/linux/pid.h +41 -1
index a3aad9b4074c..68b02eab7509 100644
@@ -2,6 +2,7 @@
 #ifndef _LINUX_PID_H
 #define _LINUX_PID_H
 
+#include <linux/file.h>
 #include <linux/pid_types.h>
 #include <linux/rculist.h>
 #include <linux/rcupdate.h>
@@ -72,8 +73,47 @@ extern struct pid init_struct_pid;
 
 struct file;
 
+
+/**
+ * __pidfd_get_pid() - Retrieve a pid associated with the specified pidfd.
+ *
+ * @pidfd:      The pidfd whose pid we want, or the fd of a /proc/<pid> file if
+ *              @alloc_proc is also set.
+ * @pin_pid:    If set, then the reference counter of the returned pid is
+ *              incremented. If not set, then @fd should be provided to pin the
+ *              pidfd.
+ * @allow_proc: If set, then an fd of a /proc/<pid> file can be passed instead
+ *              of a pidfd, and this will be used to determine the pid.
+ * @flags:      Output variable, if non-NULL, then the file->f_flags of the
+ *              pidfd will be set here.
+ * @fd:         Output variable, if non-NULL, then the pidfd reference will
+ *              remain elevated and the caller will need to decrement it
+ *              themselves.
+ *
+ * Returns: If successful, the pid associated with the pidfd, otherwise an
+ *          error.
+ */
+struct pid *__pidfd_get_pid(unsigned int pidfd, bool pin_pid,
+			    bool allow_proc, unsigned int *flags,
+			    struct fd *fd);
+
+static inline struct pid *pidfd_get_pid(unsigned int pidfd, unsigned int *flags)
+{
+	return __pidfd_get_pid(pidfd, /* pin_pid = */ true,
+			       /* allow_proc = */ false,
+			       flags, /* fd = */ NULL);
+}
+
+static inline struct pid *pidfd_to_pid_proc(unsigned int pidfd,
+					    unsigned int *flags,
+					    struct fd *fd)
+{
+	return __pidfd_get_pid(pidfd, /* pin_pid = */ false,
+			       /* allow_proc = */ true,
+			       flags, fd);
+}
+
 struct pid *pidfd_pid(const struct file *file);
-struct pid *pidfd_get_pid(unsigned int fd, unsigned int *flags);
 struct task_struct *pidfd_get_task(int pidfd, unsigned int *flags);
 int pidfd_prepare(struct pid *pid, unsigned int flags, struct file **ret);
 void do_notify_pidfd(struct task_struct *task);
kernel/pid.c +39 -19

90 lines not on this page · raw message

kernel/signal.c +4 -18
index 4344860ffcac..868bfa674c62 100644
@@ -3875,17 +3875,6 @@ static int copy_siginfo_from_user_any(kernel_siginfo_t *kinfo,
 	return copy_siginfo_from_user(kinfo, info);
 }
 
-static struct pid *pidfd_to_pid(const struct file *file)
-{
-	struct pid *pid;
-
-	pid = pidfd_pid(file);
-	if (!IS_ERR(pid))
-		return pid;
-
-	return tgid_pidfd_to_pid(file);
-}
-
 #define PIDFD_SEND_SIGNAL_FLAGS                            \
 	(PIDFD_SIGNAL_THREAD | PIDFD_SIGNAL_THREAD_GROUP | \
 	 PIDFD_SIGNAL_PROCESS_GROUP)
@@ -3908,10 +3897,11 @@ SYSCALL_DEFINE4(pidfd_send_signal, int, pidfd, int, sig,
 		siginfo_t __user *, info, unsigned int, flags)
 {
 	int ret;
-	struct fd f;
 	struct pid *pid;
 	kernel_siginfo_t kinfo;
 	enum pid_type type;
+	unsigned int f_flags;
+	struct fd f;
 
 	/* Enforce flags be set to 0 until we add an extension. */
 	if (flags & ~PIDFD_SEND_SIGNAL_FLAGS)
@@ -3921,12 +3911,8 @@ SYSCALL_DEFINE4(pidfd_send_signal, int, pidfd, int, sig,
 	if (hweight32(flags & PIDFD_SEND_SIGNAL_FLAGS) > 1)
 		return -EINVAL;
 
-	f = fdget(pidfd);
-	if (!fd_file(f))
-		return -EBADF;
-
 	/* Is this a pidfd? */
-	pid = pidfd_to_pid(fd_file(f));
+	pid = pidfd_to_pid_proc(pidfd, &f_flags, &f);
 	if (IS_ERR(pid)) {
 		ret = PTR_ERR(pid);
 		goto err;
@@ -3939,7 +3925,7 @@ SYSCALL_DEFINE4(pidfd_send_signal, int, pidfd, int, sig,
 	switch (flags) {
 	case 0:
 		/* Infer scope from the type of pidfd. */
-		if (fd_file(f)->f_flags & PIDFD_THREAD)
+		if (f_flags & PIDFD_THREAD)
 			type = PIDTYPE_PID;
 		else
 			type = PIDTYPE_TGID;
Signature · 1 line
2.46.2
#2 lore raw

PATCH 2/3 pidfd: add PIDFD_SELF* sentinels to refer to own thread/process

In reply to Lorenzo Stoakes

It is useful to be able to utilise pidfd mechanisms to reference the current thread or process (from a userland point of view - thread group leader from the kernel's point of view).

Therefore introduce PIDFD_SELF_THREAD to refer to the current thread, and PIDFD_SELF_THREAD_GROUP to refer to the current thread group leader.

For convenience and to avoid confusion from userland's perspective we alias these:

* PIDFD_SELF is an alias for PIDFD_SELF_THREAD - This is nearly always what the user will want to use, as they would find it surprising if for instance fd's were unshared()'d and they wanted to invoke pidfd_getfd() and that failed.

* PIDFD_SELF_PROCESS is an alias for PIDFD_SELF_THREAD_GROUP - Most users have no concept of thread groups or what a thread group leader is, and from userland's perspective and nomenclature this is what userland considers to be a process.

Due to the refactoring of the central __pidfd_get_pid() function we can implement this functionality centrally, providing the use of this sentinel in most functionality which utilises pidfd's.

We need to explicitly adjust kernel_waitid_prepare() to permit this (though it wouldn't really make sense to use this there, we provide the ability for consistency).

We explicitly disallow use of this in setns(), which would otherwise have required explicit custom handling, as it doesn't make sense to set the current calling thread to join the namespace of itself.

As the callers of pidfd_get_pid() expect an increased reference count on the pid we do so in the self case, reducing churn and avoiding any breakage from existing logic which decrements this reference count.

In the pidfd_send_signal() system call, we can continue to fdput() the struct fd output by pidfs_to_pid_proc() even if PIDFD_SELF* is specified, as this will be empty and the invocation will be a no-op.

This change implicitly provides PIDFD_SELF* support in the waitid(P_PIDFS, ...), process_madvise(), process_mrelease(), pidfd_send_signal(), and pidfd_getfd() system calls.

Things such as polling a pidfs and general fd operations are not supported, this strictly provides the sentinel for APIs which explicitly accept a pidfd.

---
 include/linux/pid.h        |  9 +++---
 include/uapi/linux/pidfd.h | 15 +++++++++
 kernel/exit.c              |  3 +-
 kernel/nsproxy.c           |  1 +
 kernel/pid.c               | 65 +++++++++++++++++++++++---------------
 5 files changed, 62 insertions(+), 31 deletions(-)
include/linux/pid.h +5 -4
index 68b02eab7509..7c9ed1b5d16f 100644
@@ -77,18 +77,19 @@ struct file;
 /**
  * __pidfd_get_pid() - Retrieve a pid associated with the specified pidfd.
  *
- * @pidfd:      The pidfd whose pid we want, or the fd of a /proc/<pid> file if
- *              @alloc_proc is also set.
+ * @pidfd:      The pidfd whose pid we want, the fd of a /proc/<pid> file if
+ *              @alloc_proc is also set, or PIDFD_SELF_* to refer to the current
+ *              thread or thread group leader.
  * @pin_pid:    If set, then the reference counter of the returned pid is
  *              incremented. If not set, then @fd should be provided to pin the
  *              pidfd.
  * @allow_proc: If set, then an fd of a /proc/<pid> file can be passed instead
  *              of a pidfd, and this will be used to determine the pid.
  * @flags:      Output variable, if non-NULL, then the file->f_flags of the
- *              pidfd will be set here.
+ *              pidfd will be set here. If PIDFD_SELF_* set, this is zero.
  * @fd:         Output variable, if non-NULL, then the pidfd reference will
  *              remain elevated and the caller will need to decrement it
- *              themselves.
+ *              themselves. If PIDFD_SELF_* set, this is empty.
  *
  * Returns: If successful, the pid associated with the pidfd, otherwise an
  *          error.
include/uapi/linux/pidfd.h +15 -0
index 565fc0629fff..f4db20d76f4b 100644
@@ -29,4 +29,19 @@
 #define PIDFD_GET_USER_NAMESPACE              _IO(PIDFS_IOCTL_MAGIC, 9)
 #define PIDFD_GET_UTS_NAMESPACE               _IO(PIDFS_IOCTL_MAGIC, 10)
 
+/*
+ * Special sentinel values which can be used to refer to the current thread or
+ * thread group leader (which from a userland perspective is the process).
+ */
+#define PIDFD_SELF		PIDFD_SELF_THREAD
+#define PIDFD_SELF_PROCESS	PIDFD_SELF_THREAD_GROUP
+
+#define PIDFD_SELF_THREAD	-100 /* Current thread. */
+#define PIDFD_SELF_THREAD_GROUP	-200 /* Current thread group leader. */
+
+static inline bool pidfd_is_self_sentinel(pid_t pid)
+{
+	return pid == PIDFD_SELF_THREAD || pid == PIDFD_SELF_THREAD_GROUP;
+}
+
 #endif /* _UAPI_LINUX_PIDFD_H */
kernel/exit.c +2 -1
index 619f0014c33b..3eb20f8252ee 100644
@@ -71,6 +71,7 @@
 #include <linux/user_events.h>
 #include <linux/uaccess.h>
 
+#include <uapi/linux/pidfd.h>
 #include <uapi/linux/wait.h>
 
 #include <asm/unistd.h>
@@ -1739,7 +1740,7 @@ int kernel_waitid_prepare(struct wait_opts *wo, int which, pid_t upid,
 		break;
 	case P_PIDFD:
 		type = PIDTYPE_PID;
-		if (upid < 0)
+		if (upid < 0 && !pidfd_is_self_sentinel(upid))
 			return -EINVAL;
 
 		pid = pidfd_get_pid(upid, &f_flags);
kernel/nsproxy.c +1 -0
index dc952c3b05af..d239f7eeaa1f 100644
@@ -550,6 +550,7 @@ SYSCALL_DEFINE2(setns, int, fd, int, flags)
 	struct nsset nsset = {};
 	int err = 0;
 
+	/* If fd is PIDFD_SELF_*, implicitly fail here, as invalid. */
 	if (!fd_file(f))
 		return -EBADF;
 
kernel/pid.c +39 -26

79 lines not on this page · raw message

--
2.46.2

#3 lore raw

PATCH 3/3 selftests: pidfd: add tests for PIDFD_SELF_*

In reply to Lorenzo Stoakes

Add tests to assert that PIDFD_SELF_* correctly refers to the current thread and process.

This is only practically meaningful to pidfd_send_signal() and pidfd_getfd(), but also explicitly test that we disallow this feature for setns() where it would make no sense.

We cannot reasonably wait on ourself using waitid(P_PIDFD, ...) so while in theory PIDFD_SELF_* would work here, we'd be left blocked if we tried it.

We defer testing of mm-specific functionality which uses pidfd, namely process_madvise() and process_mrelease() to mm testing (though note the latter can not be sensibly tested as it would require the testing process to be dying).

---
 tools/testing/selftests/pidfd/pidfd.h         |   8 ++
 .../selftests/pidfd/pidfd_getfd_test.c        | 136 ++++++++++++++++++
 .../selftests/pidfd/pidfd_setns_test.c        |  11 ++
 tools/testing/selftests/pidfd/pidfd_test.c    |  67 +++++++--
 4 files changed, 213 insertions(+), 9 deletions(-)
tools/testing/selftests/pidfd/pidfd.h +8 -0
index 88d6830ee004..1640b711889b 100644
@@ -50,6 +50,14 @@
 #define PIDFD_NONBLOCK O_NONBLOCK
 #endif
 
+/* System header file may not have this available. */
+#ifndef PIDFD_SELF_THREAD
+#define PIDFD_SELF_THREAD -100
+#endif
+#ifndef PIDFD_SELF_THREAD_GROUP
+#define PIDFD_SELF_THREAD_GROUP -200
+#endif
+
 /*
  * The kernel reserves 300 pids via RESERVED_PIDS in kernel/pid.c
  * That means, when it wraps around any pid < 300 will be skipped.
tools/testing/selftests/pidfd/pidfd_getfd_test.c +136 -0

160 lines not on this page · raw message

tools/testing/selftests/pidfd/pidfd_setns_test.c +11 -0
index 7c2a4349170a..bbd39dc5ceb7 100644
@@ -752,4 +752,15 @@ TEST(setns_einval)
 	close(fd);
 }
 
+TEST(setns_pidfd_self_disallowed)
+{
+	ASSERT_EQ(setns(PIDFD_SELF_THREAD, 0), -1);
+	EXPECT_EQ(errno, EBADF);
+
+	errno = 0;
+
+	ASSERT_EQ(setns(PIDFD_SELF_THREAD_GROUP, 0), -1);
+	EXPECT_EQ(errno, EBADF);
+}
+
 TEST_HARNESS_MAIN
tools/testing/selftests/pidfd/pidfd_test.c +58 -9

95 lines not on this page · raw message

Signature · 1 line
2.46.2
maintainer
#4 lore raw

Re: [PATCH 3/3] selftests: pidfd: add tests for PIDFD_SELF_*

Quoted 29 lines · Lorenzo Stoakes

Add tests to assert that PIDFD_SELF_* correctly refers to the current thread and process.

This is only practically meaningful to pidfd_send_signal() and pidfd_getfd(), but also explicitly test that we disallow this feature for setns() where it would make no sense.

We cannot reasonably wait on ourself using waitid(P_PIDFD, ...) so while in theory PIDFD_SELF_* would work here, we'd be left blocked if we tried it.

We defer testing of mm-specific functionality which uses pidfd, namely process_madvise() and process_mrelease() to mm testing (though note the latter can not be sensibly tested as it would require the testing process to be dying).

---
  tools/testing/selftests/pidfd/pidfd.h         |   8 ++
  .../selftests/pidfd/pidfd_getfd_test.c        | 136 ++++++++++++++++++
  .../selftests/pidfd/pidfd_setns_test.c        |  11 ++
  tools/testing/selftests/pidfd/pidfd_test.c    |  67 +++++++--
  4 files changed, 213 insertions(+), 9 deletions(-)
tools/testing/selftests/pidfd/pidfd.h +0 -0
index 88d6830ee004..1640b711889b 100644
@@ -50,6 +50,14 @@
  #define PIDFD_NONBLOCK O_NONBLOCK

tools/testing/selftests/pidfd/pidfd.h line 60

Quoted 10 lines
tools/testing/selftests/pidfd/pidfd.h +8 -0
  #endif
 
+/* System header file may not have this available. */
+#ifndef PIDFD_SELF_THREAD
+#define PIDFD_SELF_THREAD -100
+#endif
+#ifndef PIDFD_SELF_THREAD_GROUP
+#define PIDFD_SELF_THREAD_GROUP -200
+#endif
+

Can't we pick these up from linux/pidfd.h - patch 2/3 adds them.

Quoted 35 lines
tools/testing/selftests/pidfd/pidfd.h +0 -0
  /*
   * The kernel reserves 300 pids via RESERVED_PIDS in kernel/pid.c
   * That means, when it wraps around any pid < 300 will be skipped.
tools/testing/selftests/pidfd/pidfd_getfd_test.c +10 -0
index cd51d547b751..10793fc845ed 100644
@@ -6,6 +6,7 @@
  #include <limits.h>
  #include <linux/types.h>
  #include <poll.h>
+#include <pthread.h>
  #include <sched.h>
  #include <signal.h>
  #include <stdio.h>
@@ -15,6 +16,7 @@
  #include <sys/prctl.h>
  #include <sys/wait.h>
  #include <unistd.h>
+#include <sys/mman.h>
  #include <sys/socket.h>
  #include <linux/kcmp.h>
 
@@ -114,6 +116,89 @@ static int child(int sk)
  	return ret;
  }
 
+static int __pidfd_self_thread_worker(unsigned long page_size)
+{
+	int memfd;
+	int newfd;
+	char *ptr;
+	int ret = 0;
+
+	/*

tools/testing/selftests/pidfd/pidfd_getfd_test.c static int child(int sk) · line 136

Quoted 10 lines
tools/testing/selftests/pidfd/pidfd_getfd_test.c +10 -0
+	 * Unshare our FDs so we have our own set. This means
+	 * PIDFD_SELF_THREAD_GROUP will fail.
+	 */
+	if (unshare(CLONE_FILES) < 0) {
+		ret = -errno;
+		goto exit;
+	}
+
+	/* Truncate, map in and write to our memfd. */
+	memfd = sys_memfd_create("test_self_child", 0);

Missing eror check.

tools/testing/selftests/pidfd/pidfd_getfd_test.c static int child(int sk) · line 139

Quoted 3 lines
tools/testing/selftests/pidfd/pidfd_getfd_test.c +3 -0
+	if (ftruncate(memfd, page_size)) {
+		ret = -errno;
+		goto exit;

Hmm. you probably need scoped cleanup paths. "exit" closes memfd and newfd which isn't open yet and sys_memfd_create() could fail and memfd doesn't need closing?

Quoted 9 lines
tools/testing/selftests/pidfd/pidfd_getfd_test.c +9 -0
+	}
+
+	ptr = mmap(NULL, page_size, PROT_READ | PROT_WRITE,
+		   MAP_SHARED, memfd, 0);
+	if (ptr == MAP_FAILED) {
+		ret = -errno;
+		goto exit;
+	}
+	ptr[0] = 'y';

tools/testing/selftests/pidfd/pidfd_getfd_test.c static int child(int sk) · line 158

Quoted 10 lines
tools/testing/selftests/pidfd/pidfd_getfd_test.c +10 -0
+	if (munmap(ptr, page_size)) {
+		ret = -errno;
+		goto exit;
+	}
+
+	/* Get a thread-local duplicate of our memfd. */
+	newfd = sys_pidfd_getfd(PIDFD_SELF_THREAD, memfd, 0);
+	if (newfd < 0) {
+		ret = -errno;
+		goto exit;

Same comment here - "exit" closes newfd

Quoted 29 lines
tools/testing/selftests/pidfd/pidfd_getfd_test.c +29 -0
+	}
+
+	if (memfd == newfd) {
+		ret = -EINVAL;
+		goto exit;
+	}
+
+	/* Map in new fd and make sure that the data is as expected. */
+	ptr = mmap(NULL, page_size, PROT_READ | PROT_WRITE,
+		   MAP_SHARED, newfd, 0);
+	if (ptr == MAP_FAILED) {
+		ret = -errno;
+		goto exit;
+	}
+
+	if (ptr[0] != 'y') {
+		ret = -EINVAL;
+		goto exit;
+	}
+
+	if (munmap(ptr, page_size)) {
+		ret = -errno;
+		goto exit;
+	}
+
+exit:
+	/* Cleanup. */
+	close(newfd);
+	close(memfd);

tools/testing/selftests/pidfd/pidfd_getfd_test.c static int child(int sk) · line 197

Quoted 10 lines
tools/testing/selftests/pidfd/pidfd_getfd_test.c +10 -0
+
+	return ret;
+}
+
+static void *pidfd_self_thread_worker(void *arg)
+{
+	unsigned long page_size = (unsigned long)arg;
+	int ret;
+
+	ret = __pidfd_self_thread_worker(page_size);

Don't you want to check error here?

Quoted 119 lines
tools/testing/selftests/pidfd/pidfd_getfd_test.c +55 -0
+
+	return (void *)(intptr_t)ret;
+}
+
  FIXTURE(child)
  {
  	/*
@@ -264,6 +349,57 @@ TEST_F(child, no_strange_EBADF)
  	EXPECT_EQ(errno, ESRCH);
  }
 
+TEST(pidfd_self)
+{
+	int memfd = sys_memfd_create("test_self", 0);
+	unsigned long page_size = sysconf(_SC_PAGESIZE);
+	int newfd;
+	char *ptr;
+	pthread_t thread;
+	void *res;
+	int err;
+
+	ASSERT_GE(memfd, 0);
+	ASSERT_EQ(ftruncate(memfd, page_size), 0);
+
+	/*
+	 * Map so we can assert that the duplicated fd references the same
+	 * memory.
+	 */
+	ptr = mmap(NULL, page_size, PROT_READ | PROT_WRITE,
+		   MAP_SHARED, memfd, 0);
+	ASSERT_NE(ptr, MAP_FAILED);
+	ptr[0] = 'x';
+	ASSERT_EQ(munmap(ptr, page_size), 0);
+
+	/* Now get a duplicate of our memfd. */
+	newfd = sys_pidfd_getfd(PIDFD_SELF_THREAD_GROUP, memfd, 0);
+	ASSERT_GE(newfd, 0);
+	ASSERT_NE(memfd, newfd);
+
+	/* Now map duplicate fd and make sure it references the same memory. */
+	ptr = mmap(NULL, page_size, PROT_READ | PROT_WRITE,
+		   MAP_SHARED, newfd, 0);
+	ASSERT_NE(ptr, MAP_FAILED);
+	ASSERT_EQ(ptr[0], 'x');
+	ASSERT_EQ(munmap(ptr, page_size), 0);
+
+	/* Cleanup. */
+	close(memfd);
+	close(newfd);
+
+	/*
+	 * Fire up the thread and assert that we can lookup the thread-specific
+	 * PIDFD_SELF_THREAD (also aliased by PIDFD_SELF).
+	 */
+	ASSERT_EQ(pthread_create(&thread, NULL, pidfd_self_thread_worker,
+				 (void *)page_size), 0);
+	ASSERT_EQ(pthread_join(thread, &res), 0);
+	err = (int)(intptr_t)res;
+
+	ASSERT_EQ(err, 0);
+}
+
  #if __NR_pidfd_getfd == -1
  int main(void)
  {
tools/testing/selftests/pidfd/pidfd_setns_test.c +11 -0
index 7c2a4349170a..bbd39dc5ceb7 100644
@@ -752,4 +752,15 @@ TEST(setns_einval)
  	close(fd);
  }
 
+TEST(setns_pidfd_self_disallowed)
+{
+	ASSERT_EQ(setns(PIDFD_SELF_THREAD, 0), -1);
+	EXPECT_EQ(errno, EBADF);
+
+	errno = 0;
+
+	ASSERT_EQ(setns(PIDFD_SELF_THREAD_GROUP, 0), -1);
+	EXPECT_EQ(errno, EBADF);
+}
+
  TEST_HARNESS_MAIN
tools/testing/selftests/pidfd/pidfd_test.c +20 -2
index 9faa686f90e4..ab5caa0368a1 100644
@@ -42,12 +42,41 @@ static pid_t pidfd_clone(int flags, int *pidfd, int (*fn)(void *))
  #endif
  }
 
-static int signal_received;
+static pthread_t signal_received;
 
  static void set_signal_received_on_sigusr1(int sig)
  {
  	if (sig == SIGUSR1)
-		signal_received = 1;
+		signal_received = pthread_self();
+}
+
+static int send_signal(int pidfd)
+{
+	int ret = 0;
+
+	if (sys_pidfd_send_signal(pidfd, SIGUSR1, NULL, 0) < 0) {
+		ret = -EINVAL;
+		goto exit;
+	}
+
+	if (signal_received != pthread_self()) {
+		ret = -EINVAL;
+		goto exit;
+	}
+
+exit:
+	signal_received = 0;

tools/testing/selftests/pidfd/pidfd_test.c static pid_t pidfd_clone(int flags, int *pidfd, int (*fn)(void *)) · line 78

Quoted 10 lines
tools/testing/selftests/pidfd/pidfd_test.c +10 -0
+	return ret;
+}
+
+static void *send_signal_worker(void *arg)
+{
+	int pidfd = (int)(intptr_t)arg;
+	int ret;
+
+	ret = send_signal(pidfd);
+

Same here - don't you have to check ret?

Quoted 48 lines
tools/testing/selftests/pidfd/pidfd_test.c +23 -6
+	return (void *)(intptr_t)ret;
  }
 
  /*
@@ -56,8 +85,11 @@ static void set_signal_received_on_sigusr1(int sig)
   */
  static int test_pidfd_send_signal_simple_success(void)
  {
-	int pidfd, ret;
+	int pidfd;
  	const char *test_name = "pidfd_send_signal send SIGUSR1";
+	pthread_t thread;
+	void *thread_res;
+	int res;
 
  	if (!have_pidfd_send_signal) {
  		ksft_test_result_skip(
@@ -74,17 +106,34 @@ static int test_pidfd_send_signal_simple_success(void)
 
  	signal(SIGUSR1, set_signal_received_on_sigusr1);
 
-	ret = sys_pidfd_send_signal(pidfd, SIGUSR1, NULL, 0);
+	send_signal(pidfd);
  	close(pidfd);
-	if (ret < 0)
-		ksft_exit_fail_msg("%s test: Failed to send signal\n",
+
+	/* Now try the same thing only using PIDFD_SELF_THREAD_GROUP. */
+	res = send_signal(PIDFD_SELF_THREAD_GROUP);
+	if (res)
+		ksft_exit_fail_msg(
+			"%s test: Error %d on PIDFD_SELF_THREAD_GROUP signal\n",
+			test_name, res);
+
+	/*
+	 * Now try the same thing in a thread and assert thread ID is equal to
+	 * worker thread ID.
+	 */
+	if (pthread_create(&thread, NULL, send_signal_worker,
+			   (void *)(intptr_t)PIDFD_SELF_THREAD))
+		ksft_exit_fail_msg("%s test: Failed to create thread\n",
  				   test_name);
 
-	if (signal_received != 1)
-		ksft_exit_fail_msg("%s test: Failed to receive signal\n",
+	if (pthread_join(thread, &thread_res))
+		ksft_exit_fail_msg("%s test: Failed to join thread\n",
  				   test_name);

tools/testing/selftests/pidfd/pidfd_test.c static int test_pidfd_send_signal_simple_success(void) · line 139

Quoted 10 lines
tools/testing/selftests/pidfd/pidfd_test.c +5 -1
+	res = (int)(intptr_t)thread_res;
+	if (res)
+		ksft_exit_fail_msg(
+			"%s test: Error %d on PIDFD_SELF_THREAD signal\n",
+			test_name, res);
 
-	signal_received = 0;
  	ksft_test_result_pass("%s test: Sent signal\n", test_name);
  	return 0;
  }

thanks,
-- Shuah

#5 lore raw

Re: [PATCH 3/3] selftests: pidfd: add tests for PIDFD_SELF_*

Quoted 34 lines · Shuah Khan
Quoted 33 lines · Lorenzo Stoakes

Add tests to assert that PIDFD_SELF_* correctly refers to the current thread and process.

This is only practically meaningful to pidfd_send_signal() and pidfd_getfd(), but also explicitly test that we disallow this feature for setns() where it would make no sense.

We cannot reasonably wait on ourself using waitid(P_PIDFD, ...) so while in theory PIDFD_SELF_* would work here, we'd be left blocked if we tried it.

We defer testing of mm-specific functionality which uses pidfd, namely process_madvise() and process_mrelease() to mm testing (though note the latter can not be sensibly tested as it would require the testing process to be dying).

---
  tools/testing/selftests/pidfd/pidfd.h         |   8 ++
  .../selftests/pidfd/pidfd_getfd_test.c        | 136 ++++++++++++++++++
  .../selftests/pidfd/pidfd_setns_test.c        |  11 ++
  tools/testing/selftests/pidfd/pidfd_test.c    |  67 +++++++--
  4 files changed, 213 insertions(+), 9 deletions(-)
tools/testing/selftests/pidfd/pidfd.h +3 -0
index 88d6830ee004..1640b711889b 100644
@@ -50,6 +50,14 @@
  #define PIDFD_NONBLOCK O_NONBLOCK
  #endif
+/* System header file may not have this available. */
+#ifndef PIDFD_SELF_THREAD
+#define PIDFD_SELF_THREAD -100
Quoted 8 lines

tools/testing/selftests/pidfd/pidfd.h line 60

Quoted 5 lines
tools/testing/selftests/pidfd/pidfd.h +5 -0
+#endif
+#ifndef PIDFD_SELF_THREAD_GROUP
+#define PIDFD_SELF_THREAD_GROUP -200
+#endif
+

Can't we pick these up from linux/pidfd.h - patch 2/3 adds them.

We're running this file in userland and it's not obvious we can correctly import this header, it'd be some "../../" thing out of the testing root directory and might not interact well with all scenarios in which this file is built.

Also the existing tests do not seem to try to import that header, so it seemed the safest way of doing this.

Quoted 38 lines
Quoted 38 lines
tools/testing/selftests/pidfd/pidfd.h +0 -0
  /*
   * The kernel reserves 300 pids via RESERVED_PIDS in kernel/pid.c
   * That means, when it wraps around any pid < 300 will be skipped.
tools/testing/selftests/pidfd/pidfd_getfd_test.c +14 -0
index cd51d547b751..10793fc845ed 100644
@@ -6,6 +6,7 @@
  #include <limits.h>
  #include <linux/types.h>
  #include <poll.h>
+#include <pthread.h>
  #include <sched.h>
  #include <signal.h>
  #include <stdio.h>
@@ -15,6 +16,7 @@
  #include <sys/prctl.h>
  #include <sys/wait.h>
  #include <unistd.h>
+#include <sys/mman.h>
  #include <sys/socket.h>
  #include <linux/kcmp.h>
@@ -114,6 +116,89 @@ static int child(int sk)
  	return ret;
  }
+static int __pidfd_self_thread_worker(unsigned long page_size)
+{
+	int memfd;
+	int newfd;
+	char *ptr;
+	int ret = 0;
+
+	/*
+	 * Unshare our FDs so we have our own set. This means
+	 * PIDFD_SELF_THREAD_GROUP will fail.
+	 */
+	if (unshare(CLONE_FILES) < 0) {
Quoted 8 lines

tools/testing/selftests/pidfd/pidfd_getfd_test.c static int child(int sk) · line 136

Quoted 6 lines
tools/testing/selftests/pidfd/pidfd_getfd_test.c +6 -0
+		ret = -errno;
+		goto exit;
+	}
+
+	/* Truncate, map in and write to our memfd. */
+	memfd = sys_memfd_create("test_self_child", 0);

Missing eror check.

Ack, I had to rapidly change this code to not use the ASSERT_xxx() stuff since abstracted out to helper function for pthread() to invoke and clearly did not do so carefully enough :) thanks for pointing out will fix this + other issues.

Quoted 8 lines

tools/testing/selftests/pidfd/pidfd_getfd_test.c static int child(int sk) · line 139

Quoted 4 lines
tools/testing/selftests/pidfd/pidfd_getfd_test.c +3 -0
+	if (ftruncate(memfd, page_size)) {
+		ret = -errno;
+		goto exit;

Hmm. you probably need scoped cleanup paths. "exit" closes memfd and newfd which isn't open yet and sys_memfd_create() could fail and memfd doesn't need closing?

Yes... oops! Will fix.

Quoted 14 lines
Quoted 14 lines
tools/testing/selftests/pidfd/pidfd_getfd_test.c +13 -0
+	}
+
+	ptr = mmap(NULL, page_size, PROT_READ | PROT_WRITE,
+		   MAP_SHARED, memfd, 0);
+	if (ptr == MAP_FAILED) {
+		ret = -errno;
+		goto exit;
+	}
+	ptr[0] = 'y';
+	if (munmap(ptr, page_size)) {
+		ret = -errno;
+		goto exit;
+	}
Quoted 8 lines

tools/testing/selftests/pidfd/pidfd_getfd_test.c static int child(int sk) · line 158

Quoted 6 lines
tools/testing/selftests/pidfd/pidfd_getfd_test.c +6 -0
+
+	/* Get a thread-local duplicate of our memfd. */
+	newfd = sys_pidfd_getfd(PIDFD_SELF_THREAD, memfd, 0);
+	if (newfd < 0) {
+		ret = -errno;
+		goto exit;

Same comment here - "exit" closes newfd

Ack will fix.

Quoted 34 lines
Quoted 34 lines
tools/testing/selftests/pidfd/pidfd_getfd_test.c +33 -0
+	}
+
+	if (memfd == newfd) {
+		ret = -EINVAL;
+		goto exit;
+	}
+
+	/* Map in new fd and make sure that the data is as expected. */
+	ptr = mmap(NULL, page_size, PROT_READ | PROT_WRITE,
+		   MAP_SHARED, newfd, 0);
+	if (ptr == MAP_FAILED) {
+		ret = -errno;
+		goto exit;
+	}
+
+	if (ptr[0] != 'y') {
+		ret = -EINVAL;
+		goto exit;
+	}
+
+	if (munmap(ptr, page_size)) {
+		ret = -errno;
+		goto exit;
+	}
+
+exit:
+	/* Cleanup. */
+	close(newfd);
+	close(memfd);
+
+	return ret;
+}
+
Quoted 8 lines

tools/testing/selftests/pidfd/pidfd_getfd_test.c static int child(int sk) · line 197

Quoted 6 lines
tools/testing/selftests/pidfd/pidfd_getfd_test.c +6 -0
+static void *pidfd_self_thread_worker(void *arg)
+{
+	unsigned long page_size = (unsigned long)arg;
+	int ret;
+
+	ret = __pidfd_self_thread_worker(page_size);

Don't you want to check error here?

We check it from callers, and it is passed to them we can't assert here as we're not in a test.

Quoted 120 lines
Quoted 120 lines
tools/testing/selftests/pidfd/pidfd_getfd_test.c +55 -0
+
+	return (void *)(intptr_t)ret;
+}
+
  FIXTURE(child)
  {
  	/*
@@ -264,6 +349,57 @@ TEST_F(child, no_strange_EBADF)
  	EXPECT_EQ(errno, ESRCH);
  }
+TEST(pidfd_self)
+{
+	int memfd = sys_memfd_create("test_self", 0);
+	unsigned long page_size = sysconf(_SC_PAGESIZE);
+	int newfd;
+	char *ptr;
+	pthread_t thread;
+	void *res;
+	int err;
+
+	ASSERT_GE(memfd, 0);
+	ASSERT_EQ(ftruncate(memfd, page_size), 0);
+
+	/*
+	 * Map so we can assert that the duplicated fd references the same
+	 * memory.
+	 */
+	ptr = mmap(NULL, page_size, PROT_READ | PROT_WRITE,
+		   MAP_SHARED, memfd, 0);
+	ASSERT_NE(ptr, MAP_FAILED);
+	ptr[0] = 'x';
+	ASSERT_EQ(munmap(ptr, page_size), 0);
+
+	/* Now get a duplicate of our memfd. */
+	newfd = sys_pidfd_getfd(PIDFD_SELF_THREAD_GROUP, memfd, 0);
+	ASSERT_GE(newfd, 0);
+	ASSERT_NE(memfd, newfd);
+
+	/* Now map duplicate fd and make sure it references the same memory. */
+	ptr = mmap(NULL, page_size, PROT_READ | PROT_WRITE,
+		   MAP_SHARED, newfd, 0);
+	ASSERT_NE(ptr, MAP_FAILED);
+	ASSERT_EQ(ptr[0], 'x');
+	ASSERT_EQ(munmap(ptr, page_size), 0);
+
+	/* Cleanup. */
+	close(memfd);
+	close(newfd);
+
+	/*
+	 * Fire up the thread and assert that we can lookup the thread-specific
+	 * PIDFD_SELF_THREAD (also aliased by PIDFD_SELF).
+	 */
+	ASSERT_EQ(pthread_create(&thread, NULL, pidfd_self_thread_worker,
+				 (void *)page_size), 0);
+	ASSERT_EQ(pthread_join(thread, &res), 0);
+	err = (int)(intptr_t)res;
+
+	ASSERT_EQ(err, 0);
+}
+
  #if __NR_pidfd_getfd == -1
  int main(void)
  {
tools/testing/selftests/pidfd/pidfd_setns_test.c +11 -0
index 7c2a4349170a..bbd39dc5ceb7 100644
@@ -752,4 +752,15 @@ TEST(setns_einval)
  	close(fd);
  }
+TEST(setns_pidfd_self_disallowed)
+{
+	ASSERT_EQ(setns(PIDFD_SELF_THREAD, 0), -1);
+	EXPECT_EQ(errno, EBADF);
+
+	errno = 0;
+
+	ASSERT_EQ(setns(PIDFD_SELF_THREAD_GROUP, 0), -1);
+	EXPECT_EQ(errno, EBADF);
+}
+
  TEST_HARNESS_MAIN
tools/testing/selftests/pidfd/pidfd_test.c +24 -2
index 9faa686f90e4..ab5caa0368a1 100644
@@ -42,12 +42,41 @@ static pid_t pidfd_clone(int flags, int *pidfd, int (*fn)(void *))
  #endif
  }
-static int signal_received;
+static pthread_t signal_received;
  static void set_signal_received_on_sigusr1(int sig)
  {
  	if (sig == SIGUSR1)
-		signal_received = 1;
+		signal_received = pthread_self();
+}
+
+static int send_signal(int pidfd)
+{
+	int ret = 0;
+
+	if (sys_pidfd_send_signal(pidfd, SIGUSR1, NULL, 0) < 0) {
+		ret = -EINVAL;
+		goto exit;
+	}
+
+	if (signal_received != pthread_self()) {
+		ret = -EINVAL;
+		goto exit;
+	}
+
+exit:
+	signal_received = 0;
+	return ret;
+}
+
+static void *send_signal_worker(void *arg)
Quoted 8 lines

tools/testing/selftests/pidfd/pidfd_test.c static pid_t pidfd_clone(int flags, int *pidfd, int (*fn)(void *)) · line 78

Quoted 6 lines
tools/testing/selftests/pidfd/pidfd_test.c +6 -0
+{
+	int pidfd = (int)(intptr_t)arg;
+	int ret;
+
+	ret = send_signal(pidfd);
+

Same here - don't you have to check ret?

As in the other case, we check that in the caller rather than here. I will add a comment to both to make it clear that we intentionally forward the error.

Quoted 48 lines
Quoted 48 lines
tools/testing/selftests/pidfd/pidfd_test.c +27 -6
+	return (void *)(intptr_t)ret;
  }
  /*
@@ -56,8 +85,11 @@ static void set_signal_received_on_sigusr1(int sig)
   */
  static int test_pidfd_send_signal_simple_success(void)
  {
-	int pidfd, ret;
+	int pidfd;
  	const char *test_name = "pidfd_send_signal send SIGUSR1";
+	pthread_t thread;
+	void *thread_res;
+	int res;
  	if (!have_pidfd_send_signal) {
  		ksft_test_result_skip(
@@ -74,17 +106,34 @@ static int test_pidfd_send_signal_simple_success(void)
  	signal(SIGUSR1, set_signal_received_on_sigusr1);
-	ret = sys_pidfd_send_signal(pidfd, SIGUSR1, NULL, 0);
+	send_signal(pidfd);
  	close(pidfd);
-	if (ret < 0)
-		ksft_exit_fail_msg("%s test: Failed to send signal\n",
+
+	/* Now try the same thing only using PIDFD_SELF_THREAD_GROUP. */
+	res = send_signal(PIDFD_SELF_THREAD_GROUP);
+	if (res)
+		ksft_exit_fail_msg(
+			"%s test: Error %d on PIDFD_SELF_THREAD_GROUP signal\n",
+			test_name, res);
+
+	/*
+	 * Now try the same thing in a thread and assert thread ID is equal to
+	 * worker thread ID.
+	 */
+	if (pthread_create(&thread, NULL, send_signal_worker,
+			   (void *)(intptr_t)PIDFD_SELF_THREAD))
+		ksft_exit_fail_msg("%s test: Failed to create thread\n",
  				   test_name);
-	if (signal_received != 1)
-		ksft_exit_fail_msg("%s test: Failed to receive signal\n",
+	if (pthread_join(thread, &thread_res))
+		ksft_exit_fail_msg("%s test: Failed to join thread\n",
  				   test_name);
+	res = (int)(intptr_t)thread_res;
+	if (res)
+		ksft_exit_fail_msg(
+			"%s test: Error %d on PIDFD_SELF_THREAD signal\n",
Quoted 8 lines

tools/testing/selftests/pidfd/pidfd_test.c static int test_pidfd_send_signal_simple_success(void) · line 139

Quoted 5 lines
tools/testing/selftests/pidfd/pidfd_test.c +1 -1
+			test_name, res);
-	signal_received = 0;
  	ksft_test_result_pass("%s test: Sent signal\n", test_name);
  	return 0;
  }

thanks,
-- Shuah

Thanks for the review!

maintainer
#6 lore raw

Re: [PATCH 3/3] selftests: pidfd: add tests for PIDFD_SELF_*

Quoted 44 lines · Lorenzo Stoakes
Quoted 34 lines · Shuah Khan
Quoted 33 lines · Lorenzo Stoakes

Add tests to assert that PIDFD_SELF_* correctly refers to the current thread and process.

This is only practically meaningful to pidfd_send_signal() and pidfd_getfd(), but also explicitly test that we disallow this feature for setns() where it would make no sense.

We cannot reasonably wait on ourself using waitid(P_PIDFD, ...) so while in theory PIDFD_SELF_* would work here, we'd be left blocked if we tried it.

We defer testing of mm-specific functionality which uses pidfd, namely process_madvise() and process_mrelease() to mm testing (though note the latter can not be sensibly tested as it would require the testing process to be dying).

---
   tools/testing/selftests/pidfd/pidfd.h         |   8 ++
   .../selftests/pidfd/pidfd_getfd_test.c        | 136 ++++++++++++++++++
   .../selftests/pidfd/pidfd_setns_test.c        |  11 ++
   tools/testing/selftests/pidfd/pidfd_test.c    |  67 +++++++--
   4 files changed, 213 insertions(+), 9 deletions(-)
tools/testing/selftests/pidfd/pidfd.h +3 -0
index 88d6830ee004..1640b711889b 100644
@@ -50,6 +50,14 @@
   #define PIDFD_NONBLOCK O_NONBLOCK
   #endif
+/* System header file may not have this available. */
+#ifndef PIDFD_SELF_THREAD
+#define PIDFD_SELF_THREAD -100
Quoted 8 lines

tools/testing/selftests/pidfd/pidfd.h line 60

Quoted 5 lines
tools/testing/selftests/pidfd/pidfd.h +5 -0
+#endif
+#ifndef PIDFD_SELF_THREAD_GROUP
+#define PIDFD_SELF_THREAD_GROUP -200
+#endif
+

Can't we pick these up from linux/pidfd.h - patch 2/3 adds them.

Quoted 8 lines

We're running this file in userland and it's not obvious we can correctly import this header, it'd be some "../../" thing out of the testing root directory and might not interact well with all scenarios in which this file is built.

Also the existing tests do not seem to try to import that header, so it seemed the safest way of doing this.

kselftest has dependency on "make headers" and tests include headers from linux/ directory

These local make it difficult to maintain these tests in the longer term. Somebody has to go clean these up later.

The import will be fine and you can control that with -I flag in the makefile. Remove these and try to get including linux/pidfd.h working.

I see your v2 and v3. Please revise this patch to include the header file and remove these local defines.

thanks,
-- Shuah