Skip to content

Refuse a short buffer in every setter - #975

Merged
gijzelaerr merged 3 commits into
masterfrom
fix/setter-short-buffer
Nov 8, 2026
Merged

gijzelaerr merged 3 commits into
masterfrom
fix/setter-short-buffer

Conversation

@gijzelaerr

Copy link
Copy Markdown
Owner

Fixes #969.

Many snap7.util setters assign with a slice, so a buffer that's too short silently grows. It then gets written back to the PLC at the wrong length, or the fields after it shift.

Every setter now raises ValueError when the value doesn't fit, before changing anything. That includes DB and Row, which call these setters with their own buffers.

Behaviour changes:

  • set_lreal raised struct.error here, and set_string, set_bool and the single-byte setters raised IndexError. They now raise ValueError, so code catching the old exceptions needs updating.
  • Code that relied on a setter growing its buffer now fails.

set_string needs 2 + max_size bytes, since it pads to max_size. set_wstring needs room for the header and the value only, because it doesn't pad and its default max_size is 16382. A negative byte_index isn't covered here.

This touches the same line of set_wchar as #968, so whichever lands second has a small conflict.

Checks: full test suite, mypy, ruff and pre-commit pass locally on Windows. Every setter is tested with an exact buffer, one byte short, and offset by one. Not tested against a real PLC.

Slice assignments past the end grow a bytearray, which changes the length written to the PLC or shifts later fields. Every setter now raises ValueError instead, including the ones that raised struct.error or IndexError.
@gijzelaerr
gijzelaerr enabled auto-merge (squash) November 8, 2026 05:24
@gijzelaerr
gijzelaerr merged commit 6df71ee into master Nov 8, 2026
19 of 20 checks passed
@gijzelaerr gijzelaerr mentioned this pull request Nov 8, 2026
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.

Most setters silently grow a bytearray that is too short

1 participant