Skip to content

vcgencmd: Fix off-by-one when copying gencmd response - #217

Open
popcornmix wants to merge 1 commit into
raspberrypi:masterfrom
popcornmix:gencmd_off
Open

popcornmix wants to merge 1 commit into
raspberrypi:masterfrom
popcornmix:gencmd_off

Conversation

@popcornmix

Copy link
Copy Markdown
Contributor

strncat(dst, src, n) can write n characters plus a terminator, so passing the full buffer size could write one byte past the end of result. It also triggers -Wstringop-truncation/-Wstringop-overflow.

Copy a bounded length with memcpy and terminate explicitly.

Fixes: #197

strncat(dst, src, n) can write n characters plus a terminator, so
passing the full buffer size could write one byte past the end of
result. It also triggers -Wstringop-truncation/-Wstringop-overflow.

Copy a bounded length with memcpy and terminate explicitly.

Fixes: raspberrypi#197
@pelwell

pelwell commented Oct 2, 2026

Copy link
Copy Markdown
Collaborator

How is this better than the simpler and more efficient:

   strncpy(result, p+6, MAX_STRING);
   result[MAX_STRING - 1] = 0;

@popcornmix

popcornmix commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor Author

I tried both suggestions from #197 but neither works.
Both fix the overflow, but gcc still warns about each one (tested with gcc 15 at -O2 and -O3, -Wall -Wextra):

  • strncat(..., result_len - 1): "output may be truncated copying 4095 bytes from a string of length 4099".
  • strncpy(..., result_len) then result[result_len - 1] = 0: "output may be truncated copying 4096 bytes from a string of length 4099".

Both warnings come from -Wstringop-truncation, which -Wall turns on, so -Werror builds would still fail. The issue's own error output already shows the result_len - 1 version failing.

gcc treats the source as possibly 4099 bytes long, more than result can hold, so any str* copy limited by length gets flagged. The memcpy version in 08fe43a is the only one I've found that builds cleanly.

(your latest suggestion has the same warning).

@pelwell

pelwell commented Oct 3, 2026

Copy link
Copy Markdown
Collaborator

Something is wrong if we are having to rewrite code not because we aren't happy with how it functions but because the compiler doesn't understand how we expect it to behave. Truncation is fine because it's never going to happen - non-termination is not, and we've got that covered. How about my patch + make the p array one element (4 bytes) larger?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Compiler error (gcc-16.1.1) about vcgencmd with strncat

2 participants