From: Yuan Chen do_batch() strips trailing comments by truncating the line at '#' before checking whether fgets() filled the buffer. If a batch line longer than the buffer contains a '#' within the first sizeof(buf) - 1 bytes, the truncation makes strlen(buf) smaller and the line-length check is bypassed. The unread remainder of the line then stays in the file stream and is parsed and executed as a separate command on the next loop iteration. Continuation lines handled below are affected the same way: an overlong continuation line containing '#' bypasses the "command is too long" check, and its unread remainder is executed as a separate command. Record whether fgets() truncated the line before stripping the comment, and use that for the line-length checks, so overlong lines are rejected regardless of comments. Fixes: 71bb428fe2c1 ("tools: bpf: add bpftool") Signed-off-by: Yuan Chen --- tools/bpf/bpftool/main.c | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/tools/bpf/bpftool/main.c b/tools/bpf/bpftool/main.c index 0bbb2e198450..cef779aa72fb 100644 --- a/tools/bpf/bpftool/main.c +++ b/tools/bpf/bpftool/main.c @@ -367,11 +367,13 @@ static int do_batch(int argc, char **argv) if (json_output) jsonw_start_array(json_wtr); while (fgets(buf, sizeof(buf), fp)) { + bool truncated = strlen(buf) == sizeof(buf) - 1; + cp = strchr(buf, '#'); if (cp) *cp = '\0'; - if (strlen(buf) == sizeof(buf) - 1) { + if (truncated) { line_too_long = true; break; } @@ -380,6 +382,8 @@ static int do_batch(int argc, char **argv) * with '\' in the batch file). */ while ((cp = strstr(buf, "\\\n")) != NULL) { + bool cont_truncated; + if (!fgets(contline, sizeof(contline), fp) || strlen(contline) == 0) { p_err("missing continuation line on command %u", @@ -388,11 +392,14 @@ static int do_batch(int argc, char **argv) goto err_close; } + cont_truncated = strlen(contline) == sizeof(contline) - 1; + cp = strchr(contline, '#'); if (cp) *cp = '\0'; - if (strlen(buf) + strlen(contline) + 1 > sizeof(buf)) { + if (cont_truncated || + strlen(buf) + strlen(contline) + 1 > sizeof(buf)) { p_err("command %u is too long", lines); err = -1; goto err_close; -- 2.54.0