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: harden release-stripped boundaries against OOB/abort/underflow

esengine76f641eff7a0
diff --git a/src/esengine/core/Log.hpp b/src/esengine/core/Log.hpp
index e6c7b8d40..2ec6fb7b2 100644
--- a/src/esengine/core/Log.hpp
+++ b/src/esengine/core/Log.hpp
@@ -20,6 +20,7 @@
#include "Types.hpp"
// Standard library
+#include <charconv>
#include <functional>
#include <iomanip>
#include <iostream>
@@ -241,8 +242,16 @@ private:
if (!fmt.empty() && fmt.back() == 'f') {
auto dotPos = fmt.find('.');
if (dotPos != std::string::npos) {
- int precision = std::stoi(fmt.substr(dotPos + 1, fmt.size() - dotPos - 2));
- oss << std::fixed << std::setprecision(precision);
+ // Parse precision digits between '.' and the trailing 'f'.
+ // from_chars never throws; std::stoi would abort the whole
+ // module under -fno-exceptions on malformed specs like "{:.f}".
+ int precision = 0;
+ const char* begin = fmt.data() + dotPos + 1;
+ const char* end = fmt.data() + fmt.size() - 1; // exclude trailing 'f'
+ auto res = std::from_chars(begin, end, precision);
+ if (res.ptr != begin) {
+ oss << std::fixed << std::setprecision(precision);
+ }
}
}
}
diff --git a/src/esengine/ecs/Registry.hpp b/src/esengine/ecs/Registry.hpp
index 53f7b9d55..91aed9941 100644
--- a/src/esengine/ecs/Registry.hpp
+++ b/src/esengine/ecs/Registry.hpp
@@ -139,6 +139,12 @@ public:
const u32 idx = entity.index();
+ // Mark invalid up-front so a re-entrant destroy(entity) from an onDestroy
+ // callback short-circuits at valid() above. Otherwise the teardown below
+ // runs twice: entity_count_ underflows and idx is pushed onto recycled_
+ // twice, later aliasing two distinct entities to the same index.
+ entityValid_[idx] = false;
+
++firing_destroy_;
for (usize i = 0; i < on_destroy_entries_.size(); ++i) {
if (on_destroy_entries_[i].dead) continue;
@@ -159,7 +165,6 @@ public:
});
component_masks_[idx].reset();
- entityValid_[idx] = false;
--entity_count_;
recycled_.push(idx);
@@ -302,15 +307,23 @@ public:
template<typename T>
T& get(Entity entity) {
auto* pool = getPool<T>();
- ES_ASSERT(pool != nullptr, "Component pool does not exist");
- return pool->get(entity);
+ if (!pool) {
+ ES_LOG_ERROR("Registry::get: component pool does not exist (returning fallback)");
+ static T fallback{};
+ return fallback;
+ }
+ return pool->get(entity); // SparseSet::get is itself release-safe
}
/** @copydoc get() */
template<typename T>
const T& get(Entity entity) const {
auto* pool = getPool<T>();
- ES_ASSERT(pool != nullptr, "Component pool does not exist");
+ if (!pool) {
+ ES_LOG_ERROR("Registry::get: component pool does not exist (returning fallback)");
+ static const T fallback{};
+ return fallback;
+ }
return pool->get(entity);
}
diff --git a/src/esengine/ecs/SparseSet.hpp b/src/esengine/ecs/SparseSet.hpp
index c740d80a8..57cfa0274 100644
--- a/src/esengine/ecs/SparseSet.hpp
+++ b/src/esengine/ecs/SparseSet.hpp
@@ -191,14 +191,28 @@ public:
* @note Asserts if the entity doesn't have a component
*/
T& get(Entity entity) {
- ES_ASSERT(contains(entity), "Entity does not have component");
- return components_[denseIndexOf(entity)];
+ // Release-safe bounds check (ES_ASSERT is stripped in release builds).
+ // On a miss, log and return a fallback rather than read
+ // components_[INVALID_INDEX] out of bounds. Callers that have already
+ // proven membership should use getUnchecked() for the no-branch path.
+ u32 di = denseIndexOf(entity);
+ if (di == INVALID_INDEX || dense_[di] != entity) {
+ ES_LOG_ERROR("SparseSet::get on an entity without this component (returning fallback)");
+ static T fallback{};
+ return fallback;
+ }
+ return components_[di];
}
/** @copydoc get() */
const T& get(Entity entity) const {
- ES_ASSERT(contains(entity), "Entity does not have component");
- return components_[denseIndexOf(entity)];
+ u32 di = denseIndexOf(entity);
+ if (di == INVALID_INDEX || dense_[di] != entity) {
+ ES_LOG_ERROR("SparseSet::get on an entity without this component (returning fallback)");
+ static const T fallback{};
+ return fallback;
+ }
+ return components_[di];
}
T& getUnchecked(Entity entity) {
diff --git a/src/esengine/renderer/Texture.cpp b/src/esengine/renderer/Texture.cpp
index bcb3c770c..4295b9163 100644
--- a/src/esengine/renderer/Texture.cpp
+++ b/src/esengine/renderer/Texture.cpp
@@ -164,9 +164,15 @@ void Texture::setData(const std::vector<u8>& pixels) {
}
void Texture::setDataRaw(const void* data, u32 sizeBytes, bool flipY) {
- [[maybe_unused]] u32 bpp = bytesPerPixel(format_);
- ES_ASSERT(sizeBytes == width_ * height_ * bpp, "Data size mismatch");
- (void)sizeBytes;
+ // Always-on size guard (independent of ES_ASSERT, which is stripped in release).
+ // texSubImage2D below reads width_*height_*bpp bytes from `data`; a smaller
+ // buffer would cause an out-of-bounds read of WASM linear memory.
+ u32 expectedSize = width_ * height_ * bytesPerPixel(format_);
+ if (sizeBytes < expectedSize) {
+ ES_LOG_ERROR("Texture::setDataRaw: data size {} < required {} for {}x{}; skipping upload to avoid OOB read",
+ sizeBytes, expectedSize, width_, height_);
+ return;
+ }
if (flipY) device_->setUnpackFlipY(true);
device_->texSubImage2D(textureId_, 0, 0, width_, height_, toGfxPixelFormat(format_), data);
diff --git a/src/esengine/text/BitmapFont.cpp b/src/esengine/text/BitmapFont.cpp
index 5d387c9cd..8920a194d 100644
--- a/src/esengine/text/BitmapFont.cpp
+++ b/src/esengine/text/BitmapFont.cpp
@@ -130,6 +130,14 @@ void BitmapFont::createLabelAtlas(resource::TextureHandle texture,
line_height_ = static_cast<f32>(charHeight);
base_ = line_height_;
+ // Guard against divide-by-zero (cols below, and `% cols` in the loop).
+ // ES_ASSERT is stripped in release, so these must be runtime checks.
+ if (charWidth == 0 || charHeight == 0 || texWidth < charWidth) {
+ ES_LOG_ERROR("BitmapFont::createLabelAtlas: invalid dimensions (char {}x{}, tex {}x{}); aborting atlas build",
+ charWidth, charHeight, texWidth, texHeight);
+ return;
+ }
+
u32 cols = texWidth / charWidth;
u32 glyphIndex = 0;
diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt
index 84b5801d3..5a8af6ef4 100644
--- a/tests/CMakeLists.txt
+++ b/tests/CMakeLists.txt
@@ -102,3 +102,26 @@ add_executable(test_compressed_format
)
target_include_directories(test_compressed_format PRIVATE ${CMAKE_SOURCE_DIR}/src)
add_test(NAME test_compressed_format COMMAND test_compressed_format)
+
+# Log format-string precision parsing (Audit A1). Only needs Log.cpp.
+# Should be compiled with exceptions OFF to mirror the engine's release config:
+# proves malformed float specs like "{:.f}" no longer abort (the old std::stoi
+# path threw -> abort under -fno-exceptions).
+add_executable(test_log_format
+ core/test_log_format.cpp
+ ${CMAKE_SOURCE_DIR}/src/esengine/core/Log.cpp
+)
+target_include_directories(test_log_format PRIVATE ${CMAKE_SOURCE_DIR}/src)
+target_compile_options(test_log_format PRIVATE -fno-exceptions)
+add_test(NAME test_log_format COMMAND test_log_format)
+
+# Registry/SparseSet release-safety (Audit A6 + A7). Header-only against
+# Registry.hpp + Log.cpp (no esengine link). MUST stay free of -DES_DEBUG so
+# ES_ASSERT is stripped, matching the release config where the OOB read
+# (get on a non-member) and entity_count underflow (re-entrant destroy) appear.
+add_executable(test_registry_safety
+ ecs/test_registry_safety.cpp
+ ${CMAKE_SOURCE_DIR}/src/esengine/core/Log.cpp
+)
+target_include_directories(test_registry_safety PRIVATE ${CMAKE_SOURCE_DIR}/src)
+add_test(NAME test_registry_safety COMMAND test_registry_safety)
diff --git a/tests/core/test_log_format.cpp b/tests/core/test_log_format.cpp
new file mode 100644
index 000000000..ebf3b5e73
--- /dev/null
+++ b/tests/core/test_log_format.cpp
@@ -0,0 +1,31 @@
+// Native harness for Log format-string precision parsing (Audit A1).
+//
+// Old code parsed float precision with std::stoi(substr(...)), which THROWS on
+// malformed specs like "{:.f}" (empty precision) — and under -fno-exceptions
+// (the engine's release config) a throw aborts the entire module. The fix uses
+// std::from_chars, which never throws. Compile this with -fno-exceptions to
+// reproduce the original abort and prove the fix.
+//
+// clang++ -std=c++20 -fno-exceptions -I src \
+// tests/core/test_log_format.cpp src/esengine/core/Log.cpp -o /tmp/test_log
+
+#include "esengine/core/Log.hpp"
+
+#include <cstdio>
+
+int main() {
+ using esengine::Log;
+
+ // The dangerous one: empty precision segment. Old code: stoi("") -> abort.
+ Log::info("empty precision: {:.f}", 1.0f);
+ // Non-numeric precision. Old code: stoi("x") -> abort.
+ Log::info("non-numeric precision: {:.xf}", 2.0f);
+ // Well-formed cases must still work.
+ Log::info("normal precision: {:.2f}", 3.14159f);
+ Log::info("no dot: {:f}", 5.0f);
+ Log::info("plain value: {}", 42);
+
+ // Reaching here means none of the malformed specs aborted.
+ std::printf("\nA1 OK: malformed float precision specs did not abort\n");
+ return 0;
+}
diff --git a/tests/ecs/test_registry_safety.cpp b/tests/ecs/test_registry_safety.cpp
new file mode 100644
index 000000000..af44c34db
--- /dev/null
+++ b/tests/ecs/test_registry_safety.cpp
@@ -0,0 +1,77 @@
+// Native harness for Registry/SparseSet release-safety (Audit A6 + A7).
+//
+// Header-only against Registry.hpp (no esengine link), runs on any C++20 toolchain.
+// IMPORTANT: compiled WITHOUT -DES_DEBUG, so ES_ASSERT expands to ((void)0) —
+// exactly the release config where these bugs bite. Under the old code:
+// A6: get<T> on a non-member entity indexed components_[INVALID_INDEX] (OOB read).
+// A7: a re-entrant destroy(entity) from an onDestroy callback ran teardown twice,
+// underflowing entity_count_ and double-recycling the index.
+//
+// clang++ -std=c++20 -I src tests/ecs/test_registry_safety.cpp \
+// src/esengine/core/Log.cpp -o /tmp/test_reg && /tmp/test_reg
+
+#include "esengine/ecs/Registry.hpp"
+
+#include <cstdio>
+
+using esengine::Entity;
+using esengine::ecs::Registry;
+
+namespace {
+struct Pos { float x = 1.0f; float y = 2.0f; }; // fallback{} has x=1, y=2
+struct Vel { float dx = 0.0f; };
+}
+
+static int g_failures = 0;
+#define CHECK(cond, msg) \
+ do { \
+ if (!(cond)) { std::printf("FAIL: %s\n", msg); ++g_failures; } \
+ else { std::printf("ok: %s\n", msg); } \
+ } while (0)
+
+int main() {
+ // --- A6: get<T> on an entity without the component returns fallback (no OOB) ---
+ {
+ Registry r;
+ Entity e = r.create();
+ r.emplace<Pos>(e, Pos{10.0f, 20.0f});
+
+ CHECK(r.get<Pos>(e).x == 10.0f, "get returns the real component when present");
+
+ // Pool exists, but this entity is not a member -> SparseSet::get fallback.
+ Entity other = r.create();
+ Pos& p = r.get<Pos>(other);
+ CHECK(p.x == 1.0f && p.y == 2.0f, "get<Pos> on non-member returns fallback defaults (no OOB)");
+
+ // Pool does not exist at all -> Registry::get fallback.
+ Vel& v = r.get<Vel>(e);
+ CHECK(v.dx == 0.0f, "get<Vel> with no Vel pool returns fallback (no OOB)");
+ }
+
+ // --- A7: re-entrant destroy(entity) from onDestroy must not double-teardown ---
+ {
+ Registry r;
+ Entity e = r.create();
+ int calls = 0;
+ r.onDestroy([&](Entity ent) {
+ if (calls++ == 0) r.destroy(ent); // re-entrant destroy of the SAME entity
+ });
+ CHECK(r.entityCount() == 1u, "one live entity before destroy");
+
+ r.destroy(e);
+ CHECK(r.entityCount() == 0u, "entity_count is 0 after re-entrant destroy (no underflow)");
+
+ // Old bug: idx pushed onto recycled_ twice -> two creates alias one index.
+ Entity a = r.create();
+ Entity b = r.create();
+ CHECK(a.index() != b.index(), "indices not aliased after re-entrant destroy (no double-recycle)");
+ CHECK(r.valid(a) && r.valid(b), "both recreated entities are valid");
+ }
+
+ if (g_failures == 0) {
+ std::printf("\nALL ECS SAFETY TESTS PASSED\n");
+ return 0;
+ }
+ std::printf("\n%d FAILURE(S)\n", g_failures);
+ return 1;
+}
diff --git a/tests/renderer/test_texture_fb.cpp b/tests/renderer/test_texture_fb.cpp
index 7c9aa8fe4..f0a32e53a 100644
--- a/tests/renderer/test_texture_fb.cpp
+++ b/tests/renderer/test_texture_fb.cpp
@@ -50,6 +50,23 @@ int main() {
CHECK(d.texSubImage2DCalls == 1, "pixel upload routes through device.texSubImage2D");
}
+ // --- A2 regression: setDataRaw rejects undersized buffer (no OOB upload) ---
+ // Audit A2: ES_ASSERT is stripped in release, so an undersized buffer used to
+ // reach texSubImage2D and read past its end. Guard must hold without asserts.
+ {
+ MockGfxDevice d;
+ TextureSpecification spec;
+ spec.width = 4; spec.height = 4; spec.format = TextureFormat::RGBA8; // needs 4*4*4 = 64 bytes
+ auto tex = Texture::create(d, spec);
+ const int before = d.texSubImage2DCalls;
+ std::vector<u8> tooSmall(16, 0xAB); // 16 < 64
+ tex->setDataRaw(tooSmall.data(), static_cast<u32>(tooSmall.size()));
+ CHECK(d.texSubImage2DCalls == before, "setDataRaw skips upload for undersized buffer (no OOB read)");
+ std::vector<u8> exact(64, 0xAB);
+ tex->setDataRaw(exact.data(), static_cast<u32>(exact.size()));
+ CHECK(d.texSubImage2DCalls == before + 1, "setDataRaw uploads when size is sufficient");
+ }
+
// --- Framebuffer: color + depth-stencil ---
{
MockGfxDevice d;
diff --git a/tests/text/test_bitmap_font.cpp b/tests/text/test_bitmap_font.cpp
new file mode 100644
index 000000000..dd651a021
--- /dev/null
+++ b/tests/text/test_bitmap_font.cpp
@@ -0,0 +1,35 @@
+// Native harness for BitmapFont::createLabelAtlas degenerate dimensions (Audit A5).
+//
+// createLabelAtlas computed `cols = texWidth / charWidth` and later `% cols`.
+// With charWidth==0 (or texWidth<charWidth making cols==0) this is an integer
+// divide-by-zero -> WASM trap / SIGFPE. ES_ASSERT is stripped in release, so the
+// guard must be a runtime check. This harness drives degenerate dims and proves
+// they no longer crash.
+//
+// Note: native ARM returns 0 on integer divide-by-zero (no trap), so this only
+// exercises the guard's logic; the real trap is on the WASM target, where
+// i32.rem_u/div_u by zero is a spec-mandated trap. Not wired into CMake because
+// the BitmapFont TU references ResourceManager; run it standalone:
+// clang++ -std=c++20 -I src -I third_party/glm -Wl,-undefined,dynamic_lookup \
+// tests/text/test_bitmap_font.cpp src/esengine/text/BitmapFont.cpp \
+// src/esengine/core/Log.cpp -o /tmp/test_bf && /tmp/test_bf
+
+#include "esengine/text/BitmapFont.hpp"
+
+#include <cstdio>
+
+int main() {
+ using esengine::text::BitmapFont;
+ esengine::resource::TextureHandle tex{}; // invalid handle is fine; only stored
+
+ BitmapFont font;
+ // charWidth==0 / charHeight==0: would divide by zero on `texWidth / charWidth`.
+ font.createLabelAtlas(tex, 0, 0, "ABC", 0, 0);
+ // texWidth < charWidth: cols == 0, then `% cols` divides by zero.
+ font.createLabelAtlas(tex, 4, 4, "ABC", 8, 8);
+ // Valid dimensions still build glyphs.
+ font.createLabelAtlas(tex, 64, 16, "ABC", 16, 16);
+
+ std::printf("A5 OK: degenerate atlas dimensions did not divide by zero\n");
+ return 0;
+}