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(aot): a host that links can open a module and read what it is
yhh0e7f1f36db44
diff --git a/compiler/src/codegen.ts b/compiler/src/codegen.tsindex edbc14f00..adab011ea 100644--- a/compiler/src/codegen.ts+++ b/compiler/src/codegen.ts@@ -138,6 +138,18 @@ typedef uintptr_t es_addr_t;#define ES_PTR(a) ((unsigned char *)(a))#endif+/* A host that LOADS this asks the platform for a symbol by name, and on+ Windows nothing is exported from a DLL unless it says so — the module+ builds, loads, and answers null to every lookup. A wasm link names its+ exports on the command line instead, so this is inert there. */+#if defined(_WIN32)+#define ES_EXPORT __declspec(dllexport)+#elif defined(__GNUC__)+#define ES_EXPORT __attribute__((visibility("default")))+#else+#define ES_EXPORT+#endif+/* The packed rows the host materialised: for each row, the entity andthen one base address per component the query named, in that order. */typedef struct EsQueryRows {@@ -741,7 +753,7 @@ class Emitter {const bound = new Set<number>();loopBound(sys.body, bound);- this.line(0, `void ${cSymbol(sys.name)}(es_addr_t es_ctx) {`);+ this.line(0, `ES_EXPORT void ${cSymbol(sys.name)}(es_addr_t es_ctx) {`);this.line(1, 'const EsSysCtx *es_c = (const EsSysCtx *)ES_PTR(es_ctx);');if (plan.queries.length > 0) {this.line(1, 'const EsQueryRows *es_queries = (const EsQueryRows *)ES_PTR(es_c->queries);');@@ -870,10 +882,10 @@ export function emitC(' to the MACHINE, so it mixes in here rather than in the compiler and a',' 32-bit artifact cannot load into a 64-bit host. */',`#define ES_ABI_ENGINE_DIGEST 0x${handshake.engineAbi}ULL`,- 'const uint64_t es_abi_hash =',+ 'ES_EXPORT const uint64_t es_abi_hash =',` ES_ABI_ENGINE_DIGEST ^ (${ADDR_MIX}ULL * (uint64_t)sizeof(es_addr_t));`,'',- ...systems.map((s) => `void ${cSymbol(s.name)}(es_addr_t es_ctx);`),+ ...systems.map((s) => `ES_EXPORT void ${cSymbol(s.name)}(es_addr_t es_ctx);`),'',...manifest,].join('\n');@@ -926,10 +938,10 @@ function emitManifest(systems: readonly EirSystem[], plans: readonly SysPlan[]):+ `${plan.queries.length}u, ${plan.resources.length}u },`);});out.push('');- out.push('const EsSystemDecl es_systems[] = {');+ out.push('ES_EXPORT const EsSystemDecl es_systems[] = {');out.push(...rows);out.push('};');- out.push(`const uint32_t es_system_count = ${systems.length}u;`);+ out.push(`ES_EXPORT const uint32_t es_system_count = ${systems.length}u;`);out.push('');return out;}diff --git a/native/host/steam/SteamApi.cpp b/native/host/steam/SteamApi.cppindex 30850c02b..3567e8a71 100644--- a/native/host/steam/SteamApi.cpp+++ b/native/host/steam/SteamApi.cpp@@ -18,12 +18,7 @@#include <cstring>#include "Runtime.hpp" // ESHOST_LOGI / ESHOST_LOGE--#if defined(_WIN32)-#include <windows.h>-#else-#include <dlfcn.h>-#endif+#include "esengine/core/DynamicLibrary.hpp"namespace eshost {namespace {@@ -58,31 +53,10 @@ constexpr const char* kUtilsAccessors[] = {"SteamAPI_SteamUtils_v011", "SteamAPI_SteamUtils_v010", "SteamAPI_SteamUtils_v009",};-void* openLibrary(const char* name) {-#if defined(_WIN32)- return reinterpret_cast<void*>(LoadLibraryA(name));-#else- return dlopen(name, RTLD_LAZY | RTLD_LOCAL);-#endif-}--void closeLibrary(void* handle) {- if (!handle) return;-#if defined(_WIN32)- FreeLibrary(reinterpret_cast<HMODULE>(handle));-#else- dlclose(handle);-#endif-}--void* symbol(void* handle, const char* name) {- if (!handle) return nullptr;-#if defined(_WIN32)- return reinterpret_cast<void*>(GetProcAddress(reinterpret_cast<HMODULE>(handle), name));-#else- return dlsym(handle, name);-#endif-}+using esengine::core::closeLibrary;+using esengine::core::openLibrary;+/** Named `symbol` here because that is what this file's call sites read as. */+constexpr auto symbol = esengine::core::librarySymbol;/** The subset of the flat API this host calls, declared here because the point is* to carry no Valve header. Signatures transcribed from steam_api_flat.h. */diff --git a/src/esengine/aot/AotModule.hpp b/src/esengine/aot/AotModule.hppnew file mode 100644index 000000000..c13d2343d--- /dev/null+++ b/src/esengine/aot/AotModule.hpp@@ -0,0 +1,117 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file AotModule.hpp+ * @brief A built module of compiled systems, opened by a host that links.+ *+ * @details The wasm road ships a manifest beside the module because a browser+ * cannot read a data section out of one. A host that LOADS a library+ * has no such problem: the declaration table is in the artifact, so+ * the names, the queries, the resources and the handshake all come+ * from the thing being run rather than from a file beside it that can+ * be swapped for another.+ *+ * Refuses rather than degrades. A module built for other offsets does+ * not produce a wrong answer, it produces a read of a different field,+ * so `open` is not "did the platform load it" — it is also "does it+ * agree about the engine and the address width".+ *+ * Owns the handle. Moving transfers it; copying is refused, because+ * two owners closing one library is the bug this exists to not have.+ */+#pragma once++#include <cstdint>+#include <cstring>+#include <span>+#include <string>+#include <utility>++#include "esengine/aot/estella_abi.h"+#include "esengine/core/DynamicLibrary.hpp"++namespace esengine::aot {++/**+ * What a host expects a module to say, from the contract IT was built against.+ *+ * The width is this side's `sizeof(es_addr_t)`, mixed in exactly as the module+ * mixes its own — which is what stops a 32-bit artifact from loading here and+ * reading every row at half a pointer.+ */+constexpr std::uint64_t expectedAbiHash(std::uint64_t contractDigest) {+ return contractDigest ^ (0x9e3779b97f4a7c15ULL * static_cast<std::uint64_t>(sizeof(es_addr_t)));+}++class Module {+public:+ Module() = default;+ ~Module() { close(); }+ Module(const Module&) = delete;+ Module& operator=(const Module&) = delete;+ Module(Module&& other) noexcept { *this = std::move(other); }+ Module& operator=(Module&& other) noexcept {+ if (this != &other) {+ close();+ handle_ = std::exchange(other.handle_, nullptr);+ systems_ = std::exchange(other.systems_, {});+ }+ return *this;+ }++ /**+ * Open a module and check it agrees with `expected` (see expectedAbiHash).+ *+ * `why` is filled on every false: the ways this fails want different fixes —+ * the file is absent, it carries no declaration table, or it was built for+ * another engine.+ */+ bool open(const char* path, std::uint64_t expected, std::string* why = nullptr) {+ close();+ const auto fail = [why](const char* msg) { if (why != nullptr) *why = msg; return false; };+ handle_ = core::openLibrary(path);+ if (handle_ == nullptr) return fail("the platform could not load it");++ const auto* hash = static_cast<const std::uint64_t*>(core::librarySymbol(handle_, "es_abi_hash"));+ const auto* count = static_cast<const std::uint32_t*>(core::librarySymbol(handle_, "es_system_count"));+ const auto* decls = static_cast<const EsSystemDecl*>(core::librarySymbol(handle_, "es_systems"));+ if (hash == nullptr || count == nullptr || decls == nullptr) {+ close();+ // A wasm module is built WITHOUT the declaration table on purpose;+ // handing one to a linking host lands exactly here.+ return fail("it carries no declaration table — built for a host that shares memory?");+ }+ if (*hash != expected) {+ close();+ return fail("it was built against a different engine or address width");+ }+ systems_ = std::span<const EsSystemDecl>(decls, *count);+ return true;+ }++ bool isOpen() const { return handle_ != nullptr; }++ /** Every system this module carries, as the artifact declares them. */+ std::span<const EsSystemDecl> systems() const { return systems_; }++ /** One by the name the schedule knows, or nullptr. */+ const EsSystemDecl* find(const char* name) const {+ for (const auto& decl : systems_) {+ if (decl.name != nullptr && std::strcmp(decl.name, name) == 0) return &decl;+ }+ return nullptr;+ }++ void close() {+ // The declarations live IN the library, so they stop existing with it.+ systems_ = {};+ core::closeLibrary(handle_);+ handle_ = nullptr;+ }++private:+ void* handle_ = nullptr;+ std::span<const EsSystemDecl> systems_{};+};++} // namespace esengine::aotdiff --git a/src/esengine/aot/estella_abi.h b/src/esengine/aot/estella_abi.hindex a0121fa3e..c861726d1 100644--- a/src/esengine/aot/estella_abi.h+++ b/src/esengine/aot/estella_abi.h@@ -32,6 +32,18 @@ typedef uintptr_t es_addr_t;#define ES_PTR(a) ((unsigned char *)(a))#endif+/* A host that LOADS this asks the platform for a symbol by name, and on+ Windows nothing is exported from a DLL unless it says so — the module+ builds, loads, and answers null to every lookup. A wasm link names its+ exports on the command line instead, so this is inert there. */+#if defined(_WIN32)+#define ES_EXPORT __declspec(dllexport)+#elif defined(__GNUC__)+#define ES_EXPORT __attribute__((visibility("default")))+#else+#define ES_EXPORT+#endif+/* The packed rows the host materialised: for each row, the entity andthen one base address per component the query named, in that order. */typedef struct EsQueryRows {diff --git a/src/esengine/core/DynamicLibrary.hpp b/src/esengine/core/DynamicLibrary.hppnew file mode 100644index 000000000..2012881db--- /dev/null+++ b/src/esengine/core/DynamicLibrary.hpp@@ -0,0 +1,66 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file DynamicLibrary.hpp+ * @brief Open a shared library and take a symbol out of it.+ *+ * @details Three lines of platform per operation, and every place that needs+ * them writes the same three. Two do now — the Steamworks flat API,+ * which carries no Valve header on purpose, and the compiled systems a+ * native host loads — and a third copy is how they start to differ+ * about `RTLD_LOCAL` or about what a null handle means.+ *+ * Header-only and free of the engine, so a host, a harness or a tool+ * can use it without linking anything.+ *+ * It does NOT throw and does NOT log: what a failed open means is the+ * caller's, since a missing Steam library is a feature nobody bought+ * and a missing systems module is a build that cannot run.+ */+#pragma once++#if defined(_WIN32)+# ifndef WIN32_LEAN_AND_MEAN+# define WIN32_LEAN_AND_MEAN+# endif+# include <windows.h>+#else+# include <dlfcn.h>+#endif++namespace esengine::core {++/** A loaded library, or nullptr. The path is taken as given — a leaf name is+ * searched the way the platform searches one, which is rarely what a caller+ * wants; pass an absolute path unless the search IS the intent. */+inline void* openLibrary(const char* path) {+#if defined(_WIN32)+ return reinterpret_cast<void*>(::LoadLibraryA(path));+#else+ // LOCAL, so a symbol here cannot satisfy an unrelated lookup elsewhere.+ return ::dlopen(path, RTLD_LAZY | RTLD_LOCAL);+#endif+}++/** Safe on nullptr, because "close whatever I got" is every caller's shape. */+inline void closeLibrary(void* handle) {+ if (handle == nullptr) return;+#if defined(_WIN32)+ ::FreeLibrary(reinterpret_cast<HMODULE>(handle));+#else+ ::dlclose(handle);+#endif+}++/** The address of an exported symbol, or nullptr — including for a null handle,+ * so a caller that failed to open needs no second branch. */+inline void* librarySymbol(void* handle, const char* name) {+ if (handle == nullptr) return nullptr;+#if defined(_WIN32)+ return reinterpret_cast<void*>(::GetProcAddress(reinterpret_cast<HMODULE>(handle), name));+#else+ return ::dlsym(handle, name);+#endif+}++} // namespace esengine::corediff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txtindex e49a6adc1..ae52b9963 100644--- a/tests/CMakeLists.txt+++ b/tests/CMakeLists.txt@@ -63,6 +63,26 @@ target_compile_options(test_aot_host PRIVATE)add_test(NAME test_aot_host COMMAND test_aot_host)+# The same compiled system as a LOADABLE module, which is the shape a native+# host takes. Built from the same two sources the harness links directly, so a+# difference between the two roads is the loading and nothing else.+add_library(aot_move_system MODULE+ aot/generated/move_system.c+ aot/generated/move_system_decl.c+)+target_include_directories(aot_move_system PRIVATE+ ${CMAKE_SOURCE_DIR}/src/esengine/aot+ ${CMAKE_SOURCE_DIR}/tests/aot/generated+)+set_target_properties(aot_move_system PROPERTIES PREFIX "")+add_dependencies(test_aot_host aot_move_system)+# The path rather than a convention: where a MODULE lands differs by generator+# and by platform, and a harness guessing it reports "cannot load" for a file+# that was built perfectly.+target_compile_definitions(test_aot_host PRIVATE+ ES_AOT_MODULE_PATH="$<TARGET_FILE:aot_move_system>"+)+# SparseSet testsadd_executable(test_sparse_setecs/test_sparse_set.cppdiff --git a/tests/aot/generated/move_system.c b/tests/aot/generated/move_system.cindex e3d6716f7..f29fd3ccd 100644--- a/tests/aot/generated/move_system.c+++ b/tests/aot/generated/move_system.c@@ -3,7 +3,7 @@#include "estella_abi.h"#include "estella_offsets.h"-void es_sys_MoveSystem(es_addr_t es_ctx) {+ES_EXPORT void es_sys_MoveSystem(es_addr_t es_ctx) {const EsSysCtx *es_c = (const EsSysCtx *)ES_PTR(es_ctx);const EsQueryRows *es_queries = (const EsQueryRows *)ES_PTR(es_c->queries);const es_addr_t *es_resources = (const es_addr_t *)ES_PTR(es_c->resources);diff --git a/tests/aot/generated/move_system_decl.c b/tests/aot/generated/move_system_decl.cindex d0b31b465..66e27bbc5 100644--- a/tests/aot/generated/move_system_decl.c+++ b/tests/aot/generated/move_system_decl.c@@ -11,10 +11,10 @@to the MACHINE, so it mixes in here rather than in the compiler and a32-bit artifact cannot load into a 64-bit host. */#define ES_ABI_ENGINE_DIGEST 0xe83b13ad2f96720cULL-const uint64_t es_abi_hash =+ES_EXPORT const uint64_t es_abi_hash =ES_ABI_ENGINE_DIGEST ^ (0x9e3779b97f4a7c15ULL * (uint64_t)sizeof(es_addr_t));-void es_sys_MoveSystem(es_addr_t es_ctx);+ES_EXPORT void es_sys_MoveSystem(es_addr_t es_ctx);/* The systems in this file, and what each one needs filled in. */static const char *const es_sys_MoveSystem_q0_comps[] = { "Transform", "Mover" };@@ -23,7 +23,7 @@ static const EsQueryDecl es_sys_MoveSystem_queries[] = { { es_sys_MoveSystem_q0_static const char *const es_sys_MoveSystem_resources[] = { "Time" };static const unsigned char es_sys_MoveSystem_resources_mut[] = { 0u };-const EsSystemDecl es_systems[] = {+ES_EXPORT const EsSystemDecl es_systems[] = {{ "MoveSystem", es_sys_MoveSystem, es_sys_MoveSystem_queries, es_sys_MoveSystem_resources, es_sys_MoveSystem_resources_mut, 1u, 1u },};-const uint32_t es_system_count = 1u;+ES_EXPORT const uint32_t es_system_count = 1u;diff --git a/tests/aot/test_aot_host.cpp b/tests/aot/test_aot_host.cppindex e04831c73..157fcc25a 100644--- a/tests/aot/test_aot_host.cpp+++ b/tests/aot/test_aot_host.cpp@@ -28,10 +28,12 @@#include <cstddef>#include <cstdint>#include <cstring>+#include <string>#include <vector>#include "esengine/aot/AotHost.hpp"#include "esengine/aot/AotComponents.generated.hpp"+#include "esengine/aot/AotModule.hpp"#include "esengine/ecs/Registry.hpp"#include "esengine/ecs/components/Transform.hpp"@@ -342,3 +344,53 @@ TEST_CASE("a compiled system runs on the generated resolvers, exactly as on handCHECK(want->position.y == got->position.y);}}++#ifdef ES_AOT_MODULE_PATH+TEST_CASE("the same system, loaded out of a module rather than linked in") {+ aot::Module mod;+ std::string why;+ const std::uint64_t expected = aot::expectedAbiHash(ES_EXPECTED_CONTRACT_HASH);+ REQUIRE_MESSAGE(mod.open(ES_AOT_MODULE_PATH, expected, &why), why);++ // The declaration table is IN the artifact, so a loading host needs no+ // manifest beside it: the name, the queries and the resources all came out+ // of the thing that is about to run.+ const EsSystemDecl* decl = mod.find("MoveSystem");+ REQUIRE(decl != nullptr);+ CHECK(decl->queryCount == 1u);+ CHECK(decl->resourceCount == 1u);+ CHECK(std::strcmp(decl->resources[0], "Time") == 0);+ CHECK(decl->fn != nullptr);++ // And it moves the world the linked-in copy moves.+ World linked = makeWorld();+ World loaded = makeWorld();+ aot::CallArena arena;+ aot::runBound(aot::bind(*declOf("MoveSystem"), componentsOf(linked), resourcesOf(linked)),+ linked.entities, resourcesOf(linked), arena);+ aot::runBound(aot::bind(*decl, componentsOf(loaded), resourcesOf(loaded)),+ loaded.entities, resourcesOf(loaded), arena);++ for (std::size_t i = 0; i < linked.entities.size(); ++i) {+ const auto* want = linked.registry.tryGet<ecs::Transform>(Entity::fromRaw(linked.entities[i]));+ const auto* got = loaded.registry.tryGet<ecs::Transform>(Entity::fromRaw(loaded.entities[i]));+ REQUIRE((want != nullptr) == (got != nullptr));+ if (want == nullptr) continue;+ CHECK(want->position.x == got->position.x);+ CHECK(want->position.y == got->position.y);+ }+}++TEST_CASE("a module built for another engine is refused, and says which half moved") {+ aot::Module mod;+ std::string why;+ // One bit of the contract, which is what a rebuilt engine looks like from+ // here. It must not open at all: a wrong offset is a read of another field.+ CHECK(mod.open(ES_AOT_MODULE_PATH, aot::expectedAbiHash(ES_EXPECTED_CONTRACT_HASH ^ 1ULL), &why) == false);+ CHECK(mod.isOpen() == false);+ CHECK(why.find("engine") != std::string::npos);++ CHECK(mod.open("no-such-module-anywhere", 0, &why) == false);+ CHECK(why.find("load") != std::string::npos);+}+#endif