Skip to content

copy_or_zeromem: add compiler value barrier on masks - #833

Open
smolkaj wants to merge 1 commit into
libtom:developfrom
smolkaj:fix/copy-or-zeromem-barrier
Open

smolkaj wants to merge 1 commit into
libtom:developfrom
smolkaj:fix/copy-or-zeromem-barrier

Conversation

@smolkaj

@smolkaj smolkaj commented Dec 3, 2026 •

Copy link
Copy Markdown

Fixes: #832

Adds a portable compiler barrier on the bitmasks in copy_or_zeromem so optimizing compilers do not turn the branchless masking loop into a secret-dependent branch or a memset call.

Verified branchless output across optimization levels on x86-64 and ARM64 (with and without inline assembly enabled) and ran the test suite under Clang and GCC.

Checklist

  • if this fixes something: added a Fixes: tag to the commit message

Prevent optimizing compilers (in particular Clang 21 on x86-64 and
AArch64) from propagating the 0 / all-ones range of `mask` and
`fastMask` into secret-dependent branches or `memset` calls.

Uses an empty inline-assembly barrier on GCC/Clang when `LTC_NO_ASM`
and `__STRICT_ANSI__` are not defined, with a typed `volatile` fallback
otherwise, and undefines the local macro at EOF for `AMALGAM=1` builds.

Fixes: libtom#832

@sjaeckel sjaeckel 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.

Thanks for the PR :)

Basically LGTM.

If you agree with the proposal, please amend the commit and also add a Fixes: 5c0b1b4bf6ee ("add copy_or_zeromem()") to the commit message.

#if !defined(__STRICT_ANSI__) && (defined(__GNUC__) || defined(__clang__)) && !defined(LTC_NO_ASM)
#define LTC_VALUE_BARRIER(type, x) __asm__ ("" : "+r" (x))
#else
#define LTC_VALUE_BARRIER(type, x) do { volatile type ltc_vb_ = (x); (x) = ltc_vb_; } while (0)

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.

Suggested change
#define LTC_VALUE_BARRIER(type, x) do { volatile type ltc_vb_ = (x); (x) = ltc_vb_; } while (0)
#define LTC_VALUE_BARRIER(type, x) do { volatile type LTC_TMPVAR(vb) = (x); (x) = LTC_TMPVAR(vb); } while (0)

WDYT?

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.

Clang 21 compiles copy_or_zeromem into a secret branch and memset call

2 participants