Re: [PATCH] tools/counter: Reject invalid watch fields before narrowing

From: Fabrice Gasnier

Date: Fri Nov 20 2026 - 12:40:54 EST


On 11/20/26 07:19, Zhu Jun wrote:
> The channel, component ID and parent fields are all eight bits wide.
> The current parser accepts trailing characters and silently narrows
> values above 255, which can select the wrong counter watch. Parse
> these fields before assignment and only accept a value in range.
>
> Fixes: 1e73427f6635 ("tools/counter: add a flexible watch events tool")
> Signed-off-by: Zhu Jun <zhujun2@xxxxxxxxxxxxxxxxxxxx>
> ---

Hi Zhu

Acked-by: Fabrice Gasnier <fabrice.gasnier@xxxxxxxxxxx>

Best Regards,
Thanks,
Fabrice

> tools/counter/counter_watch_events.c | 51 ++++++++++------------------
> 1 file changed, 18 insertions(+), 33 deletions(-)
>
> diff --git a/tools/counter/counter_watch_events.c b/tools/counter/counter_watch_events.c
> index 15e21b0c5ffd..432a0cb9d300 100644
> --- a/tools/counter/counter_watch_events.c
> +++ b/tools/counter/counter_watch_events.c
> @@ -13,6 +13,7 @@
> #include <linux/kernel.h>
> #include <stdlib.h>
> #include <stdio.h>
> +#include <stdint.h>
> #include <string.h>
> #include <sys/ioctl.h>
> #include <unistd.h>
> @@ -288,44 +289,28 @@ int main(int argc, char **argv)
> watches[i].event = ret;
> break;
> case WATCH_CHANNEL:
> - if (!value) {
> - fprintf(stderr, "Invalid chan=<number>\n");
> - rc = EXIT_FAILURE;
> - goto err_free_watches;
> - }
> - watches[i].channel = strtoul(value, NULL, 10);
> - if (errno) {
> - perror("strtoul failed: chan=<number>\n");
> - rc = EXIT_FAILURE;
> - goto err_free_watches;
> - }
> - break;
> case WATCH_ID:
> - if (!value) {
> - fprintf(stderr, "Invalid id=<number>\n");
> - rc = EXIT_FAILURE;
> - goto err_free_watches;
> - }
> - watches[i].component.id = strtoul(value, NULL, 10);
> - if (errno) {
> - perror("strtoul failed: id=<number>\n");
> - rc = EXIT_FAILURE;
> - goto err_free_watches;
> - }
> - break;
> - case WATCH_PARENT:
> - if (!value) {
> - fprintf(stderr, "Invalid parent=<number>\n");
> - rc = EXIT_FAILURE;
> - goto err_free_watches;
> - }
> - watches[i].component.parent = strtoul(value, NULL, 10);
> - if (errno) {
> - perror("strtoul failed: parent=<number>\n");
> + case WATCH_PARENT: {
> + long num;
> + char *end;
> +
> + errno = 0;
> + num = value ? strtol(value, &end, 10) : -1;
> + if (!value || end == value || *end || errno ||
> + num < 0 || num > UINT8_MAX) {
> + fprintf(stderr, "Invalid value for %s\n",
> + counter_watch_subopts[ret]);
> rc = EXIT_FAILURE;
> goto err_free_watches;
> }
> + if (ret == WATCH_CHANNEL)
> + watches[i].channel = num;
> + else if (ret == WATCH_ID)
> + watches[i].component.id = num;
> + else
> + watches[i].component.parent = num;
> break;
> + }
> default:
> fprintf(stderr, "Unknown suboption '%s'\n", value);
> rc = EXIT_FAILURE;
>
>