Skip to content

Avoid undefined signed left shift in M2/M3/M4 macros - #648

Open
artyompal wants to merge 1 commit into
bellard:masterfrom
artyompal:fix-m4-signed-left-shift
Open

artyompal wants to merge 1 commit into
bellard:masterfrom
artyompal:fix-m4-signed-left-shift

Conversation

@artyompal

Copy link
Copy Markdown

M4() packs four 1-byte opcodes into a 32-bit integer by shifting op4 left by 24 bits. When op4 >= 128 (such as OP_neq in the typeof optimization), shifting a signed int left by 24 overflows the sign bit and triggers undefined behavior in C11/C17 (§6.5.7p4), caught by UBSan's shift-base check when built without -fwrapv:

quickjs.c:36947:67: runtime error: left shift of 168 by 24 places cannot be represented in type 'int'

Changes:

  • Perform the packing shifts in uint32_t in M2/M3/M4 and cast the result to int so the variadic argument type matches va_arg(ap, int) in code_match().
  • Unpack via uint32_t in code_match() to avoid implementation-defined signed right shifts on negative values.

(Supersedes #367, which leaves M4 with unsigned type uint32_t mismatched with va_arg(ap, int) when op4 >= 128 and does not update the right shifts in code_match().)

M4() packs four 1-byte opcodes into a 32-bit integer by shifting op4 left
by 24 bits. When op4 >= 128 (such as OP_neq in the typeof optimization),
shifting a signed int left by 24 overflows the sign bit and triggers
undefined behavior in C11/C17 (6.5.7p4), caught by UBSan's shift-base
check when built without -fwrapv.

Perform the packing shifts in uint32_t and cast the result to int to match
va_arg(ap, int) in code_match(). Unpack via uint32_t in code_match() to
avoid implementation-defined signed right shifts on negative values.
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.

1 participant