[PATCH v2 4/6] util.c: add pidfd_get_pid

Ákos Uzonyi uzonyi.akos at gmail.com
Fri May 15 19:18:38 UTC 2020


* defs.h (pidfd_get_pid): New function definition.
* utils.c (pidfd_get_pid): New function, returns the pid of a pidfd.
(printpidfd): Rewritten using pidfd_get_pid.
(printfd_pid): Changed printpidfd arguments

Signed-off-by: Ákos Uzonyi <uzonyi.akos at gmail.com>
---
 defs.h |  4 ++++
 util.c | 37 +++++++++++++++++++------------------
 2 files changed, 23 insertions(+), 18 deletions(-)

diff --git a/defs.h b/defs.h
index 39985bbe..c0bda6ce 100644
--- a/defs.h
+++ b/defs.h
@@ -1029,6 +1029,10 @@ printpath(struct tcb *, kernel_ulong_t addr);
 # define TIMESPEC_TEXT_BUFSIZE \
 		(sizeof(long long) * 3 * 2 + sizeof("{tv_sec=-, tv_nsec=}"))
 
+/**
+ * Returns the pid associated with pidfd of the process with ID pid_of_fd
+ */
+extern pid_t pidfd_get_pid(pid_t pid_of_fd, int fd);
 /**
  * Print file descriptor fd owned by process with ID pid (from the PID NS
  * of the tracer).
diff --git a/util.c b/util.c
index 3f562efc..4d3f77fb 100644
--- a/util.c
+++ b/util.c
@@ -567,43 +567,44 @@ printdev(struct tcb *tcp, int fd, const char *path)
 	return false;
 }
 
-static bool
-printpidfd(struct tcb *tcp, int fd, const char *path)
+pid_t
+pidfd_get_pid(pid_t pid_of_fd, int fd)
 {
-	static const char pidfd_path[] = "anon_inode:[pidfd]";
-
-	if (strcmp(path, pidfd_path))
-		return false;
-
 	char fdi_path[sizeof("/proc/%u/fdinfo/%u") + 2 * sizeof(int) * 3];
-	xsprintf(fdi_path, "/proc/%u/fdinfo/%u", tcp->pid, fd);
+	xsprintf(fdi_path, "/proc/%u/fdinfo/%u", pid_of_fd, fd);
 
 	FILE *f = fopen_stream(fdi_path, "r");
 	if (!f)
-		return false;
+		return -1;
 
 	static const char pid_pfx[] = "Pid:\t";
 	char *line = NULL;
 	size_t sz = 0;
-	bool ret = false;
+	pid_t pid = -1;
 	while (getline(&line, &sz, f) > 0) {
 		const char *pos = STR_STRIP_PREFIX(line, pid_pfx);
 		if (pos == line)
 			continue;
 
-		int pid = string_to_uint_ex(pos, NULL, INT_MAX, "\n");
-		if (pid >= 0) {
-			tprintf("pid:%d", pid);
-			ret = true;
-		}
-
+		pid = string_to_uint_ex(pos, NULL, INT_MAX, "\n");
 		break;
 	}
 
 	free(line);
 	fclose(f);
 
-	return ret;
+	return pid;
+}
+
+static bool
+printpidfd(pid_t pid_of_fd, int fd)
+{
+	pid_t pid = pidfd_get_pid(pid_of_fd, fd);
+	if (pid <= 0)
+		return false;
+
+	tprintf("pid:%d", pid);
+	return true;
 }
 
 void
@@ -620,7 +621,7 @@ printfd_pid(struct tcb *tcp, pid_t pid, int fd)
 		    printdev(tcp, fd, path))
 			goto printed;
 		if (is_number_in_set(DECODE_FD_PIDFD, decode_fd_set) &&
-		    printpidfd(tcp, fd, path))
+		    printpidfd(pid, fd))
 			goto printed;
 		print_quoted_string_ex(path, strlen(path),
 			QUOTE_OMIT_LEADING_TRAILING_QUOTES, "<>");
-- 
2.26.2



More information about the Strace-devel mailing list