Skip to content

A signed integer cast to a pointer sign-extends, in a local and in a constant global - #1231

Merged
ehartford merged 1 commit into
mainfrom
int-to-ptr-sign-extends
Sep 20, 2026
Merged

ehartford merged 1 commit into
mainfrom
int-to-ptr-sign-extends

Conversation

@ehartford

Copy link
Copy Markdown
Contributor

sqlite3.h's SQLITE_TRANSIENT is ((void (*)(void *))-1). c_import binds it correctly; codegen miscompiled it, silently, in two places.

  • Local cast (src/CodegenDispatch.w, Int → Ptr): a bare inttoptr from an i32. LLVM zero-extends a narrower integer, so -1 became 0x00000000FFFFFFFF. A signed source now widens to 64 bits first; an unsigned source still zero-extends.
  • Constant global (src/CodegenTraits.w, module binding whose initializer folds to an integer): a pointer-typed binding was handled only for the value 0. Any other value fell to the generic path and was emitted as an integer global (@G = internal constant i32 -1 in the IR) and read back as eight bytes, so its upper half was adjacent memory. It is now a pointer constant. Binds LLVMConstIntToPtr.

Effect: sqlite3_bind_text(..., SQLITE_TRANSIENT) passed SQLite a pointer that was not SQLITE_TRANSIENT. lldb: bindText → vdbeUnbind → vdbeMemClear called it as a destructor (EXC_BAD_ACCESS). Found while rewriting examples/c-interop.

Test: behav_int_to_pointer_cast_sign_extends.w covers the local, the global, a zero global, a negative *const u8 global, a runtime signed value and an unsigned one. It fails at its first assertion on the previous compiler.

Battery, seed-driven at 444dbb4, alone in its batch: build, :fixpoint, :test, :move-audit, :drop-audit, :test-green, :last-green all green.

…constant global

sqlite3.h's SQLITE_TRANSIENT is ((void (*)(void *))-1). c_import binds it
correctly; codegen did not. Two exact lines:

- CodegenDispatch.w, the Int -> Ptr cast, emitted a bare inttoptr from an i32.
  LLVM zero-extends a narrower integer, so -1 became 0x00000000FFFFFFFF.
- CodegenTraits.w, a module binding whose initializer folds to an integer,
  handled a pointer-typed binding only for the value 0. Any other value fell
  to the generic path and was emitted as an i32 global (`@G = internal
  constant i32 -1` in the IR) and read back as eight bytes.

sqlite3_bind_text(..., SQLITE_TRANSIENT) therefore passed SQLite a pointer
that was not SQLITE_TRANSIENT; lldb shows bindText -> vdbeUnbind ->
vdbeMemClear calling it as a destructor. Binds LLVMConstIntToPtr for the
constant case.

behav_int_to_pointer_cast_sign_extends.w fails at its first assertion on the
previous compiler and passes on this one.
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