Re: [PATCH v2 6/9] perf tests: Use scandirat for shell script finding

From: Namhyung Kim
Date: Fri Feb 09 2024 - 23:41:19 EST


On Wed, Jan 31, 2024 at 4:15 PM Ian Rogers <irogers@xxxxxxxxxx> wrote:
>
> Avoid filename appending buffers by using openat, faccessat and
> scandirat more widely. Turn the script's path back to a file name
> using readlink from /proc/<pid>/fd/<fd>.
>
> Read the script's description using api/io.h to avoid fdopen
> conversions. Whilst reading perform additional sanity checks on the
> script's contents.
>
> Signed-off-by: Ian Rogers <irogers@xxxxxxxxxx>
> ---
[SNIP]
> -static const char *shell_test__description(char *description, size_t size,
> - const char *path, const char *name)
> +static char *shell_test__description(int dir_fd, const char *name)
> {
> - FILE *fp;
> - char filename[PATH_MAX];
> - int ch;
> + struct io io;
> + char buf[128], desc[256];
> + int ch, pos = 0;
>
> - path__join(filename, sizeof(filename), path, name);
> - fp = fopen(filename, "r");
> - if (!fp)
> + io__init(&io, openat(dir_fd, name, O_RDONLY), buf, sizeof(buf));
> + if (io.fd < 0)
> return NULL;
>
> /* Skip first line - should be #!/bin/sh Shebang */
> + if (io__get_char(&io) != '#')
> + goto err_out;
> + if (io__get_char(&io) != '!')
> + goto err_out;
> do {
> - ch = fgetc(fp);
> - } while (ch != EOF && ch != '\n');
> -
> - description = fgets(description, size, fp);
> - fclose(fp);
> + ch = io__get_char(&io);
> + if (ch < 0)
> + goto err_out;
> + } while (ch != '\n');
>
> - /* Assume first char on line is omment everything after that desc */
> - return description ? strim(description + 1) : NULL;
> + do {
> + ch = io__get_char(&io);
> + if (ch < 0)
> + goto err_out;
> + } while (ch == '#' || isspace(ch));
> + while (ch > 0 && ch != '\n') {
> + desc[pos++] = ch;
> + if (pos >= (int)sizeof(desc) - 1)

Maybe (pos == sizeof(desc) - 2) ? I'm not sure what happens if it has a
description longer than the buffer size.

> + break;
> + ch = io__get_char(&io);
> + }
> + while (pos > 0 && isspace(desc[--pos]))
> + ;
> + desc[++pos] = '\0';

Wouldn't it overflow the buffer?

Thanks,
Namhyung


> + close(io.fd);
> + return strdup(desc);
> +err_out:
> + close(io.fd);
> + return NULL;
> }