#include "lua_engine.h" #include "classes.h" #include "data.h" #include "game.h" #include "manager.h" #include "platform.h" #include #include #include #include #include #include // classes.h declares the original's Lua imports, and its luaL_newstate differs from Lua's only in its return type. // Lua's is renamed away here, as Init opens the state the way the original's reserved heap did. #define luaL_newstate lua_newstate_auxiliary extern "C" { #include "lauxlib.h" #include "lua.h" #include "lualib.h" } #undef luaL_newstate constexpr const char* ENUMS_SCRIPT = "scripts/enums.lua"; constexpr const char* MAIN_SCRIPT = "scripts/main.lua"; constexpr const char* MOD_MAIN_SCRIPT = "/main.lua"; constexpr const char* NATIVE_MODULES = "scripts/?.so"; constexpr const char* SCRIPT_MODULES = "scripts/?.lua"; constexpr const char* SCRIPT_FOLDER_MODULES = "/?.lua;"; constexpr const char* UPDATE_MARKER = "/update.it"; constexpr const char* PATH_SEPARATORS = "/\\"; constexpr const char* RUN_CALLBACK = "_RunCallback"; constexpr const char* UNLOAD_MOD = "_UnloadMod"; constexpr int API_VERSION_NONE = -1; constexpr int API_VERSION_CURRENT = 1; constexpr int PILL_EFFECT_UNCHANGED = -1; constexpr int GC_COOLDOWN_FRAMES = 600; constexpr int GC_SHRINK_DIVISOR = 100; constexpr int GC_SHRINK_MIN = 10; constexpr int GC_STEP_MAX = 10000; constexpr uint64_t NS_PER_MS = 1000000; constexpr uint32_t MASK_SALT = 0xdeadbeef; constexpr int MASK_SHIFTS[] = {4, 5, 11}; // The libraries a normal state opens: no io, os or package, so scripts reach neither files nor native code. constexpr luaL_Reg SANDBOX_LIBRARIES[] = { {"_G", luaopen_base}, {LUA_COLIBNAME, luaopen_coroutine}, {LUA_TABLIBNAME, luaopen_table}, {LUA_STRLIBNAME, luaopen_string}, {LUA_MATHLIBNAME, luaopen_math}, {LUA_UTF8LIBNAME, luaopen_utf8}, {LUA_DBLIBNAME, luaopen_debug}}; // A game object a callback hands to Lua by pointer, and the class whose metatable it gets. struct LuaObject { void* object; LuaClass luaClass; }; // One run of a callback: the name its errors log, its id, and the parameter mods filter it by (-1 for none). struct CallbackRun { const char* name; LuaCallback id; int param = -1; }; // One distinct address per class, the registry keys of their metatables, as LuaBridge's class keys are. static std::array classKeys; const void* lua_class_key(LuaClass luaClass) { return &classKeys[luaClass]; } // Pushes a callback argument: integers and booleans as themselves. static void value_push(lua_State* state, int value) { lua_pushinteger(state, value); } static void value_push(lua_State* state, unsigned int value) { lua_pushinteger(state, value); } static void value_push(lua_State* state, bool value) { lua_pushboolean(state, value); } // Pushes an object as a userdata holding its pointer, with its class's metatable, or nil for none. static void value_push(lua_State* state, LuaObject value) { if (!value.object) return lua_pushnil(state); *(void**)lua_newuserdata(state, sizeof(void*)) = value.object; lua_rawgetp(state, LUA_REGISTRYINDEX, lua_class_key(value.luaClass)); lua_setmetatable(state, -2); } // The message a failed call left on top of the stack, popped. The original leaves it there. static std::string error_pop(lua_State* state) { if (lua_gettop(state) < 1) return "missing error"; const char* text = lua_tostring(state, -1); std::string error = text ? text : ""; lua_pop(state, 1); return error; } // Logs a callback's error, and shows it on the console once a game exists. static void error_log(const char* name, const std::string& error) { log_printf(LOG_INFO, "Error in \"%s\" call: %s\n", name, error.c_str()); if (g_game) g_game->console.print_format(CONSOLE_ERROR, "\"%s\" failed: %s\n", name, error.c_str()); } // Calls _RunCallback with a callback's id, its filter parameter and its arguments when a mod added a function for it, // leaving its one result on the stack. Whether it ran, false without a function or on an error, which is logged. // The callers, result readers and error throws the original instantiates per callback are this and its readers // (00872980, 00872c60, 00873470, 00873980, 00873d00, 00873fc0, 00874120, 00874210, 00874310, 00874a10, 00874f60) // (0085c080, 008727d0, 0086130e, 00861225, 00861d96, 00861e7f, 008623a6, 0086248f, 008628b6, 0086299f, 00864453) // (0086453c, 00865bbc), and their catches log through error_log (00860ea3, 008611da, 0086191f, 00861d4b, 0086235b) // (0086286b, 00862ea4, 008632e1, 00863706, 00863b6a, 00863e31, 00863f1e, 008640de, 00864408, 00864f6e, 00865b69) // (008661cc). template static bool callback_run(LuaEngine& engine, CallbackRun run, Args... args) { if (!engine.enabledCallbacks[run.id]) return false; lua_State* state = engine.state; lua_rawgeti(state, LUA_REGISTRYINDEX, engine.runCallbackRef); value_push(state, (int)run.id); value_push(state, run.param); (value_push(state, args), ...); if (lua_pcall(state, sizeof...(Args) + 2, 1, 0) == LUA_OK) return true; error_log(run.name, error_pop(state)); return false; } // Runs a callback whose result the game ignores. template static void callback_notify(LuaEngine& engine, CallbackRun run, Args... args) { if (callback_run(engine, run, args...)) lua_pop(engine.state, 1); } // Runs a Pre*Collision callback for an entity and what it hits, and reads its result as true, false or nothing. static LuaResult collision_run(LuaEngine& engine, CallbackRun run, LuaObject entity, Entity* collider, bool isLow) { if (!callback_run(engine, run, entity, LuaObject{collider, LUA_CLASS_ENTITY}, isLow)) return LUA_RESULT_NIL; LuaResult result = lua_isnil(engine.state, -1) ? LUA_RESULT_NIL : lua_toboolean(engine.state, -1) ? LUA_RESULT_TRUE : LUA_RESULT_FALSE; lua_pop(engine.state, 1); return result; } // Sets value to a field of the table on top of the stack, when the field is not nil. static void field_read(lua_State* state, const char* key, bool& value) { lua_getfield(state, -1, key); if (!lua_isnil(state, -1)) value = lua_toboolean(state, -1); lua_pop(state, 1); } // A field of the package table, empty when it is not a string. static std::string package_field_get(lua_State* state, const char* field) { lua_getglobal(state, LUA_LOADLIBNAME); lua_getfield(state, -1, field); const char* text = lua_tostring(state, -1); std::string value = text ? text : ""; lua_pop(state, 2); return value; } // Sets a field of the package table to a string. static void package_field_set(lua_State* state, const char* field, const std::string& value) { lua_getglobal(state, LUA_LOADLIBNAME); lua_pushstring(state, value.c_str()); lua_setfield(state, -2, field); lua_pop(state, 1); } // 0085ef00 Adds a search pattern to package.path or package.cpath. static void package_field_append(lua_State* state, const char* field, const std::string& pattern) { package_field_set(state, field, package_field_get(state, field) + ";" + pattern); } // 0085f080 The folder a path is in, the whole path when it has none. static std::string directory_get(std::string_view path) { return std::string(path.substr(0, path.find_last_of(PATH_SEPARATORS))); } // Moves a global into the registry, clearing it, so only the engine reaches it. static int global_take(lua_State* state, const char* name) { lua_getglobal(state, name); int ref = luaL_ref(state, LUA_REGISTRYINDEX); lua_pushnil(state); lua_setglobal(state, name); return ref; } // The mask the API hides object pointers with, hashed from a time in milliseconds. static uint32_t pointer_mask_make(uint32_t time) { uint32_t hash = time ^ (time >> MASK_SHIFTS[0]); hash = (hash ^ MASK_SALT) + (hash << MASK_SHIFTS[1]); return hash ^ (hash >> MASK_SHIFTS[2]); } // 00860440 Lua's allocator: frees a block resized to nothing, resizes any other. static void* memory_allocate(void*, void* block, size_t, size_t size) { if (size) return std::realloc(block, size); std::free(block); return nullptr; } // 00860470 Reports a Lua error raised outside any protected call, before Lua aborts. static int panic_report(lua_State* state) { const char* error = lua_tostring(state, -1); std::fprintf(stderr, "PANIC: unprotected error in call to Lua API (%s)\n", error ? error : ""); std::fflush(stderr); return 0; } // 00870e00 Hands a mod's table to _UnloadMod and releases it. // The original throws past every caller on a Lua error. This logs it as a callback error instead. static void mod_unload(LuaEngine& engine, LuaMod& mod) { lua_State* state = engine.state; lua_rawgeti(state, LUA_REGISTRYINDEX, engine.unloadModRef); lua_rawgeti(state, LUA_REGISTRYINDEX, mod.tableRef); if (lua_pcall(state, 1, 1, 0) == LUA_OK) lua_pop(state, 1); else error_log(UNLOAD_MOD, error_pop(state)); luaL_unref(state, LUA_REGISTRYINDEX, mod.tableRef); mod.tableRef = LUA_REF_NONE; } // 008604c0 Opens a state with the pointer mask hashed from the time, the sandboxed libraries or, in debug mode, every // library with require searching resources/scripts/, then runs enums.lua and main.lua, as RunBundledScript did // (0086e5e0), and takes their _RunCallback and _UnloadMod. The state always opens as on the reserved heap, with the // C heap in its place, since --luaheapsize is ignored. RegisterAPI is not called until it is reconstructed. void LuaEngine::Init(LuaMode luaMode) { pointerMask = pointer_mask_make((uint32_t)(GetTimeNs() / NS_PER_MS)); state = lua_newstate(memory_allocate, nullptr); if (state) lua_atpanic(state, panic_report); if (luaMode == LUA_MODE_DEBUG) { log_printf(LOG_WARN, "Running Lua in debug mode...\n"); luaL_openlibs(state); package_field_append(state, "cpath", resource_path(NATIVE_MODULES)); package_field_append(state, "path", resource_path(SCRIPT_MODULES)); lua_pushboolean(state, true); lua_setglobal(state, "_LUADEBUG"); } else for (const luaL_Reg& library : SANDBOX_LIBRARIES) { luaL_requiref(state, library.name, library.func, 1); lua_pop(state, 1); } mode = luaMode; log_printf(LOG_WARN, "**The mod API is not reconstructed yet, so scripts run without the Isaac table\n"); RunScript(resource_path(ENUMS_SCRIPT)); RunScript(resource_path(MAIN_SCRIPT)); runCallbackRef = global_take(state, RUN_CALLBACK); unloadModRef = global_take(state, UNLOAD_MOD); } void LuaEngine::RegisterAPI() { reconstruction_missing("LuaEngine::RegisterAPI 00866960"); } // 0086e520 Unloads every registered mod, releases the engine's references and closes the state. // The mod list clear (008975d0) is the list's own. void LuaEngine::destroy() { for (LuaMod& mod : mods) mod_unload(*this, mod); mods.clear(); luaL_unref(state, LUA_REGISTRYINDEX, runCallbackRef); luaL_unref(state, LUA_REGISTRYINDEX, unloadModRef); runCallbackRef = LUA_REF_NONE; unloadModRef = LUA_REF_NONE; lua_close(state); state = nullptr; } // 0086e6c0 Runs a script file, after unloading the mods it registered when it last ran. In debug mode require searches // the script's folder first. An error is logged, and a mod registered with an API version other than 1 gets an // update.it in its folder. After a run Lua collects its garbage and logs its memory. Whether the script ran. bool LuaEngine::RunScript(std::string_view path) { std::string file(path); log_printf(LOG_INFO, "Running Lua Script: %s\n", file.c_str()); for (auto mod = mods.begin(); mod != mods.end();) { if (mod->scriptPath != file) ++mod; else { mod_unload(*this, *mod); mod = mods.erase(mod); } } std::string modulesPath; if (mode == LUA_MODE_DEBUG) { modulesPath = package_field_get(state, "path"); package_field_set(state, "path", directory_get(file) + SCRIPT_FOLDER_MODULES + modulesPath); } scriptPath = file; scriptApiVersion = API_VERSION_NONE; bool isFailed = luaL_loadfile(state, file.c_str()) != LUA_OK || lua_pcall(state, 0, LUA_MULTRET, 0) != LUA_OK; if (mode == LUA_MODE_DEBUG) package_field_set(state, "path", modulesPath); if (!isFailed) { lua_gc(state, LUA_GCCOLLECT, 0); int bytes = lua_gc(state, LUA_GCCOUNTB, 0); int kilobytes = lua_gc(state, LUA_GCCOUNT, 0); log_printf(LOG_INFO, "Lua mem usage: %d KB and %d bytes\n", kilobytes, bytes); return true; } if (lua_gettop(state) > 0) { if (lua_type(state, -1) == LUA_TSTRING) { log_printf(LOG_INFO, "ERR: %s\n", lua_tostring(state, -1)); if (g_game) g_game->console.PrintError(lua_tostring(state, -1)); } lua_settop(state, 0); } log_printf(LOG_INFO, "There was an error running the lua file: %s\n", file.c_str()); if (scriptApiVersion == API_VERSION_NONE || scriptApiVersion == API_VERSION_CURRENT) return false; log_printf(LOG_INFO, "The error might be from compatibility issue, please update the mod!\n"); std::ofstream(directory_get(scriptPath) + UPDATE_MARKER); return false; } // 008f70f0 Runs again the main.lua of the loaded mod in folder modName, for the luamod command, with ModManager // loading that mod. Whether it ran, false when no loaded mod with that folder has a main.lua. bool LuaEngine::LuamodCMD(std::string_view modName) { ModManager& modManager = g_manager->modManager; for (auto& mod : modManager.mods) { if (!mod->isLoaded || mod->directory != modName) continue; std::string path = platform.modsDirectory + mod->directory + MOD_MAIN_SCRIPT; std::error_code error; if (!std::filesystem::exists(path, error)) continue; modManager.loadingMod = mod.get(); bool isRun = RunScript(path); modManager.loadingMod = nullptr; return isRun; } return false; } // 008657c0 Steps the garbage collector once a frame. The step grows while memory grew in each of the last ten frames, // holds for ten seconds after, then shrinks back. void LuaEngine::gc_update() { int memory = lua_gc(state, LUA_GCCOUNT, 0); gcGrowth[gcFrame % LUA_GC_HISTORY_SIZE] = memory - (gcLastMemory < 0 ? memory : gcLastMemory); gcFrame++; gcLastMemory = memory; int growth = std::accumulate(gcGrowth.begin(), gcGrowth.end(), 0); bool isGrowing = std::ranges::none_of(gcGrowth, [](int frameGrowth) { return frameGrowth < 0; }); if (isGrowing && growth > 0) { gcCooldown = GC_COOLDOWN_FRAMES; gcStepSize = std::clamp(gcStepSize + growth / LUA_GC_HISTORY_SIZE, LUA_GC_STEP_MIN, GC_STEP_MAX); } else if (gcCooldown > 0) gcCooldown--; else gcStepSize = std::max(gcStepSize - std::max(gcStepSize / GC_SHRINK_DIVISOR, GC_SHRINK_MIN), LUA_GC_STEP_MIN); lua_gc(state, LUA_GCSTEP, gcStepSize); } // 0086f640 A collectible's id by its name, -1 for none. The original searches a copy of the name map. int LuaEngine::Isaac_GetItemIdByName(std::string_view name) { auto& names = g_manager->itemConfig.collectibleNameMap; auto found = names.find(name); return found == names.end() ? -1 : found->second; } // 00862250 Runs MC_PRE_BOMB_COLLISION, filtered by the bomb's variant. LuaResult LuaEngine::PreBombCollision(Entity_Bomb* bomb, Entity* collider, bool isLow) { CallbackRun run = {"PreBombCollision", MC_PRE_BOMB_COLLISION, (int)bomb->_variant}; return collision_run(*this, run, {bomb, LUA_CLASS_BOMB}, collider, isLow); } // 008610d0 Runs MC_PRE_FAMILIAR_COLLISION, filtered by the familiar's variant. LuaResult LuaEngine::PreFamiliarCollision(Entity_Familiar* familiar, Entity* collider, bool isLow) { CallbackRun run = {"PreFamiliarCollision", MC_PRE_FAMILIAR_COLLISION, (int)familiar->_variant}; return collision_run(*this, run, {familiar, LUA_CLASS_FAMILIAR}, collider, isLow); } // 00861c40 Runs MC_PRE_KNIFE_COLLISION, filtered by the knife's subtype. LuaResult LuaEngine::PreKnifeCollision(Entity_Knife* knife, Entity* collider, bool isLow) { CallbackRun run = {"PreKnifeCollision", MC_PRE_KNIFE_COLLISION, (int)knife->_subtype}; return collision_run(*this, run, {knife, LUA_CLASS_KNIFE}, collider, isLow); } // 00860d70 Runs MC_PRE_NPC_COLLISION, filtered by the NPC's type. LuaResult LuaEngine::PreNPCCollision(Entity_NPC* npc, Entity* collider, bool isLow) { CallbackRun run = {"PreNPCCollision", MC_PRE_NPC_COLLISION, (int)npc->_type}; return collision_run(*this, run, {npc, LUA_CLASS_NPC}, collider, isLow); } // 008631b0 Runs MC_PRE_PICKUP_COLLISION, filtered by the pickup's variant. LuaResult LuaEngine::PrePickupCollision(Entity_Pickup* pickup, Entity* collider, bool isLow) { CallbackRun run = {"PrePickupCollision", MC_PRE_PICKUP_COLLISION, (int)pickup->_variant}; return collision_run(*this, run, {pickup, LUA_CLASS_PICKUP}, collider, isLow); } // 00864300 Runs MC_PRE_PLAYER_COLLISION, filtered by the player's variant. LuaResult LuaEngine::PrePlayerCollide(Entity_Player* player, Entity* collider, bool isLow) { CallbackRun run = {"PrePlayerCollision", MC_PRE_PLAYER_COLLISION, (int)player->_variant}; return collision_run(*this, run, {player, LUA_CLASS_PLAYER}, collider, isLow); } // 00862760 Runs MC_PRE_PROJECTILE_COLLISION, filtered by the projectile's variant. LuaResult LuaEngine::PreProjectileCollision(Entity_Projectile* projectile, Entity* collider, bool isLow) { CallbackRun run = {"PreProjectileCollision", MC_PRE_PROJECTILE_COLLISION, (int)projectile->_variant}; return collision_run(*this, run, {projectile, LUA_CLASS_PROJECTILE}, collider, isLow); } // 00862d70 Runs MC_PRE_TEAR_COLLISION, filtered by the tear's variant. LuaResult LuaEngine::PreTearCollision(Entity_Tear* tear, Entity* collider, bool isLow) { CallbackRun run = {"PreTearCollision", MC_PRE_TEAR_COLLISION, (int)tear->_variant}; return collision_run(*this, run, {tear, LUA_CLASS_TEAR}, collider, isLow); } // 00863e90 Runs MC_EVALUATE_CACHE for a player's stat, filtered by the cache flag. void LuaEngine::EvaluateItems(Entity_Player* player, int cacheFlag) { callback_notify(*this, {"PostEvaluateItems", MC_EVALUATE_CACHE, cacheFlag}, LuaObject{player, LUA_CLASS_PLAYER}, cacheFlag); } // 00865ad0 Runs MC_GET_PILL_EFFECT for the effect a pill color got. The effect a mod chose, -1 to keep it. // The original aborts on a result that is not an integer. This keeps the effect instead. int LuaEngine::GetPillEffect(int pillEffect, int pillColor) { CallbackRun run = {"GetPillEffect", MC_GET_PILL_EFFECT}; if (!callback_run(*this, run, pillEffect, pillColor)) return PILL_EFFECT_UNCHANGED; int isInteger = 0; lua_Integer effect = lua_tointegerx(state, -1, &isInteger); lua_pop(state, 1); return isInteger ? (int)effect : PILL_EFFECT_UNCHANGED; } // 00866140 Runs MC_POST_ENTITY_KILL, filtered by the entity's type. void LuaEngine::PostEntityKill(Entity* entity) { callback_notify(*this, {"PostEntityKill", MC_POST_ENTITY_KILL, (int)entity->_type}, LuaObject{entity, LUA_CLASS_ENTITY}); } // 00864ee0 Runs MC_POST_GAME_STARTED with whether the run continues a saved one. void LuaEngine::PostGameStart(bool isContinued) { callback_notify(*this, {"PostGameStart", MC_POST_GAME_STARTED}, isContinued); } // 00861890 Runs MC_POST_KNIFE_INIT, filtered by the knife's subtype. void LuaEngine::PostKnifeInit(Entity_Knife* knife) { callback_notify(*this, {"PostKnifeInit", MC_POST_KNIFE_INIT, (int)knife->_subtype}, LuaObject{knife, LUA_CLASS_KNIFE}); } // 00864050 Runs MC_POST_PLAYER_INIT, filtered by the player's variant. void LuaEngine::PostPlayerInit(Entity_Player* player) { callback_notify(*this, {"PostPlayerInit", MC_POST_PLAYER_INIT, (int)player->_variant}, LuaObject{player, LUA_CLASS_PLAYER}); } // 00863680 Runs MC_POST_RENDER after the game renders. void LuaEngine::PostRender() { callback_notify(*this, {"PostRender", MC_POST_RENDER}); } // 008638d0 Runs MC_USE_ITEM for an active item, filtered by its type. A table result sets Discharge, Remove and // ShowAnim, any other result ShowAnim alone. Whether to show the use animation, false without a result. bool LuaEngine::UseItem(LuaItemUse& use) { CallbackRun run = {"PostUseItem", MC_USE_ITEM, use.collectibleType}; if (!callback_run(*this, run, use.collectibleType, LuaObject{use.rng, LUA_CLASS_RNG}, LuaObject{use.player, LUA_CLASS_PLAYER}, use.useFlags, use.activeSlot, use.customVarData)) return false; bool isShowAnimation = false; if (!lua_istable(state, -1)) isShowAnimation = lua_toboolean(state, -1); else { field_read(state, "Discharge", use.isDischarge); field_read(state, "Remove", use.isRemove); field_read(state, "ShowAnim", isShowAnimation); } lua_pop(state, 1); return isShowAnimation; } // 00863da0 Runs MC_USE_PILL for a pill effect, filtered by it. void LuaEngine::UsePill(int pillEffect, Entity_Player* player, unsigned int useFlags) { callback_notify(*this, {"PostUsePillEffect", MC_USE_PILL, pillEffect}, pillEffect, LuaObject{player, LUA_CLASS_PLAYER}, useFlags); }