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.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(bindings): boundarySpan — always-on validation for every raw pointer+length entry
yhhf638d34bc79e
diff --git a/.github/workflows/build.yml b/.github/workflows/build.ymlindex 9a780fcb8..a04f59953 100644--- a/.github/workflows/build.yml+++ b/.github/workflows/build.yml@@ -71,7 +71,7 @@ jobs:test_ecs test_events test_particle test_tilemap test_sparse_set \test_resource_pool test_shader_variant test_log_format test_registry_safety \test_shader_device test_draw_params test_texture_fb test_buffer_device \- test_compressed_format test_batch_builder+ test_compressed_format test_batch_builder test_boundary_span# The root package.json is ESM, so the emscripten-emitted .js must run as .cjs.- name: Run C++ test harnesses@@ -79,7 +79,7 @@ jobs:for t in test_ecs test_events test_particle test_tilemap test_sparse_set \test_resource_pool test_shader_variant test_log_format test_registry_safety \test_shader_device test_draw_params test_texture_fb test_buffer_device \- test_compressed_format test_batch_builder; do+ test_compressed_format test_batch_builder test_boundary_span; docp "build/wasm/web-tests/bin/$t.js" "build/wasm/web-tests/bin/$t.cjs"echo "=== $t"node "build/wasm/web-tests/bin/$t.cjs"diff --git a/docs/REARCHITECTURE.md b/docs/REARCHITECTURE.mdindex bbf269ccd..cabc1dfe2 100644--- a/docs/REARCHITECTURE.md+++ b/docs/REARCHITECTURE.md@@ -138,14 +138,13 @@- `SparseSet` 新增 `version()`:在组件缓冲**重分配**(emplace 扩容)、**relocate**(remove swap-pop、sort/rebuildSparse)时自增——作为 RC3 跨界指针失效守卫的**单一来源**,取代已删除的 `SchemaComponentPool::poolVersion`(后者还漏了 remove 时不自增的 bug)。- **验证**:native MSVC harness 编译+运行通过(version() 在 fill/remove/clear 后均自增;destroy 后回收的实体无残留组件);SDK typecheck + 2012 测试全过。-### RC3 错误/生命周期 — 🟡 进行中(错误通道已落地并测试)+### RC3 错误/生命周期 — ✅ 已全部收口(2026-07-07 边界校验常开落地)错误模型已定:**保持 `-fno-exceptions` + 显式状态 + onAbort 死亡标志**(不增体积/不降速)。- ✅ **错误通道(已完成)**:新增 `moduleHealth.ts`——`WasmModuleAborted` + 按模块的死亡标志 + `installAbortGuard`(挂 emscripten `Module.onAbort`,保留既有 handler)。`handleWasmError` 对 `WasmModuleAborted` **重抛不吞**(abort 是终态,吞掉就是继续调用尸体)。`BuiltinBridge` 在 `connect` 装守卫,并在唯一收口 `resolveAndCache_` 把四个边界方法包成"调用前短路 + 调用中 abort 则致命重抛"。验证:typecheck + 8 个新测试 + 全套 2020 测试通过。- ✅ **RAII `_malloc`(已完成)**:新增 `wasmScratch.ts`——`withScratch(mod, alloc => …)` / `withMalloc`,作用域内分配的所有缓冲在回调返回**或抛异常**时按逆序释放。把 9 个文件的全部瞬时分配站点(runtimeLoader、TextureLoader、PhysicsSystem×3、TimelineUploader×6、ModuleBackend、SpineController×4、tilemapAPI×3、tiledLoader×4、TextRenderer)迁到该助手;持久缓冲(material/draw/renderer/geometry 的 alloc-once)与已有 try/finally 的站点不动。验证:5 个新 helper 测试 + typecheck + 全套 2025 测试;逐一人工复核 TimelineUploader/SpineController 等复杂多缓冲迁移,行为逐字节保持。- ✅ **指针失效(已查清,主路径本就安全)**:复核 `BuiltinBridge.resolvePtrGetter/Setter` 后确认——活的 `getXxxPtr` 路径**每次访问都重新 `getPtrFn(e)` 取指针、并重新读 `mod.HEAPF32`**(emscripten 在堆增长时会替换 `Module.HEAPF32`)。所以对重分配与视图失效**都已天然安全**,无需把 version 接进来。RC2 新增的 `SparseSet::version()` 保留为"单一来源",供未来任何**缓存**指针的调用方复核。真正的残留风险只在个别**缓存** HEAP 视图的子系统读取,属下条范畴。-- ⏳ **RC3 剩余**(较低优先级 / 需 emsdk):- 1. C++ 边界校验始终开启(不被 release 的 `ES_ASSERT` 剥离)——生成的 embind 包装已有 `valid(entity)` 守卫,需审计补齐其余入口(C++ harness 可验证)。- 2. 各子系统桥接(physics/spine/tilemap/timeline)调用前接 `throwIfModuleAborted` + 缓存 HEAP 视图处改为每次重读(目前只有主模块经 BuiltinBridge 装了 abort 守卫)。+- ✅ **边界校验常开(2026-07-07 收口)**:全边界审计确认——实体路径已全闭环(EHT 生成包装的 `valid/has` 门 + Registry/SparseSet 的 `ES_VERIFY` 常开守卫使"无守卫的实体解引用"入口为 **0**;顺带补齐 `getOrEmplace` 缺失的 `ES_VERIFY(valid)` 不对称)。真正的缺口是 **26 个裸指针+长度入口**(JS 传 `uintptr_t`+count 直接 `reinterpret_cast`,坏 count 在写路径可致沙箱内堆损坏)——新增 `bindings/BoundarySpan.hpp` 单一收口:`boundarySpan<T>(ptr, count, what)` 常开三重校验(空指针、`count*sizeof` 溢出、**wasm 线性内存范围** `emscripten_get_heap_size()`),失败记日志并拒绝整个调用。已应用到 Renderer(spine/text 提交、两处矩阵、物理批同步、mesh2d)、Geometry(init/indices/update/两处 transform + `draw_meshWithUniforms` 记录游走越界修复)、Tilemap(5 入 3 出)、sdfFromAlpha、ImmediateDraw、ResourceManager(3 处,含 `rm_createTextureEx` 无视 `pixelsLen` 的过读修复)、physics side module(多边形/链条 + 链条点数上限)。验证:新 `tests/bindings/test_boundary_span.cpp`(emscripten 下测真实堆界)+ registry_safety + 7 个 headless 场景(sprite/text/tilemap/mesh2d/粒子/后处理/spine 全部经过被改路径)全 PASS。+- ✅ 各子系统桥接 abort 守卫:随 F2 统一 `WasmBridge` 基类落地(全子系统覆盖)。### RC5 渲染唯一路径 — ✅ 渲染/GPU 部分已落地(SDK 部分待续)**已完成(PR #41–#47,已并入 master)**:diff --git a/src/esengine/bindings/BoundarySpan.hpp b/src/esengine/bindings/BoundarySpan.hppnew file mode 100644index 000000000..5abecf34b--- /dev/null+++ b/src/esengine/bindings/BoundarySpan.hpp@@ -0,0 +1,75 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file BoundarySpan.hpp+ * @brief Always-on validation for JS-supplied pointer+length pairs at the WASM boundary.+ * @details A `uintptr_t` + count from JS is a bare claim about linear memory. Trusting it+ * blindly lets a wrong count (or a 0 from a failed malloc / an undefined that+ * coerced) read garbage or — on write paths — silently corrupt unrelated engine+ * state inside the sandbox. These helpers are the single boundary gate:+ * null-checked, overflow-checked, and range-checked against the actual wasm+ * heap size. They are ALWAYS ON (never compiled out in release); on failure they+ * log and return nullptr so the entry point degrades instead of hitting UB.+ *+ * @author ESEngine Team+ * @date 2026+ *+ * @copyright Copyright (c) 2026 ESEngine Team+ * Licensed under the Apache License, Version 2.0.+ */+#pragma once++#include "../core/Types.hpp"+#include "../core/Log.hpp"++#ifdef __EMSCRIPTEN__+#include <emscripten/heap.h>+#endif++#include <cstdint>++namespace esengine {++namespace detail {+inline usize boundaryHeapSize() {+#ifdef __EMSCRIPTEN__+ return emscripten_get_heap_size();+#else+ // Native builds have no single linear-memory bound; null/overflow checks still apply.+ return SIZE_MAX;+#endif+}+} // namespace detail++/**+ * @brief Validates a JS-supplied pointer to @p count elements of T and returns it typed.+ * @return The typed pointer, or nullptr (after an always-on error log) when the pointer+ * is null, the byte size overflows, or the span leaves the wasm heap.+ */+template <typename T>+inline const T* boundarySpan(uintptr_t ptr, u64 count, const char* what) {+ if (ptr == 0) {+ ES_LOG_ERROR("{}: null buffer pointer; rejected", what);+ return nullptr;+ }+ const u64 bytes = count * static_cast<u64>(sizeof(T));+ if (count != 0 && bytes / count != sizeof(T)) {+ ES_LOG_ERROR("{}: byte size overflows (count {}); rejected", what, count);+ return nullptr;+ }+ const u64 heap = static_cast<u64>(detail::boundaryHeapSize());+ if (static_cast<u64>(ptr) > heap || bytes > heap - static_cast<u64>(ptr)) {+ ES_LOG_ERROR("{}: span [{} + {} bytes] exceeds the wasm heap ({}); rejected",+ what, ptr, bytes, heap);+ return nullptr;+ }+ return reinterpret_cast<const T*>(ptr);+}++/** @brief Mutable variant of boundarySpan, for entry points that WRITE into a JS buffer. */+template <typename T>+inline T* boundarySpanMut(uintptr_t ptr, u64 count, const char* what) {+ return const_cast<T*>(boundarySpan<T>(ptr, count, what));+}++} // namespace esenginediff --git a/src/esengine/bindings/GeometryBindings.cpp b/src/esengine/bindings/GeometryBindings.cppindex 9ac161ee1..fafd61823 100644--- a/src/esengine/bindings/GeometryBindings.cpp+++ b/src/esengine/bindings/GeometryBindings.cpp@@ -3,6 +3,7 @@#include "GeometryBindings.hpp"#include "ActiveContext.hpp"+#include "BoundarySpan.hpp"#include "../renderer/OpenGLHeaders.hpp"#include "../renderer/GfxDevice.hpp"#include "../renderer/CustomGeometry.hpp"@@ -71,8 +72,8 @@ void geometry_init(u32 handle, uintptr_t verticesPtr, u32 vertexCount,return;}- const f32* vertices = reinterpret_cast<const f32*>(verticesPtr);- const i32* layoutData = reinterpret_cast<const i32*>(layoutPtr);+ const i32* layoutData = boundarySpan<i32>(layoutPtr, layoutCount, "geometry_init.layout");+ if (!layoutData) return;static constexpr const char* ATTR_NAMES[] = {"a_attr0", "a_attr1", "a_attr2", "a_attr3",@@ -85,7 +86,12 @@ void geometry_init(u32 handle, uintptr_t verticesPtr, u32 vertexCount,attrs.emplace_back(static_cast<ShaderDataType>(layoutData[i]), ATTR_NAMES[i]);}- geom->init(ctx().require<GfxDevice>(), vertices, vertexCount, VertexLayout(std::move(attrs)), dynamic);+ VertexLayout layout(std::move(attrs));+ const f32* vertices = boundarySpan<f32>(+ verticesPtr, static_cast<u64>(vertexCount) * (layout.getStride() / sizeof(f32)),+ "geometry_init.vertices");+ if (!vertices) return;+ geom->init(ctx().require<GfxDevice>(), vertices, vertexCount, std::move(layout), dynamic);}void geometry_setIndices16(u32 handle, uintptr_t indicesPtr, u32 indexCount) {@@ -94,7 +100,8 @@ void geometry_setIndices16(u32 handle, uintptr_t indicesPtr, u32 indexCount) {auto* geom = g_geometryManager->get(handle);if (!geom) return;- const u16* indices = reinterpret_cast<const u16*>(indicesPtr);+ const u16* indices = boundarySpan<u16>(indicesPtr, indexCount, "geometry_setIndices16");+ if (!indices) return;geom->setIndices(indices, indexCount);}@@ -104,7 +111,8 @@ void geometry_setIndices32(u32 handle, uintptr_t indicesPtr, u32 indexCount) {auto* geom = g_geometryManager->get(handle);if (!geom) return;- const u32* indices = reinterpret_cast<const u32*>(indicesPtr);+ const u32* indices = boundarySpan<u32>(indicesPtr, indexCount, "geometry_setIndices32");+ if (!indices) return;geom->setIndices(indices, indexCount);}@@ -114,7 +122,10 @@ void geometry_updateVertices(u32 handle, uintptr_t verticesPtr, u32 vertexCount,auto* geom = g_geometryManager->get(handle);if (!geom) return;- const f32* vertices = reinterpret_cast<const f32*>(verticesPtr);+ const f32* vertices = boundarySpan<f32>(+ verticesPtr, static_cast<u64>(vertexCount) * (geom->getVertexStride() / sizeof(f32)),+ "geometry_updateVertices");+ if (!vertices) return;geom->updateVertices(vertices, vertexCount, offset);}@@ -139,7 +150,8 @@ void draw_mesh(u32 geometryHandle, u32 shaderHandle, uintptr_t transformPtr) {flushImmediateDrawIfActive();- const f32* transformData = reinterpret_cast<const f32*>(transformPtr);+ const f32* transformData = boundarySpan<f32>(transformPtr, 16, "draw_mesh.transform");+ if (!transformData) return;glm::mat4 transform = glm::make_mat4(transformData);applyMeshPipeline(*g_device, *shader, *geom);@@ -172,7 +184,8 @@ void draw_meshWithUniforms(u32 geometryHandle, u32 shaderHandle, uintptr_t transflushImmediateDrawIfActive();- const f32* transformData = reinterpret_cast<const f32*>(transformPtr);+ const f32* transformData = boundarySpan<f32>(transformPtr, 16, "draw_meshWithUniforms.transform");+ if (!transformData) return;glm::mat4 transform = glm::make_mat4(transformData);applyMeshPipeline(*g_device, *shader, *geom);@@ -187,12 +200,17 @@ void draw_meshWithUniforms(u32 geometryHandle, u32 shaderHandle, uintptr_t trans};static constexpr u32 UNIFORM_NAME_COUNT = sizeof(UNIFORM_NAMES) / sizeof(UNIFORM_NAMES[0]);- const f32* uniforms = reinterpret_cast<const f32*>(uniformsPtr);+ const f32* uniforms = boundarySpan<f32>(uniformsPtr, uniformCount, "draw_meshWithUniforms.uniforms");+ if (uniformCount != 0 && !uniforms) return;u32 idx = 0;- while (idx < uniformCount) {+ // Each record is [type, nameId, payload...]; a truncated record must stop the+ // walk instead of reading past uniformCount.+ while (idx + 2 <= uniformCount) {auto type = static_cast<i32>(uniforms[idx++]);auto nameId = static_cast<i32>(uniforms[idx++]);+ const u32 arity = (type == 10) ? 2u : (type >= 1 && type <= 4 ? static_cast<u32>(type) : 0u);+ if (uniformCount - idx < arity) break;const char* name = (nameId >= 0 && static_cast<u32>(nameId) < UNIFORM_NAME_COUNT)? UNIFORM_NAMES[nameId] : "u_unknown";diff --git a/src/esengine/bindings/ImmediateDrawBindings.cpp b/src/esengine/bindings/ImmediateDrawBindings.cppindex 4d1e37efa..f1f6994d0 100644--- a/src/esengine/bindings/ImmediateDrawBindings.cpp+++ b/src/esengine/bindings/ImmediateDrawBindings.cpp@@ -2,6 +2,7 @@// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team#include "ImmediateDrawBindings.hpp"+#include "BoundarySpan.hpp"#include "ActiveContext.hpp"#include "../renderer/OpenGLHeaders.hpp"#include "../renderer/GfxDevice.hpp"@@ -39,7 +40,8 @@ void draw_begin(uintptr_t matrixPtr) {g_device->setViewport(0, 0, g_viewportWidth, g_viewportHeight);- const f32* matrixData = reinterpret_cast<const f32*>(matrixPtr);+ const f32* matrixData = boundarySpan<f32>(matrixPtr, 16, "draw_begin.matrix");+ if (!matrixData) return;ctx().state().current_view_projection = glm::make_mat4(matrixData);g_immediateDraw->begin(g_currentViewProjection);ctx().state().immediate_draw_active = true;diff --git a/src/esengine/bindings/PhysicsShapes.cpp b/src/esengine/bindings/PhysicsShapes.cppindex 2d01ffb39..0b3517a25 100644--- a/src/esengine/bindings/PhysicsShapes.cpp+++ b/src/esengine/bindings/PhysicsShapes.cpp@@ -1,6 +1,7 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team#include "PhysicsContext.hpp"+#include "BoundarySpan.hpp"extern "C" {@@ -135,7 +136,8 @@ void physics_addPolygonShape(uint32_t entityId, uintptr_t verticesPtr, int verteshapeDef.filter.categoryBits = static_cast<uint64_t>(categoryBits);shapeDef.filter.maskBits = static_cast<uint64_t>(maskBits);- auto* floats = reinterpret_cast<float*>(verticesPtr);+ auto* floats = boundarySpan<float>(verticesPtr, static_cast<u64>(vertexCount) * 2, "physics_addPolygonShape");+ if (!floats) return;b2Vec2 points[B2_MAX_POLYGON_VERTICES];for (int i = 0; i < vertexCount; i++) {points[i] = {floats[i * 2], floats[i * 2 + 1]};@@ -157,9 +159,12 @@ void physics_addChainShape(uint32_t entityId, uintptr_t pointsPtr, int pointCounuint32_t categoryBits, uint32_t maskBits) {auto it = g_ctx.entityToBody.find(entityId);if (it == g_ctx.entityToBody.end()) return;- if (pointCount < 4) return;+ // Chain points are unbounded by Box2D itself; cap at a sane ceiling so a wild+ // count can't allocate gigabytes or walk the heap.+ if (pointCount < 4 || pointCount > 65536) return;- auto* floats = reinterpret_cast<float*>(pointsPtr);+ auto* floats = boundarySpan<float>(pointsPtr, static_cast<u64>(pointCount) * 2, "physics_addChainShape");+ if (!floats) return;std::vector<b2Vec2> points(pointCount);for (int i = 0; i < pointCount; i++) {points[i] = {floats[i * 2], floats[i * 2 + 1]};diff --git a/src/esengine/bindings/RendererBindings.cpp b/src/esengine/bindings/RendererBindings.cppindex aec72c566..f96af43f9 100644--- a/src/esengine/bindings/RendererBindings.cpp+++ b/src/esengine/bindings/RendererBindings.cpp@@ -3,6 +3,7 @@#include "RendererBindings.hpp"#include "ActiveContext.hpp"+#include "BoundarySpan.hpp"#include "../renderer/GfxDevice.hpp"#include "../renderer/RenderFrame.hpp"#include "../renderer/RenderContext.hpp"@@ -69,9 +70,12 @@ void renderer_submitSpineBatch(u32 entity, i32 layer, f32 depth) {if (!g_initialized || !g_renderFrame) return;- auto* vertices = reinterpret_cast<const f32*>(verticesPtr);- auto* indices = reinterpret_cast<const u16*>(indicesPtr);- auto* transform = reinterpret_cast<const f32*>(transformPtr);+ if (vertexCount < 0 || indexCount < 0) return;+ // Spine vertex format is x,y,u,v,r,g,b,a (8 floats per vertex).+ auto* vertices = boundarySpan<f32>(verticesPtr, static_cast<u64>(vertexCount) * 8, "renderer_submitSpineBatch.vertices");+ auto* indices = boundarySpan<u16>(indicesPtr, static_cast<u64>(indexCount), "renderer_submitSpineBatch.indices");+ auto* transform = boundarySpan<f32>(transformPtr, 16, "renderer_submitSpineBatch.transform");+ if (!vertices || !indices || !transform) return;g_renderFrame->submitSpineBatch(vertices, vertexCount, indices, indexCount,textureId, blendMode, transform, Entity::fromRaw(entity), layer, depth);@@ -102,8 +106,10 @@ void renderer_submitSpineBatchByEntity(* glm::mat4_cast(t.worldRotation)* glm::scale(glm::mat4(1.0f), s);- auto* vertices = reinterpret_cast<const f32*>(verticesPtr);- auto* indices = reinterpret_cast<const u16*>(indicesPtr);+ if (vertexCount < 0 || indexCount < 0) return;+ auto* vertices = boundarySpan<f32>(verticesPtr, static_cast<u64>(vertexCount) * 8, "renderer_submitSpineBatchByEntity.vertices");+ auto* indices = boundarySpan<u16>(indicesPtr, static_cast<u64>(indexCount), "renderer_submitSpineBatchByEntity.indices");+ if (!vertices || !indices) return;g_renderFrame->submitSpineBatch(vertices, vertexCount, indices, indexCount,textureId, blendMode, &model[0][0], ent, layer, depth);@@ -120,9 +126,12 @@ void renderer_submitTextBatch(u32 entity, i32 layer, f32 depth, i32 sdf) {if (!g_initialized || !g_renderFrame) return;- auto* vertices = reinterpret_cast<const f32*>(verticesPtr);- auto* indices = reinterpret_cast<const u16*>(indicesPtr);- auto* transform = reinterpret_cast<const f32*>(transformPtr);+ if (vertexCount < 0 || indexCount < 0) return;+ // Text vertex format is x,y,u,v,r,g,b,a (8 floats per vertex).+ auto* vertices = boundarySpan<f32>(verticesPtr, static_cast<u64>(vertexCount) * 8, "renderer_submitTextBatch.vertices");+ auto* indices = boundarySpan<u16>(indicesPtr, static_cast<u64>(indexCount), "renderer_submitTextBatch.indices");+ auto* transform = boundarySpan<f32>(transformPtr, 16, "renderer_submitTextBatch.transform");+ if (!vertices || !indices || !transform) return;g_renderFrame->submitTextBatch(vertices, vertexCount, indices, indexCount,textureId, transform, Entity::fromRaw(entity), layer, depth, sdf != 0);@@ -155,9 +164,10 @@ void mesh2d_setGeometry(ecs::Registry& registry, u32 entity,return;}- const f32* posUv = reinterpret_cast<const f32*>(posUvPtr);- const u32* colors = reinterpret_cast<const u32*>(colorsPtr);- const u32* indices = reinterpret_cast<const u32*>(indicesPtr);+ const f32* posUv = boundarySpan<f32>(posUvPtr, static_cast<u64>(vertexCount) * 4, "mesh2d_setGeometry.posUv");+ const u32* colors = colorsPtr ? boundarySpan<u32>(colorsPtr, vertexCount, "mesh2d_setGeometry.colors") : nullptr;+ const u32* indices = boundarySpan<u32>(indicesPtr, indexCount, "mesh2d_setGeometry.indices");+ if (!posUv || !indices || (colorsPtr && !colors)) return;for (u32 i = 0; i < indexCount; ++i) {if (indices[i] >= vertexCount) {@@ -174,7 +184,7 @@ void mesh2d_setGeometry(ecs::Registry& registry, u32 entity,auto& out = mesh->vertices[v];out.position = { posUv[v * 4 + 0], posUv[v * 4 + 1] };out.uv = { posUv[v * 4 + 2], posUv[v * 4 + 3] };- out.color = colorsPtr ? colors[v] : 0xFFFFFFFFu;+ out.color = colors ? colors[v] : 0xFFFFFFFFu;mn = glm::min(mn, out.position);mx = glm::max(mx, out.position);}@@ -265,7 +275,8 @@ void renderFrameWithMatrix(ecs::Registry& registry, i32 viewportWidth, i32 viewpg_device->setViewport(0, 0, static_cast<u32>(viewportWidth), static_cast<u32>(viewportHeight));- const f32* matrixData = reinterpret_cast<const f32*>(matrixPtr);+ const f32* matrixData = boundarySpan<f32>(matrixPtr, 16, "renderFrameWithMatrix.matrix");+ if (!matrixData) return;glm::mat4 viewProjection = glm::make_mat4(matrixData);const auto& cc = ctx().state().clear_color;@@ -303,7 +314,8 @@ void renderer_begin(uintptr_t matrixPtr, u32 targetHandle, i32 clearFlags,i32 clearX, i32 clearY, u32 clearW, u32 clearH) {if (!g_renderFrame) return;- const f32* matrixData = reinterpret_cast<const f32*>(matrixPtr);+ const f32* matrixData = boundarySpan<f32>(matrixPtr, 16, "renderer_begin.matrix");+ if (!matrixData) return;glm::mat4 viewProjection = glm::make_mat4(matrixData);g_renderFrame->begin(viewProjection, targetHandle,@@ -641,7 +653,9 @@ u32 registry_getGeneration(ecs::Registry& registry, u32 entity) {}void registry_batchSyncPhysicsTransforms(ecs::Registry& registry, uintptr_t bufferPtr, int count, float ppu) {- const float* buffer = reinterpret_cast<const float*>(bufferPtr);+ if (count < 0) return;+ const float* buffer = boundarySpan<f32>(bufferPtr, static_cast<u64>(count) * 4, "registry_batchSyncPhysicsTransforms");+ if (!buffer) return;for (int i = 0; i < count; i++) {const int offset = i * 4;uint32_t entityId;diff --git a/src/esengine/bindings/ResourceManagerBindings.cpp b/src/esengine/bindings/ResourceManagerBindings.cppindex 71fa7d71b..cb3cd7c28 100644--- a/src/esengine/bindings/ResourceManagerBindings.cpp+++ b/src/esengine/bindings/ResourceManagerBindings.cpp@@ -2,6 +2,7 @@// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team#include "ResourceManagerBindings.hpp"+#include "BoundarySpan.hpp"#include "../resource/TextureMetadata.hpp"#include "../text/BitmapFont.hpp"#include "../core/Types.hpp"@@ -12,7 +13,8 @@ namespace esengine {u32 rm_createTexture(resource::ResourceManager& rm, u32 width, u32 height,uintptr_t pixelsPtr, u32 pixelsLen, i32 format, bool flipY) {- const u8* pixels = reinterpret_cast<const u8*>(pixelsPtr);+ const u8* pixels = boundarySpan<u8>(pixelsPtr, pixelsLen, "rm_createTexture");+ if (!pixels) return 0;ConstSpan<u8> pixelSpan(pixels, pixelsLen);TextureFormat texFormat = TextureFormat::RGBA8;@@ -26,7 +28,8 @@ u32 rm_createTexture(resource::ResourceManager& rm, u32 width, u32 height,u32 rm_createTextureEx(resource::ResourceManager& rm, u32 width, u32 height,uintptr_t pixelsPtr, u32 pixelsLen, i32 format, bool flipY,i32 filterMode, i32 wrapMode) {- const u8* pixels = reinterpret_cast<const u8*>(pixelsPtr);+ const u8* pixels = pixelsPtr ? boundarySpan<u8>(pixelsPtr, pixelsLen, "rm_createTextureEx") : nullptr;+ if (pixelsPtr && !pixels) return 0;TextureFormat texFormat = TextureFormat::RGBA8;if (format == 0) texFormat = TextureFormat::RGB8;@@ -55,8 +58,13 @@ u32 rm_createTextureEx(resource::ResourceManager& rm, u32 width, u32 height,auto* texture = rm.getTexture(handle);if (texture && pixels) {- u32 dataSize = width * height * (texFormat == TextureFormat::RGBA8 ? 4 : 3);- texture->setDataRaw(pixels, dataSize, flipY);+ const u64 required = static_cast<u64>(width) * height * (texFormat == TextureFormat::RGBA8 ? 4 : 3);+ if (pixelsLen < required) {+ ES_LOG_ERROR("rm_createTextureEx: pixel buffer {} < required {}; upload skipped",+ pixelsLen, required);+ } else {+ texture->setDataRaw(pixels, static_cast<u32>(required), flipY);+ }}return handle.id();@@ -197,7 +205,8 @@ void rm_updateTextureSubregion(resource::ResourceManager& rm, u32 handleId,if (!tex) return;// Sub-region pixels must already match the texture's format (RGBA8 atlas);// updateSubRegion bounds-checks the rect + buffer size internally.- const u8* pixels = reinterpret_cast<const u8*>(pixelsPtr);+ const u8* pixels = boundarySpan<u8>(pixelsPtr, pixelsLen, "rm_updateTextureSubregion");+ if (!pixels) return;tex->updateSubRegion(x, y, width, height, pixels, pixelsLen, /*flipY=*/false);}diff --git a/src/esengine/bindings/TilemapBindings.cpp b/src/esengine/bindings/TilemapBindings.cppindex 77ee2d2d3..f4d5127cd 100644--- a/src/esengine/bindings/TilemapBindings.cpp+++ b/src/esengine/bindings/TilemapBindings.cpp@@ -3,6 +3,7 @@#ifdef ES_ENABLE_TILEMAP#include "ActiveContext.hpp"+#include "BoundarySpan.hpp"#include "../tilemap/TilemapSystem.hpp"#include "../tilemap/TiledMapLoader.hpp"#include "../renderer/RenderContext.hpp"@@ -81,7 +82,8 @@ void tilemap_fillRect(u32 entity, i32 x, i32 y,void tilemap_setTiles(u32 entity, uintptr_t tilesPtr, u32 count) {auto e = Entity::fromRaw(entity);if (e == INVALID_ENTITY || !getTilemapSystem().hasLayer(e)) return;- const auto* tiles = reinterpret_cast<const u16*>(tilesPtr);+ const auto* tiles = boundarySpan<u16>(tilesPtr, count, "tilemap_setTiles");+ if (!tiles) return;getTilemapSystem().setTiles(e, tiles, count);}@@ -90,7 +92,8 @@ void tilemap_setTiles(u32 entity, uintptr_t tilesPtr, u32 count) {void tilemap_setTilesets(u32 entity, uintptr_t dataPtr, u32 count) {auto e = Entity::fromRaw(entity);if (e == INVALID_ENTITY || !getTilemapSystem().hasLayer(e)) return;- const auto* d = reinterpret_cast<const u32*>(dataPtr);+ const auto* d = count ? boundarySpan<u32>(dataPtr, static_cast<u64>(count) * 3, "tilemap_setTilesets") : nullptr;+ if (count && !d) return;std::vector<tilemap::TilesetSlot> slots;slots.reserve(count);for (u32 i = 0; i < count; ++i) {@@ -292,7 +295,8 @@ bool tilemap_importChunks(u32 entity, const std::string& encoded) {// --- Tiled map loader bindings ---u32 tiled_loadMap(uintptr_t dataPtr, u32 dataSize) {- const auto* data = reinterpret_cast<const char*>(dataPtr);+ const auto* data = boundarySpan<char>(dataPtr, dataSize, "tiled_loadMap");+ if (!data) return 0;return getTiledLoader().loadFromMemory(data, dataSize);}@@ -310,7 +314,8 @@ std::string tiled_getExternalTilesetSource(u32 handle, u32 index) {bool tiled_loadExternalTileset(u32 handle, u32 index,uintptr_t dataPtr, u32 dataSize) {- const auto* data = reinterpret_cast<const char*>(dataPtr);+ const auto* data = boundarySpan<char>(dataPtr, dataSize, "tiled_loadExternalTileset");+ if (!data) return false;return getTiledLoader().loadExternalTileset(handle, index, data, dataSize);}@@ -374,7 +379,8 @@ u32 tiled_getLayerTiles(u32 handle, u32 index,const auto& tiles = map->layers[index].tiles;u32 count = std::min(static_cast<u32>(tiles.size()), maxCount);- auto* out = reinterpret_cast<u16*>(outPtr);+ auto* out = boundarySpanMut<u16>(outPtr, count, "tiled_getLayerTiles");+ if (!out) return 0;std::memcpy(out, tiles.data(), count * sizeof(u16));return count;}@@ -515,7 +521,8 @@ u32 tiled_getObjectVertices(u32 handle, u32 groupIndex, u32 objIndex,if (objIndex >= grp.objects.size()) return 0;const auto& verts = grp.objects[objIndex].vertices;u32 count = std::min(static_cast<u32>(verts.size()), maxFloats);- auto* out = reinterpret_cast<f32*>(outPtr);+ auto* out = boundarySpanMut<f32>(outPtr, count, "tiled_getObjectVertices");+ if (!out) return 0;std::memcpy(out, verts.data(), count * sizeof(f32));return count;}@@ -554,7 +561,8 @@ void tilemap_setChunkTiles(u32 entity, i32 chunkX, i32 chunkY,uintptr_t tilesPtr, u32 width, u32 height) {auto e = Entity::fromRaw(entity);if (e == INVALID_ENTITY || !getTilemapSystem().hasLayer(e)) return;- const auto* tiles = reinterpret_cast<const u16*>(tilesPtr);+ const auto* tiles = boundarySpan<u16>(tilesPtr, static_cast<u64>(width) * height, "tilemap_setChunkTiles");+ if (!tiles) return;getTilemapSystem().setChunkTiles(e, chunkX, chunkY, tiles, width, height);}@@ -615,7 +623,8 @@ u32 tiled_getLayerChunkTiles(u32 handle, u32 layerIndex, u32 chunkIndex,if (chunkIndex >= chunks.size()) return 0;const auto& tiles = chunks[chunkIndex].tiles;u32 count = std::min(static_cast<u32>(tiles.size()), maxCount);- auto* out = reinterpret_cast<u16*>(outPtr);+ auto* out = boundarySpanMut<u16>(outPtr, count, "tiled_getLayerChunkTiles");+ if (!out) return 0;std::memcpy(out, tiles.data(), count * sizeof(u16));return count;}@@ -624,7 +633,8 @@ void tilemap_setTileAnimation(u32 entity, u32 tileId,uintptr_t framesPtr, u32 frameCount) {auto e = Entity::fromRaw(entity);if (e == INVALID_ENTITY || !getTilemapSystem().hasLayer(e)) return;- const auto* data = reinterpret_cast<const u32*>(framesPtr);+ const auto* data = boundarySpan<u32>(framesPtr, static_cast<u64>(frameCount) * 2, "tilemap_setTileAnimation");+ if (!data) return;std::vector<tilemap::AnimFrame> frames(frameCount);for (u32 i = 0; i < frameCount; i++) {frames[i].tile_id = static_cast<u16>(data[i * 2]);diff --git a/src/esengine/bindings/WebSDKEntry.cpp b/src/esengine/bindings/WebSDKEntry.cppindex d6b709430..267335518 100644--- a/src/esengine/bindings/WebSDKEntry.cpp+++ b/src/esengine/bindings/WebSDKEntry.cpp@@ -20,6 +20,7 @@#include "ActiveContext.hpp"#include "ResourceManagerBindings.hpp"#include "RendererBindings.hpp"+#include "BoundarySpan.hpp"#include "ImmediateDrawBindings.hpp"#include "GeometryBindings.hpp"#ifdef ES_ENABLE_POSTPROCESS@@ -293,8 +294,10 @@ resource::ResourceManager* getResourceManager() {// bitmap to a signed distance field. Both buffers are caller-allocated in WASM// linear memory (TS passes HEAPU8 pointers); `alpha` and `out` are width*height.void web_sdfFromAlpha(uintptr_t alphaPtr, uintptr_t outPtr, u32 width, u32 height, f32 spread) {- const u8* alpha = reinterpret_cast<const u8*>(alphaPtr);- u8* out = reinterpret_cast<u8*>(outPtr);+ const u64 pixels = static_cast<u64>(width) * height;+ const u8* alpha = boundarySpan<u8>(alphaPtr, pixels, "sdfFromAlpha.alpha");+ u8* out = boundarySpanMut<u8>(outPtr, pixels, "sdfFromAlpha.out");+ if (!alpha || !out) return;text::sdfFromAlpha(alpha, out, width, height, spread);}diff --git a/src/esengine/ecs/Registry.hpp b/src/esengine/ecs/Registry.hppindex 4edfe7ec4..7c8c8ffca 100644--- a/src/esengine/ecs/Registry.hpp+++ b/src/esengine/ecs/Registry.hpp@@ -382,6 +382,8 @@ public:if (pool.contains(entity)) {return pool.get(entity);}+ // Release-safe: see emplace() — invalid entity -> OOB write on the mask.+ ES_VERIFY(valid(entity), { static T fallback{}; fallback = T{}; return fallback; });auto& result = pool.emplace(entity, std::forward<Args>(args)...);component_masks_[entity.index()].set(componentTypeId<T>());return result;diff --git a/src/esengine/renderer/CustomGeometry.hpp b/src/esengine/renderer/CustomGeometry.hppindex 542b63555..96ab6a43e 100644--- a/src/esengine/renderer/CustomGeometry.hpp+++ b/src/esengine/renderer/CustomGeometry.hpp@@ -93,6 +93,9 @@ public:*/u32 getVertexCount() const { return vertexCount_; }+ /** @brief Byte stride of one vertex (0 before init) — boundary-validation source. */+ u32 getVertexStride() const { return stride_; }+/*** @brief Checks if geometry uses indices*/diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txtindex 2c1928361..e20855c6a 100644--- a/tests/CMakeLists.txt+++ b/tests/CMakeLists.txt@@ -111,6 +111,16 @@ add_executable(test_buffer_devicetarget_include_directories(test_buffer_device PRIVATE ${CMAKE_SOURCE_DIR}/src)add_test(NAME test_buffer_device COMMAND test_buffer_device)+# Boundary-span validation (RC3): JS-supplied pointer+length pairs are null-,+# overflow-, and heap-range-checked ALWAYS ON. Header-only + Log.cpp; under+# emscripten the heap-range cases exercise the real linear-memory bound.+add_executable(test_boundary_span+ bindings/test_boundary_span.cpp+ ${CMAKE_SOURCE_DIR}/src/esengine/core/Log.cpp+)+target_include_directories(test_boundary_span PRIVATE ${CMAKE_SOURCE_DIR}/src)+add_test(NAME test_boundary_span COMMAND test_boundary_span)+# Unified submission face (render-pipeline unification): BatchBuilder is the single# DrawCommand producer for every stream. Compiles BatchBuilder/DrawList/# TransientBufferPool against the MockGfxDevice and asserts per-stream baseVertexdiff --git a/tests/bindings/test_boundary_span.cpp b/tests/bindings/test_boundary_span.cppnew file mode 100644index 000000000..4f8b90fee--- /dev/null+++ b/tests/bindings/test_boundary_span.cpp@@ -0,0 +1,66 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+// Boundary-span validation (RC3): every JS-supplied pointer+length pair crosses+// through boundarySpan, which must reject null pointers, overflowing byte sizes,+// and spans that leave the wasm heap — ALWAYS ON, independent of ES_ASSERT.+// Built with emscripten, so the heap-range checks here exercise the real+// emscripten_get_heap_size() bound.+#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN+#include <doctest.h>++#include "esengine/bindings/BoundarySpan.hpp"++#include <cstdint>+#include <vector>++using namespace esengine;++TEST_CASE("valid span inside the heap passes through typed") {+ std::vector<f32> buf(64, 1.5f);+ auto ptr = reinterpret_cast<uintptr_t>(buf.data());++ const f32* span = boundarySpan<f32>(ptr, 64, "test.valid");+ REQUIRE(span != nullptr);+ CHECK(span == buf.data());+ CHECK(span[63] == 1.5f);+}++TEST_CASE("zero count with a valid pointer is allowed") {+ std::vector<u8> buf(4);+ CHECK(boundarySpan<u8>(reinterpret_cast<uintptr_t>(buf.data()), 0, "test.zero") != nullptr);+}++TEST_CASE("null pointer is rejected") {+ CHECK(boundarySpan<f32>(0, 16, "test.null") == nullptr);+ CHECK(boundarySpanMut<u16>(0, 1, "test.nullMut") == nullptr);+}++TEST_CASE("byte-size overflow is rejected") {+ std::vector<u8> buf(4);+ auto ptr = reinterpret_cast<uintptr_t>(buf.data());+ // count * sizeof(u32) wraps u64.+ CHECK(boundarySpan<u32>(ptr, UINT64_MAX / 2, "test.overflow") == nullptr);+}++TEST_CASE("span exceeding the wasm heap is rejected") {+#ifdef __EMSCRIPTEN__+ const u64 heap = emscripten_get_heap_size();+ // A pointer near the end of linear memory with a span that runs past it.+ CHECK(boundarySpan<f32>(static_cast<uintptr_t>(heap - 8), 100, "test.pastEnd") == nullptr);+ // A pointer entirely beyond the heap.+ CHECK(boundarySpan<u8>(static_cast<uintptr_t>(heap + 1024), 1, "test.beyond") == nullptr);+#else+ // Native builds have no linear-memory bound; null/overflow checks still hold.+ CHECK(true);+#endif+}++TEST_CASE("mutable variant validates identically and allows writes") {+ std::vector<u16> buf(8, 0);+ auto ptr = reinterpret_cast<uintptr_t>(buf.data());++ u16* span = boundarySpanMut<u16>(ptr, 8, "test.mut");+ REQUIRE(span != nullptr);+ span[7] = 42;+ CHECK(buf[7] == 42);+}