Skip to content

libsql-ffi: Fix sqlean sha256() under gcc 11 and later - #2334

Open
colinhacks wants to merge 2 commits into
tursodatabase:mainfrom
colinhacks:fix-sqlean-sha256-aliasing
Open

colinhacks wants to merge 2 commits into
tursodatabase:mainfrom
colinhacks:fix-sqlean-sha256-aliasing

Conversation

@colinhacks

@colinhacks colinhacks commented Nov 19, 2026 •

Copy link
Copy Markdown

With the sqlean crypto extension, sha256() returned the wrong hash when the C code was built with gcc 11 or later at -O2 or -O3. sha256_final wrote the message length into the byte buffer through a sha2_word64* cast. That breaks strict aliasing, and gcc 11+ reorders the store around the final transform.

The write now goes through MEMCPY_BCOPY (the file's memcpy macro). The two length writes in sha512's last step had the same cast, so they use it too. sha512() was right on every compiler I tried, but it no longer depends on that.

Testing

There's no test in the PR. The workspace test run builds libsql-ffi with multiple-ciphers (bindings/c turns on encryption), which doesn't compile sqlean, and it builds the C code at -O0, where the old code was right anyway.

I built bundled/src/sqlite3.c and bundled/sqlean/crypto/*.c with -DSQLITE_CORE, called crypto_init, and compared against shasum:

Build sha256('a') before after
gcc 16 -O2 767DD50D… (wrong) CA978112…
gcc 16 -O3 767DD50D… (wrong) CA978112…
clang -O3 CA978112… CA978112…

With gcc 16 -O3, both hashes match shasum after the change for inputs of 0, 55, 56, 64, 111, 112 and 1000 bytes, which cover both padding branches.

Fixes #2333

sha256_final stored the message length through a sha2_word64 pointer
into the byte buffer, a strict-aliasing violation that gcc 11 and later
reorder at -O2 and -O3, so sha256() returned the wrong hash. Store it
with memcpy, and do the same for the two length writes in sha512's last
step.
Copilot AI balanced review requested due to automatic review settings November 19, 2026 18:52

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

The workspace test run builds libsql-ffi with multiple-ciphers, which doesn't compile sqlean, so the test can't find sha256().

This branch has not been deployed

No deployments
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.

sha256() returns a wrong hash when libsql-ffi is built with gcc 11 or later

2 participants