Skip to content

Fix palette-packing decant logic to avoid UB from invalid iterator#2031

Merged
Rangi42 merged 2 commits into
gbdev:masterfrom
Rangi42:fix-decanting
Jul 23, 2026
Merged

Fix palette-packing decant logic to avoid UB from invalid iterator#2031
Rangi42 merged 2 commits into
gbdev:masterfrom
Rangi42:fix-decanting

Conversation

@Rangi42

@Rangi42 Rangi42 commented Jul 23, 2026

Copy link
Copy Markdown
Contributor

The "Iterate through the component's color sets, and transfer them" logic shifted from.begin(), which would make subsequent std::advance calls go past _assigned.end() and cause UB. This rewrite uses absolute numeric indexes into _assigned to avoid that potential problem.

I haven't been able to craft a test case that actually reaches that piece of logic, and I suspect that it's unreachable given how we sort and process color sets before decanting, but cannot prove that; so it stays in. (Maybe if we added 4bpp 16-colors-per-palette support, it would become reachable?)

This approach can be compared with the pal_packing.rs port, which also uses absolute indexes (but changed how color sets work so there's no extra complexity of skipping over free slots).

@Rangi42 Rangi42 added this to the 1.0.3 milestone Jul 23, 2026
@Rangi42
Rangi42 requested a review from ISSOtm July 23, 2026 00:52
@Rangi42 Rangi42 added bug Unexpected behavior / crashes; to be fixed ASAP! rgbgfx This affects RGBGFX labels Jul 23, 2026
The "Iterate through the component's color sets, and transfer them"
logic shifted `from.begin()`, which would make subsequent `std::advance`
calls go past `_assigned.end()` and cause UB. This rewrite uses absolute
numeric indexes into `_assigned` to avoid that potential problem.

I haven't been able to craft a test case that actually *reaches*
that piece of logic, and I suspect that it's unreachable given how
we sort and process color sets before decanting, but cannot prove
that; so it stays in. (Maybe if we added 4bpp 16-colors-per-palette
support, it would become reachable?)

@ISSOtm ISSOtm left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Logic looks sound, I only have some comments regarding the code style itself

Comment thread src/gfx/pal_packing.cpp Outdated
Comment thread src/gfx/pal_packing.cpp Outdated
@Rangi42
Rangi42 merged commit 604c69e into gbdev:master Jul 23, 2026
28 checks passed
@Rangi42
Rangi42 deleted the fix-decanting branch July 23, 2026 03:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Unexpected behavior / crashes; to be fixed ASAP! rgbgfx This affects RGBGFX

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants