#include "lua_engine.h" #include "lua_api.h" #include "classes.h" #include "data.h" #include "game.h" #include "manager.h" #include "platform.h" #include #include #include #include #include #include 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 uint64_t NS_PER_MS = 1000000; constexpr int API_VERSION_NONE = -1; constexpr int API_VERSION_CURRENT = 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 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}}; // 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]; } // Logs the error a failed call left on top of the stack, popping it, and shows it on the console once a game exists. // The original leaves the message on the stack. void lua_error_log(lua_State* state, const char* name) { const char* text = lua_gettop(state) < 1 ? "missing error" : lua_tostring(state, -1); std::string error = text ? text : ""; if (lua_gettop(state) > 0) lua_pop(state, 1); 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()); } // 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 lua_error_log(state, UNLOAD_MOD); 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. 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; RegisterAPI(); RunScript(resource_path(ENUMS_SCRIPT)); RunScript(resource_path(MAIN_SCRIPT)); runCallbackRef = global_take(state, RUN_CALLBACK); unloadModRef = global_take(state, UNLOAD_MOD); } // 00866960 Registers the mod API: the classes, then the namespaces and the global functions, which replace the // SFXManager and MusicManager classes with the functions returning them. void LuaEngine::RegisterAPI() { for (auto registerPart : {lua_api_vector_register, lua_api_color_register, lua_api_rng_register, lua_api_bit_set128_register, lua_api_containers_register, lua_api_sprite_register, lua_api_entity_register, lua_api_entities_register, lua_api_entity_player_register, lua_api_game_register, lua_api_room_register, lua_api_item_config_register, lua_api_isaac_register}) registerPart(state); } // 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; }