Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

fix: always-on ECS release-safety guards + single-source entity packing

esenginedf5411ca3862
diff --git a/.github/workflows/cross-platform.yml b/.github/workflows/cross-platform.yml
index 8d7c7222f..a9f6c727b 100644
--- a/.github/workflows/cross-platform.yml
+++ b/.github/workflows/cross-platform.yml
@@ -112,6 +112,20 @@ jobs:
shell: bash
run: cp $(find node_modules/.pnpm -name 'esbuild.wasm' -path '*/esbuild-wasm/*' | head -1) desktop/public/esbuild.wasm
+ # Native ECS release-safety tests (ES_VERIFY guards + PackedId packing).
+ # Compiled WITHOUT -DES_DEBUG to mirror the shipped Release config (where
+ # ES_ASSERT is stripped) and under ASAN, so the OOB write / index-alias
+ # these guards prevent are caught deterministically. Header-only: needs
+ # only a C++20 compiler, no CMake/emsdk. MSVC has different sanitizer flags.
+ - name: Run ECS release-safety tests (ASAN, release-mirror)
+ if: matrix.platform != 'windows-latest'
+ shell: bash
+ run: |
+ c++ -std=c++20 -fsanitize=address -I src \
+ tests/ecs/test_registry_safety.cpp src/esengine/core/Log.cpp \
+ -o test_registry_safety
+ ./test_registry_safety
+
# Type-check & test SDK first (editor depends on it)
- name: Type-check SDK
run: pnpm --filter ./sdk exec tsc --noEmit
diff --git a/sdk/src/types.ts b/sdk/src/types.ts
index fbc8c7277..63fcbdba0 100644
--- a/sdk/src/types.ts
+++ b/sdk/src/types.ts
@@ -23,25 +23,36 @@
*/
export type Entity = number;
-/** Bit widths of the packed Entity representation (must match C++). */
-export const ENTITY_INDEX_BITS = 20;
-export const ENTITY_GEN_BITS = 12;
-export const ENTITY_INDEX_MASK = (1 << ENTITY_INDEX_BITS) - 1;
+/**
+ * Bit widths of the packed Entity representation. MUST match the C++ split
+ * (`PackedId<22, 10>` via `Entity::Layout` in core/Types.hpp / PackedId.hpp).
+ */
+export const ENTITY_INDEX_BITS = 22;
+export const ENTITY_GEN_BITS = 10;
+/** Number of representable indices (2^INDEX_BITS) — used for overflow-safe packing. */
+const ENTITY_INDEX_COUNT = 2 ** ENTITY_INDEX_BITS;
+export const ENTITY_INDEX_MASK = ENTITY_INDEX_COUNT - 1;
export const ENTITY_GEN_MASK = (1 << ENTITY_GEN_BITS) - 1;
-/** 20-bit index portion of an Entity handle. */
+/** Index portion (low ENTITY_INDEX_BITS) of an Entity handle. */
export function entityIndex(e: Entity): number {
+ // `& MASK` is correct even for e > 2^31: the low INDEX_BITS survive the
+ // int32 coercion, and MASK (2^22-1) is well within int32 range.
return e & ENTITY_INDEX_MASK;
}
-/** 12-bit generation portion of an Entity handle. */
+/** Generation portion (high ENTITY_GEN_BITS) of an Entity handle. */
export function entityGeneration(e: Entity): number {
+ // `>>>` reads e as unsigned 32-bit, so this is correct for the full u32 range.
return (e >>> ENTITY_INDEX_BITS) & ENTITY_GEN_MASK;
}
/** Construct an Entity from an index + generation pair. */
export function makeEntity(index: number, generation: number): Entity {
- return (((generation & ENTITY_GEN_MASK) << ENTITY_INDEX_BITS) | (index & ENTITY_INDEX_MASK)) as Entity;
+ // Build via multiply + `>>> 0` rather than `<<`: `gen << 22` would overflow
+ // int32 (go negative) for high generations. The product is < 2^32, and
+ // `>>> 0` coerces it to the same unsigned value C++ stores in Entity::raw.
+ return (((generation & ENTITY_GEN_MASK) * ENTITY_INDEX_COUNT + (index & ENTITY_INDEX_MASK)) >>> 0) as Entity;
}
/**
diff --git a/sdk/tests/entity-generation.test.ts b/sdk/tests/entity-generation.test.ts
index bf3a52e4a..9ea447ea9 100644
--- a/sdk/tests/entity-generation.test.ts
+++ b/sdk/tests/entity-generation.test.ts
@@ -6,6 +6,7 @@ import { describe, expect, it } from 'vitest';
import { World } from '../src/world';
import {
ENTITY_GEN_BITS,
+ ENTITY_GEN_MASK,
ENTITY_INDEX_BITS,
ENTITY_INDEX_MASK,
entityGeneration,
@@ -22,16 +23,25 @@ describe('Entity packing', () => {
expect(entityGeneration(e)).toBe(7);
});
- it('uses the documented 20/12 bit layout', () => {
- expect(ENTITY_INDEX_BITS).toBe(20);
- expect(ENTITY_GEN_BITS).toBe(12);
- expect(ENTITY_INDEX_MASK).toBe(0xFFFFF);
+ it('uses the documented 22/10 bit layout (matches C++ PackedId<22,10>)', () => {
+ expect(ENTITY_INDEX_BITS).toBe(22);
+ expect(ENTITY_GEN_BITS).toBe(10);
+ expect(ENTITY_INDEX_MASK).toBe(0x3FFFFF);
});
it('masks out-of-range index/generation to their documented widths', () => {
const e = makeEntity(0xFFFFFFFF, 0xFFFFFFFF);
- expect(entityIndex(e)).toBe(0xFFFFF);
- expect(entityGeneration(e)).toBe(0xFFF);
+ expect(entityIndex(e)).toBe(0x3FFFFF);
+ expect(entityGeneration(e)).toBe(0x3FF);
+ });
+
+ it('packs a high generation without int32 overflow (stays unsigned)', () => {
+ // gen << 22 would overflow int32 to a negative number; makeEntity must
+ // produce the same unsigned u32 the C++ side stores in Entity::raw.
+ const e = makeEntity(7, ENTITY_GEN_MASK); // max generation
+ expect(e).toBeGreaterThan(0); // not a negative int32
+ expect(entityIndex(e)).toBe(7);
+ expect(entityGeneration(e)).toBe(ENTITY_GEN_MASK);
});
it('treats both sentinels as invalid', () => {
diff --git a/src/esengine/core/Log.hpp b/src/esengine/core/Log.hpp
index 2ec6fb7b2..1761338f6 100644
--- a/src/esengine/core/Log.hpp
+++ b/src/esengine/core/Log.hpp
@@ -21,6 +21,7 @@
// Standard library
#include <charconv>
+#include <cstdlib>
#include <functional>
#include <iomanip>
#include <iostream>
@@ -325,4 +326,93 @@ private:
#define ES_ASSERT(condition, message) ((void)0)
#endif
+// =============================================================================
+// Verify Macro (always-on boundary guard)
+// =============================================================================
+
+namespace detail {
+
+/**
+ * @brief Optional sink invoked whenever an ES_VERIFY condition fails.
+ *
+ * @details ES_VERIFY always logs + recovers (in both debug and release). This
+ * hook makes a failure *observable*: release-mode safety tests install
+ * a counter to assert "the guard fired and we degraded gracefully",
+ * and a dev build can install an aborting hook to fail loudly. Default
+ * is null (log + recover only). Not thread-safe to set — install once
+ * at startup or from a single-threaded test.
+ */
+using VerifyHook = void (*)(const char* cond, const char* file, int line);
+
+inline VerifyHook& verifyHook() {
+ static VerifyHook hook = nullptr;
+ return hook;
+}
+
+} // namespace detail
+
+/**
+ * @brief Always-on boundary guard — the release-safe counterpart to ES_ASSERT.
+ *
+ * @details Unlike ES_ASSERT, which is stripped in release builds (leaving
+ * boundary checks absent in shipped wasm), ES_VERIFY is compiled into
+ * *every* build. On failure it logs an error, fires the optional
+ * detail::verifyHook(), then runs the recovery statement(s) so the
+ * caller degrades gracefully instead of falling through into an OOB
+ * write / integer overflow / UB.
+ *
+ * @param cond Boolean expression that must hold.
+ * @param ... Recovery statement(s) run on failure (e.g. `return`,
+ * `return fallback`, `continue`). Variadic so the recovery may
+ * itself contain commas (e.g. brace-enclosed multi-statements).
+ *
+ * @par Discipline
+ * Use ES_VERIFY for any check that prevents OOB / overflow / UB on values
+ * derived from runtime data or external input (entity handles, deserialized
+ * indices, container subscripts). Reserve ES_ASSERT for pure-logic invariants
+ * that cannot happen if the surrounding code is correct.
+ *
+ * @code
+ * T& get(u32 i) {
+ * static T fallback{};
+ * ES_VERIFY(i < size_, { fallback = T{}; return fallback; });
+ * return data_[i];
+ * }
+ * @endcode
+ */
+#define ES_VERIFY(cond, ...) \
+ do { \
+ if (!(cond)) [[unlikely]] { \
+ ES_LOG_ERROR("Verify failed: ({}) at {}:{}", #cond, __FILE__, __LINE__); \
+ if (auto _es_vh = ::esengine::detail::verifyHook()) { \
+ _es_vh(#cond, __FILE__, __LINE__); \
+ } \
+ __VA_ARGS__; \
+ } \
+ } while (false)
+
+/**
+ * @brief Always-on **fatal** guard for invariants with no safe recovery.
+ *
+ * @details Use when a violated precondition leaves no valid value to return and
+ * continuing would be UB (e.g. returning `*nullptr` from a `T&`
+ * accessor). Unlike ES_ASSERT this is kept in release, so instead of a
+ * message-less SEGV the build aborts with a clear diagnostic. Prefer
+ * the recoverable ES_VERIFY whenever a sane fallback exists; reach for
+ * this only when there genuinely isn't one.
+ *
+ * @param cond Boolean expression that must hold.
+ * @param message Human-readable description of the invariant.
+ */
+#define ES_VERIFY_FATAL(cond, message) \
+ do { \
+ if (!(cond)) [[unlikely]] { \
+ ES_LOG_FATAL("Fatal: {} ({}) at {}:{}", message, #cond, __FILE__, __LINE__); \
+ if (auto _es_vh = ::esengine::detail::verifyHook()) { \
+ _es_vh(#cond, __FILE__, __LINE__); \
+ } \
+ std::abort(); \
+ } \
+ } while (false)
+
} // namespace esengine
diff --git a/src/esengine/core/PackedId.hpp b/src/esengine/core/PackedId.hpp
new file mode 100644
index 000000000..428ac86c8
--- /dev/null
+++ b/src/esengine/core/PackedId.hpp
@@ -0,0 +1,74 @@
+/**
+ * @file PackedId.hpp
+ * @brief Single source of truth for index+generation bit-packing.
+ *
+ * @details Both the ECS @ref esengine::Entity and the resource
+ * @ref esengine::resource::Handle pack a slot index plus a reuse
+ * generation into one integer. They used to each copy-paste the
+ * masks/shifts (three independent packings drifted apart — see the
+ * RC re-architecture's "multiple sources of truth" root cause). This
+ * template is the one definition both delegate to; the bit split is a
+ * parameter.
+ *
+ * The u32 storage is deliberate and **structurally enforced** by the
+ * static_assert below: a packed id must fit in 32 bits so that
+ * - Entity stays 4 bytes (cache-friendly ECS dense arrays, cheap FFI),
+ * - the value is a JS safe integer (< 2^53) and crosses embind as a
+ * plain `number`,
+ * - it fits box2d's 32-bit wasm32 body user-data.
+ * Widening to a 64-bit id is therefore a deliberate, ABI-versioned
+ * change, not something a bit-split tweak can do by accident.
+ *
+ * @author ESEngine Team
+ * @date 2026
+ *
+ * @copyright Copyright (c) 2026 ESEngine Team
+ * Licensed under the MIT License.
+ */
+#pragma once
+
+#include <cstdint>
+
+namespace esengine {
+
+/**
+ * @brief Index+generation packing into a u32, parameterized by the bit split.
+ * @tparam IndexBits Number of low bits holding the slot index.
+ * @tparam GenBits Number of high bits holding the reuse generation.
+ */
+template <std::uint32_t IndexBits, std::uint32_t GenBits>
+struct PackedId {
+ static_assert(IndexBits + GenBits <= 32,
+ "PackedId index+generation must fit in a u32 (keeps the id 4 bytes, "
+ "a JS safe integer, and within box2d's 32-bit wasm32 user-data). "
+ "Widen the storage as a deliberate, ABI-versioned change instead.");
+ static_assert(IndexBits > 0 && GenBits > 0, "both fields need at least one bit");
+
+ static constexpr std::uint32_t INDEX_BITS = IndexBits;
+ static constexpr std::uint32_t GEN_BITS = GenBits;
+ static constexpr std::uint32_t INDEX_MASK = (std::uint32_t{1} << IndexBits) - 1;
+ static constexpr std::uint32_t GEN_MASK = (std::uint32_t{1} << GenBits) - 1;
+
+ /** @brief Largest representable slot index. */
+ static constexpr std::uint32_t maxIndex() { return INDEX_MASK; }
+ /** @brief Largest representable generation before it wraps. */
+ static constexpr std::uint32_t maxGeneration() { return GEN_MASK; }
+
+ /** @brief Extract the slot index from a packed value. */
+ static constexpr std::uint32_t indexOf(std::uint32_t raw) { return raw & INDEX_MASK; }
+ /** @brief Extract the generation from a packed value. */
+ static constexpr std::uint32_t generationOf(std::uint32_t raw) {
+ return (raw >> IndexBits) & GEN_MASK;
+ }
+ /**
+ * @brief Pack an index + generation. Out-of-range inputs are masked, not
+ * trusted — callers that mint ids from runtime values must
+ * range-check the index first (e.g. Registry::activateIndex's
+ * ES_VERIFY), which is the structural home for that guard.
+ */
+ static constexpr std::uint32_t pack(std::uint32_t index, std::uint32_t generation) {
+ return ((generation & GEN_MASK) << IndexBits) | (index & INDEX_MASK);
+ }
+};
+
+} // namespace esengine
diff --git a/src/esengine/core/ServiceRegistry.hpp b/src/esengine/core/ServiceRegistry.hpp
index ed694d65a..ac1835edd 100644
--- a/src/esengine/core/ServiceRegistry.hpp
+++ b/src/esengine/core/ServiceRegistry.hpp
@@ -104,6 +104,14 @@ public:
template<typename T>
T& require() {
T* svc = getService<T>();
+ // NOTE: this is the natural home for ES_VERIFY_FATAL (a missing required
+ // service has no safe T& to return, and *nullptr silently corrupts wasm
+ // address 0 rather than faulting). Deferred: turning it on surfaces
+ // ~33 existing call paths (UI layout/scrollview tests) that invoke
+ // require() on services they never register and "work" only via that
+ // null-address tolerance. Those callers must register/guard their
+ // services first; until then keep the debug-only assert to avoid
+ // destabilizing them. See foundation-audit follow-up.
ES_ASSERT(svc != nullptr, "Required service not registered");
return *svc;
}
diff --git a/src/esengine/core/Types.hpp b/src/esengine/core/Types.hpp
index d856ea401..7cee636b8 100644
--- a/src/esengine/core/Types.hpp
+++ b/src/esengine/core/Types.hpp
@@ -26,6 +26,9 @@
#include <string>
#include <vector>
+// Project includes
+#include "PackedId.hpp"
+
namespace esengine {
// =============================================================================
@@ -114,32 +117,38 @@ constexpr Shared<T> makeShared(Args&&... args) {
/**
* @brief Entity identifier with packed index + generation
*
- * @details Entities pack a 20-bit index and 12-bit generation into a single
+ * @details Entities pack a 22-bit index and 10-bit generation into a single
* u32. The generation detects stale references after an entity is
- * destroyed and its index recycled (ABA problem).
+ * destroyed and its index recycled (ABA problem). The bit-packing
+ * math lives once in @ref PackedId; this just wires Entity to it.
+ *
+ * Layout: [generation(10) | index(22)]
+ * - Max entities: 4,194,303 (2^22 - 1)
+ * - Max generations: 1,023 (2^10 - 1) before wrap
*
- * Layout: [generation(12) | index(20)]
- * - Max entities: 1,048,575 (2^20 - 1)
- * - Max generations: 4,095 (2^12 - 1) before wrap
+ * The split is u32 (4 bytes) on purpose — see PackedId.hpp for why
+ * (FFI as a plain JS number, box2d 32-bit user-data, dense-array
+ * cache behaviour). PackedId's static_assert enforces it.
*/
struct Entity {
u32 raw;
- static constexpr u32 INDEX_BITS = 20;
- static constexpr u32 GEN_BITS = 12;
- static constexpr u32 INDEX_MASK = (1u << INDEX_BITS) - 1;
- static constexpr u32 GEN_MASK = (1u << GEN_BITS) - 1;
+ using Layout = PackedId<22, 10>;
+ static constexpr u32 INDEX_BITS = Layout::INDEX_BITS;
+ static constexpr u32 GEN_BITS = Layout::GEN_BITS;
+ static constexpr u32 INDEX_MASK = Layout::INDEX_MASK;
+ static constexpr u32 GEN_MASK = Layout::GEN_MASK;
static constexpr u32 INVALID_RAW = 0xFFFFFFFF;
constexpr Entity() : raw(INVALID_RAW) {}
explicit constexpr Entity(u32 r) : raw(r) {}
explicit constexpr operator u32() const { return raw; }
- /** @brief Gets the 20-bit entity index */
- constexpr u32 index() const { return raw & INDEX_MASK; }
+ /** @brief Gets the entity index */
+ constexpr u32 index() const { return Layout::indexOf(raw); }
- /** @brief Gets the 12-bit generation number */
- constexpr u32 generation() const { return (raw >> INDEX_BITS) & GEN_MASK; }
+ /** @brief Gets the generation number */
+ constexpr u32 generation() const { return Layout::generationOf(raw); }
/** @brief Checks if this is not the invalid sentinel */
constexpr bool isValid() const { return raw != INVALID_RAW; }
@@ -151,9 +160,7 @@ struct Entity {
static constexpr Entity fromRaw(u32 v) { return Entity(v); }
/** @brief Creates an Entity from index and generation */
- static constexpr Entity make(u32 idx, u32 gen) {
- return Entity(((gen & GEN_MASK) << INDEX_BITS) | (idx & INDEX_MASK));
- }
+ static constexpr Entity make(u32 idx, u32 gen) { return Entity(Layout::pack(idx, gen)); }
constexpr bool operator==(Entity other) const { return raw == other.raw; }
constexpr bool operator!=(Entity other) const { return raw != other.raw; }
diff --git a/src/esengine/ecs/ComponentMask.hpp b/src/esengine/ecs/ComponentMask.hpp
index 83b9a08fc..152c09251 100644
--- a/src/esengine/ecs/ComponentMask.hpp
+++ b/src/esengine/ecs/ComponentMask.hpp
@@ -16,6 +16,7 @@
// Includes
// =============================================================================
+#include "../core/Log.hpp"
#include "../core/Types.hpp"
#ifdef _MSC_VER
@@ -121,7 +122,10 @@ public:
private:
/** @brief Count trailing zeros; val must be non-zero */
static u32 ctz64(u64 val) {
- ES_ASSERT(val != 0, "ctz64 undefined for zero");
+ // Defense-in-depth: __builtin_ctzll(0) is UB. Callers guard with
+ // `while (word != 0)`, so this never fires in correct code, but the
+ // guard is always-on (ES_ASSERT is stripped in release). 64 = "no set bit".
+ ES_VERIFY(val != 0, return 64);
#if defined(__GNUC__) || defined(__clang__)
return static_cast<u32>(__builtin_ctzll(val));
#elif defined(_MSC_VER)
diff --git a/src/esengine/ecs/Entity.hpp b/src/esengine/ecs/Entity.hpp
index 6cf81aa39..6daf0a2bd 100644
--- a/src/esengine/ecs/Entity.hpp
+++ b/src/esengine/ecs/Entity.hpp
@@ -2,7 +2,9 @@
* @file Entity.hpp
* @brief Entity utilities for the ECS system
* @details The core Entity type is defined in Types.hpp as a packed struct
- * with 20-bit index and 12-bit generation.
+ * with a 22-bit index and 10-bit generation. The packing math is
+ * shared with resource handles via core/PackedId.hpp — there is a
+ * single id representation (Entity::raw), no separate 64-bit handle.
*
* @author ESEngine Team
* @date 2025
@@ -18,21 +20,3 @@
// Project includes
#include "../core/Types.hpp"
-
-namespace esengine::ecs {
-
-// =============================================================================
-// Entity Handle Functions (64-bit, for FFI)
-// =============================================================================
-
-/**
- * @brief Combines entity index and generation into a single 64-bit handle
- * @param index The entity index (lower 32 bits)
- * @param generation The generation number (upper 32 bits)
- * @return A packed 64-bit handle
- */
-inline constexpr u64 makeEntityHandle(u32 index, u32 generation) {
- return (static_cast<u64>(generation) << 32) | static_cast<u64>(index);
-}
-
-} // namespace esengine::ecs
diff --git a/src/esengine/ecs/Registry.hpp b/src/esengine/ecs/Registry.hpp
index c4432b978..05663afcf 100644
--- a/src/esengine/ecs/Registry.hpp
+++ b/src/esengine/ecs/Registry.hpp
@@ -116,6 +116,11 @@ public:
* @return The newly created Entity, or INVALID_ENTITY if index is already alive
*/
Entity restore(u32 index) {
+ // Release-safe: reject a deserialized index beyond the addressable range
+ // up front, before mutating next_index_ below (activateIndex would also
+ // refuse, but only after next_index_ was already advanced, leaving the
+ // registry unable to allocate fresh indices).
+ ES_VERIFY(index <= Entity::INDEX_MASK, return INVALID_ENTITY);
if (index < entityValid_.size() && entityValid_[index]) {
return INVALID_ENTITY;
}
@@ -206,11 +211,6 @@ public:
generations_[idx] == entity.generation();
}
- /** @brief Gets the packed u64 handle (for legacy/FFI compatibility) */
- u64 entityHandle(Entity entity) const {
- return makeEntityHandle(entity.index(), entity.generation());
- }
-
usize entityCount() const {
return entity_count_;
}
@@ -245,7 +245,10 @@ public:
*/
template<typename T, typename... Args>
T& emplace(Entity entity, Args&&... args) {
- ES_ASSERT(valid(entity), "Invalid entity");
+ // Release-safe: an invalid entity indexes component_masks_ out of bounds
+ // below (entity.index() of the invalid sentinel is 0xFFFFF), and
+ // ES_ASSERT is stripped in release -> OOB write. Degrade to a fallback.
+ ES_VERIFY(valid(entity), { static T fallback{}; fallback = T{}; return fallback; });
auto& pool = assurePool<T>();
auto& result = pool.emplace(entity, std::forward<Args>(args)...);
component_masks_[entity.index()].set(componentTypeId<T>());
@@ -264,7 +267,8 @@ public:
*/
template<typename T, typename... Args>
T& emplaceOrReplace(Entity entity, Args&&... args) {
- ES_ASSERT(valid(entity), "Invalid entity");
+ // Release-safe: see emplace() — invalid entity -> OOB write on the mask.
+ ES_VERIFY(valid(entity), { static T fallback{}; fallback = T{}; return fallback; });
auto& pool = assurePool<T>();
if (pool.contains(entity)) {
@@ -565,7 +569,11 @@ private:
* @brief Activates an entity index: resizes arrays, bumps generation, returns packed Entity
*/
Entity activateIndex(u32 index) {
- ES_ASSERT(index <= Entity::INDEX_MASK, "Entity index overflow (20-bit limit exceeded)");
+ // Release-safe: an index beyond the 20-bit range would silently alias an
+ // existing slot via Entity::make's mask (ES_ASSERT is stripped in
+ // release). Refuse before any state mutation. restore() passes a
+ // deserialized index here, so this also guards scene loading.
+ ES_VERIFY(index <= Entity::INDEX_MASK, return INVALID_ENTITY);
if (index >= entityValid_.size()) {
entityValid_.resize(index + 1, false);
generations_.resize(index + 1, 0);
diff --git a/src/esengine/ecs/SparseSet.hpp b/src/esengine/ecs/SparseSet.hpp
index b7a554e69..3b33836d0 100644
--- a/src/esengine/ecs/SparseSet.hpp
+++ b/src/esengine/ecs/SparseSet.hpp
@@ -18,6 +18,7 @@
// =============================================================================
// Project includes
+#include "../core/Log.hpp"
#include "../core/Types.hpp"
#include "Entity.hpp"
@@ -265,7 +266,10 @@ public:
*/
template<typename... Args>
T& emplace(Entity entity, Args&&... args) {
- ES_ASSERT(!contains(entity), "Entity already has component");
+ // Release-safe: a duplicate emplace would append a second dense slot and
+ // overwrite the sparse->dense mapping, corrupting the set (ES_ASSERT is
+ // stripped in release). Degrade to returning the existing component.
+ ES_VERIFY(!contains(entity), return get(entity));
const u32 idx = entity.index();
const auto pageIndex = idx / SPARSE_PAGE_SIZE;
@@ -435,8 +439,12 @@ public:
* @note Asserts if the entity is not in the set
*/
usize indexOf(Entity entity) const {
- ES_ASSERT(contains(entity), "Entity not in set");
- return denseIndexOf(entity);
+ // Release-safe: a non-member would otherwise return INVALID_INDEX and be
+ // used as a dense-array subscript (OOB). Compute the dense index once and
+ // verify membership; callers must treat INVALID_INDEX as "not present".
+ const u32 di = denseIndexOf(entity);
+ ES_VERIFY(di != INVALID_INDEX && dense_[di] == entity, return INVALID_INDEX);
+ return di;
}
private:
diff --git a/src/esengine/ecs/View.hpp b/src/esengine/ecs/View.hpp
index 99101687e..cf6232244 100644
--- a/src/esengine/ecs/View.hpp
+++ b/src/esengine/ecs/View.hpp
@@ -68,6 +68,11 @@ public:
* @return The current entity ID
*/
Entity operator*() const {
+ // Kept as ES_ASSERT (not ES_VERIFY) deliberately: this is the ECS query
+ // hot path, and entities_ is structurally non-null for any iterator the
+ // View API hands out (begin()/end() always pass a live pointer). Only a
+ // manually default-constructed iterator violates it — a pure-logic
+ // misuse, not a runtime-data boundary — so no per-deref branch here.
ES_ASSERT(entities_ != nullptr, "Dereferencing null ViewIterator");
return (*entities_)[index_];
}
diff --git a/src/esengine/resource/Handle.hpp b/src/esengine/resource/Handle.hpp
index fd2783b16..d4c9ae885 100644
--- a/src/esengine/resource/Handle.hpp
+++ b/src/esengine/resource/Handle.hpp
@@ -49,10 +49,13 @@ class Handle {
public:
using IdType = u32;
- static constexpr u32 INDEX_BITS = 20;
- static constexpr u32 GEN_BITS = 12;
- static constexpr u32 INDEX_MASK = (1u << INDEX_BITS) - 1;
- static constexpr u32 GEN_MASK = (1u << GEN_BITS) - 1;
+ // Bit-packing math is shared with Entity via PackedId (single source). The
+ // resource handle split stays 20+12 (independent of the ECS entity split).
+ using Layout = PackedId<20, 12>;
+ static constexpr u32 INDEX_BITS = Layout::INDEX_BITS;
+ static constexpr u32 GEN_BITS = Layout::GEN_BITS;
+ static constexpr u32 INDEX_MASK = Layout::INDEX_MASK;
+ static constexpr u32 GEN_MASK = Layout::GEN_MASK;
static constexpr IdType INVALID = 0;
/** @brief Creates an invalid handle */
@@ -70,7 +73,7 @@ public:
* @param generation Reuse counter for the slot (max 4095)
*/
static Handle fromParts(u32 index, u32 generation) {
- return Handle(((generation & GEN_MASK) << INDEX_BITS) | (index & INDEX_MASK));
+ return Handle(Layout::pack(index, generation));
}
/** @brief Checks if the handle references a valid resource */
@@ -80,16 +83,16 @@ public:
IdType id() const { return id_; }
/** @brief Extracts the slot index from the packed handle */
- u32 index() const { return id_ & INDEX_MASK; }
+ u32 index() const { return Layout::indexOf(id_); }
/** @brief Extracts the generation from the packed handle */
- u32 generation() const { return (id_ >> INDEX_BITS) & GEN_MASK; }
+ u32 generation() const { return Layout::generationOf(id_); }
/** @brief Extracts index from a raw packed ID */
- static u32 extractIndex(IdType packed) { return packed & INDEX_MASK; }
+ static u32 extractIndex(IdType packed) { return Layout::indexOf(packed); }
/** @brief Extracts generation from a raw packed ID */
- static u32 extractGeneration(IdType packed) { return (packed >> INDEX_BITS) & GEN_MASK; }
+ static u32 extractGeneration(IdType packed) { return Layout::generationOf(packed); }
/** @brief Equality comparison */
bool operator==(const Handle& other) const { return id_ == other.id_; }
diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt
index 5a8af6ef4..139deac21 100644
--- a/tests/CMakeLists.txt
+++ b/tests/CMakeLists.txt
@@ -124,4 +124,10 @@ add_executable(test_registry_safety
${CMAKE_SOURCE_DIR}/src/esengine/core/Log.cpp
)
target_include_directories(test_registry_safety PRIVATE ${CMAKE_SOURCE_DIR}/src)
+# Run under AddressSanitizer: the bugs this guards (emplace-on-invalid OOB write,
+# over-range index alias) are memory-safety faults that only ASAN catches
+# deterministically. Skipped on MSVC (different sanitizer flag syntax).
+set(_es_safety_asan $<OR:$<CXX_COMPILER_ID:GNU>,$<CXX_COMPILER_ID:Clang>,$<CXX_COMPILER_ID:AppleClang>>)
+target_compile_options(test_registry_safety PRIVATE $<${_es_safety_asan}:-fsanitize=address>)
+target_link_options(test_registry_safety PRIVATE $<${_es_safety_asan}:-fsanitize=address>)
add_test(NAME test_registry_safety COMMAND test_registry_safety)
diff --git a/tests/ecs/test_registry_safety.cpp b/tests/ecs/test_registry_safety.cpp
index e4d40fc48..9dbe49f8f 100644
--- a/tests/ecs/test_registry_safety.cpp
+++ b/tests/ecs/test_registry_safety.cpp
@@ -15,6 +15,7 @@
#include <cstdio>
using esengine::Entity;
+using esengine::u32;
using esengine::ecs::Registry;
namespace {
@@ -29,6 +30,11 @@ static int g_failures = 0;
else { std::printf("ok: %s\n", msg); } \
} while (0)
+// Counts ES_VERIFY failures so tests can assert "the guard fired and we
+// degraded gracefully" rather than just "it didn't crash".
+static int g_verifyHits = 0;
+static void countingVerifyHook(const char*, const char*, int) { ++g_verifyHits; }
+
int main() {
// --- A6: get<T> on an entity without the component returns fallback (no OOB) ---
{
@@ -85,6 +91,93 @@ int main() {
CHECK(r.valid(a) && r.valid(b), "both recreated entities are valid");
}
+ // --- ES_VERIFY: emplace / emplaceOrReplace on an invalid entity is release-safe ---
+ // Without the guard, component_masks_[Entity{}.index() == 0xFFFFF] is an OOB
+ // write (ES_ASSERT is stripped here). The guard must fire and return a fallback.
+ {
+ esengine::detail::verifyHook() = countingVerifyHook;
+ Registry r;
+
+ g_verifyHits = 0;
+ Pos& p = r.emplace<Pos>(Entity{}, Pos{7.0f, 8.0f});
+ CHECK(g_verifyHits == 1, "emplace(invalid) fires the verify hook");
+ CHECK(p.x == 1.0f && p.y == 2.0f, "emplace(invalid) returns fallback defaults (no OOB write)");
+
+ g_verifyHits = 0;
+ Pos& p2 = r.emplaceOrReplace<Pos>(Entity{}, Pos{9.0f, 9.0f});
+ CHECK(g_verifyHits == 1, "emplaceOrReplace(invalid) fires the verify hook");
+ CHECK(p2.x == 1.0f, "emplaceOrReplace(invalid) returns fallback (no OOB write)");
+
+ esengine::detail::verifyHook() = nullptr;
+ }
+
+ // --- ES_VERIFY: restore() with an over-range (deserialized) index is refused ---
+ // This is the scene-loading path: a corrupt/huge index must not silently
+ // alias an existing slot via Entity::make's 20-bit mask.
+ {
+ esengine::detail::verifyHook() = countingVerifyHook;
+ Registry r;
+ Entity a = r.create(); // real entity at index 0
+
+ g_verifyHits = 0;
+ Entity bad = r.restore(Entity::INDEX_MASK + 1); // beyond the 20-bit range
+ CHECK(g_verifyHits == 1, "restore(over-range) fires the verify hook");
+ CHECK(!bad.isValid(), "restore(over-range) returns INVALID_ENTITY (no silent alias)");
+ CHECK(r.valid(a), "the pre-existing entity is untouched after a bad restore");
+
+ // next_index_ must not be corrupted by the rejected restore: fresh
+ // allocation still works and does not alias the survivor.
+ Entity c = r.create();
+ CHECK(r.valid(c) && c.index() != a.index(), "create() still works after a rejected restore");
+
+ esengine::detail::verifyHook() = nullptr;
+ }
+
+ // --- ES_VERIFY: duplicate emplace degrades to the existing component ---
+ // A second emplace on the same entity would push a duplicate dense slot and
+ // overwrite the sparse mapping (corruption). The guard degrades to get().
+ {
+ esengine::detail::verifyHook() = countingVerifyHook;
+ Registry r;
+ Entity e = r.create();
+ r.emplace<Pos>(e, Pos{3.0f, 4.0f});
+
+ g_verifyHits = 0;
+ Pos& dup = r.emplace<Pos>(e, Pos{100.0f, 200.0f}); // duplicate
+ CHECK(g_verifyHits == 1, "duplicate emplace fires the verify hook");
+ CHECK(dup.x == 3.0f && dup.y == 4.0f, "duplicate emplace returns the existing component (no corruption)");
+ CHECK(r.get<Pos>(e).x == 3.0f, "entity still maps to the original component");
+
+ esengine::detail::verifyHook() = nullptr;
+ }
+
+ // --- PackedId / Entity 22+10 packing is correct and round-trips ---
+ {
+ CHECK(Entity::INDEX_BITS == 22u && Entity::GEN_BITS == 10u, "Entity split is 22+10");
+ CHECK(Entity::INDEX_MASK == 0x3FFFFFu, "index mask is 2^22-1");
+ CHECK(Entity::GEN_MASK == 0x3FFu, "generation mask is 2^10-1");
+
+ // Round-trip across the corners, including the max generation that would
+ // overflow a signed-32 shift on the JS side (here it's unsigned C++).
+ const u32 idxs[] = {0u, 1u, 1234u, Entity::INDEX_MASK};
+ const u32 gens[] = {1u, 2u, 512u, Entity::GEN_MASK};
+ bool roundtrip_ok = true;
+ for (u32 idx : idxs) {
+ for (u32 gen : gens) {
+ Entity e = Entity::make(idx, gen);
+ if (e.index() != idx || e.generation() != gen) roundtrip_ok = false;
+ if (Entity::fromRaw(e.id()) != e) roundtrip_ok = false;
+ }
+ }
+ CHECK(roundtrip_ok, "Entity::make/index/generation/fromRaw round-trip for all corners");
+
+ // PackedId is the single source the split is derived from.
+ using L = esengine::PackedId<22, 10>;
+ CHECK(L::pack(7u, 3u) == Entity::make(7u, 3u).raw, "PackedId::pack matches Entity::make");
+ CHECK(L::indexOf(L::pack(99u, 5u)) == 99u, "PackedId index round-trips");
+ CHECK(L::generationOf(L::pack(99u, 5u)) == 5u, "PackedId generation round-trips");
+ }
+
if (g_failures == 0) {
std::printf("\nALL ECS SAFETY TESTS PASSED\n");
return 0;