[PATCH 1/2] util.c: add universal search_fdinfo() function

Dmitry V. Levin ldv at strace.io
Sat Mar 25 21:29:01 UTC 2023


On Sun, Mar 26, 2023 at 01:06:02AM +0800, leedagee wrote:
> search_fdinfo() takes pid, fd and line prefix, reads corresponding
> procfs entry and returns a string of the value. The result is allocated
> with strdup(), so caller should free it.
> 
> Signed-off-by: leedagee <leedageea at gmail.com>
> ---
>  src/util.c | 34 +++++++++++++++++++++++++---------
>  1 file changed, 25 insertions(+), 9 deletions(-)
> 
> diff --git a/src/util.c b/src/util.c
> index 4fe45bf13..c27457467 100644
> --- a/src/util.c
> +++ b/src/util.c
> @@ -709,37 +709,53 @@ printdev(struct tcb *tcp, int fd, const char *path, const struct finfo *finfo)
>  	return false;
>  }
>  
> -pid_t
> -pidfd_get_pid(pid_t pid_of_fd, int fd)
> +static char *
> +search_fdinfo(pid_t pid_of_fd, int fd, const char *search_pfx,
> +	      size_t search_pfx_len)
>  {
>  	int proc_pid = 0;
>  	translate_pid(NULL, pid_of_fd, PT_TID, &proc_pid);
>  	if (!proc_pid)
> -		return -1;
> +		return NULL;
>  
>  	char fdi_path[sizeof("/proc/%u/fdinfo/%u") + 2 * sizeof(int) * 3];
>  	xsprintf(fdi_path, "/proc/%u/fdinfo/%u", proc_pid, fd);
>  
>  	FILE *f = fopen_stream(fdi_path, "r");
>  	if (!f)
> -		return -1;
> +		return NULL;
>  
> -	static const char pid_pfx[] = "Pid:\t";
> -	char *line = NULL;
> +	char *line = NULL, *result = NULL;
>  	size_t sz = 0;
> -	pid_t pid = -1;
>  	while (getline(&line, &sz, f) > 0) {
> -		const char *pos = STR_STRIP_PREFIX(line, pid_pfx);
> +		const char *pos =
> +		  str_strip_prefix_len(line, search_pfx, search_pfx_len - 1);

If search_pfx_len is the length of search_pfx, then "search_pfx_len - 1"
is one byte less than necessary.

>  		if (pos == line)
>  			continue;
>  
> -		pid = string_to_uint_ex(pos, NULL, INT_MAX, "\n");
> +		result = xstrdup(pos);
>  		break;
>  	}
>  
>  	free(line);
>  	fclose(f);
>  
> +	return result;
> +}
> +
> +pid_t
> +pidfd_get_pid(pid_t pid_of_fd, int fd)
> +{
> +	static const char pid_pfx[] = "Pid:\t";
> +
> +	char *result = search_fdinfo(pid_of_fd, fd, pid_pfx, sizeof(pid_pfx));

sizeof(pid_pfx) includes trailing '\0', so it's one byte more than needed.

Looks like you pass length+1 to search_fdinfo just to use length-1 there.


-- 
ldv


More information about the Strace-devel mailing list