Skip to content

Odd-sized Scratch allocations misalign the next reference counter #185

Closed

Description

@dimensionscape

Scratch::alloc in src/hx/thread/Scratch.cpp advances the pooled cursor by bytes + sizeof(int), without alignment padding. The next allocation constructs an int reference counter at that cursor and later increments and decrements it through int*.

Two simultaneously live one-byte allocations are enough to misalign the second counter:

auto a = hx::thread::Scratch::alloc(1);
auto b = hx::thread::Scratch::alloc(1);
printf("counter alignment remainder: %zu\n",
    (size_t)(b.view.ptr.ptr - sizeof(int)) % alignof(int));

The current implementation printed counter alignment remainder: 1 on Linux x86_64. With an aligned arena base and four-byte ints, the second counter begins at offset 5. The placement construction and subsequent int accesses are therefore misaligned C++ operations. They can fail on stricter architectures even though x86_64 tolerated them in this probe. I have not reproduced an architecture-specific crash.

The harness used Haxe 4.3.3 as a native host against checkout 793e054, included View.hpp and unchanged Scratch.cpp directly with its API-level-500 branch enabled in that translation unit, and disabled precompiled headers. This was a direct test of the implementation, not a full Haxe 5 application.

Align each counter and account for the padded reservation consistently when checking capacity and releasing space. Also establish the alignment promised for the exposed byte view before callers reinterpret it as wider native types. At minimum, the allocator's own int counter must always be aligned.

Add odd-size allocation sequences, arena-boundary cases and an alignment-sanitizer test. This occurs even with reverse-order destruction and is separate from the overlapping lifetime problem in #184. The Bytes/Memory alignment fixes in #171 do not cover Scratch.

Activity

  1. added
    haxe 5Only affects Haxe 5 (API level 500); fixable here, needs Haxe 5 to test
    on Oct 19, 2026
  2. added 3 commits that reference this issue on Oct 20, 2026
    13cd55a
    c33bd76
    2223f09
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    haxe 5Only affects Haxe 5 (API level 500); fixable here, needs Haxe 5 to test

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions