@ -52,21 +52,24 @@ namespace LuaUtil
" tonumber " , " tostring " , " type " , " unpack " , " xpcall " , " rawequal " , " rawget " , " rawset " , " setmetatable " } ;
static const std : : string safePackages [ ] = { " coroutine " , " math " , " string " , " table " } ;
static constexpr int64_t countHookStep = 2000 ;
static constexpr int64_t countHookStep = 1000 ;
bool LuaState : : sProfilerEnabled = true ;
void LuaState : : countHook ( lua_State * L , lua_Debug * ar )
{
LuaState * THIS ;
( void ) lua_getallocf ( L , reinterpret_cast < void * * > ( & THIS ) ) ;
if ( ! THIS - > mActiveScriptId . mContainer )
LuaState * self ;
( void ) lua_getallocf ( L , reinterpret_cast < void * * > ( & self ) ) ;
if ( self - > mActiveScriptIdStack . empty ( ) )
return ;
THIS - > mActiveScriptId . mContainer - > addCPUusage ( THIS - > mActiveScriptId . mIndex , countHookStep ) ;
THIS - > mCurrentCallInstructionCounter + = countHookStep ;
if ( THIS - > mSettings . mInstructionLimit > 0
& & THIS - > mCurrentCallInstructionCounter > THIS - > mSettings . mInstructionLimit )
const ScriptId & activeScript = self - > mActiveScriptIdStack . back ( ) ;
activeScript . mContainer - > addInstructionCount ( activeScript . mIndex , countHookStep ) ;
self - > mWatchdogInstructionCounter + = countHookStep ;
if ( self - > mSettings . mInstructionLimit > 0
& & self - > mWatchdogInstructionCounter > self - > mSettings . mInstructionLimit )
{
lua_pushstring ( L ,
" Lua CPU usage exceeded, probably an infinite loop in a script. "
" Lua instruction count exceeded, probably an infinite loop in a script. "
" To change the limit set \" [Lua] instruction limit per call \" in settings.cfg " ) ;
lua_error ( L ) ;
}
@ -74,9 +77,9 @@ namespace LuaUtil
void * LuaState : : trackingAllocator ( void * ud , void * ptr , size_t osize , size_t nsize )
{
LuaState * THIS = static_cast < LuaState * > ( ud ) ;
const uint64_t smallAllocSize = THIS - > mSettings . mSmallAllocMaxSize ;
const uint64_t memoryLimit = THIS - > mSettings . mMemoryLimit ;
LuaState * self = static_cast < LuaState * > ( ud ) ;
const uint64_t smallAllocSize = self - > mSettings . mSmallAllocMaxSize ;
const uint64_t memoryLimit = self - > mSettings . mMemoryLimit ;
if ( ! ptr )
osize = 0 ;
@ -90,14 +93,14 @@ namespace LuaUtil
else
bigAllocDelta + = nsize ;
if ( bigAllocDelta > 0 & & memoryLimit > 0 & & THIS - > mTotalMemoryUsage + nsize - osize > memoryLimit )
if ( bigAllocDelta > 0 & & memoryLimit > 0 & & self - > mTotalMemoryUsage + nsize - osize > memoryLimit )
{
Log ( Debug : : Error ) < < " Lua realloc " < < osize < < " -> " < < nsize
< < " is blocked because Lua memory limit (configurable in settings.cfg) is exceeded " ;
return nullptr ;
}
THIS - > mTotalMemoryUsage + = smallAllocDelta + bigAllocDelta ;
THIS - > mSmallAllocMemoryUsage + = smallAllocDelta ;
self - > mTotalMemoryUsage + = smallAllocDelta + bigAllocDelta ;
self - > mSmallAllocMemoryUsage + = smallAllocDelta ;
void * newPtr = nullptr ;
if ( nsize = = 0 )
@ -107,59 +110,83 @@ namespace LuaUtil
if ( bigAllocDelta ! = 0 )
{
auto it = osize > smallAllocSize ? THIS - > mBigAllocOwners . find ( ptr ) : THIS - > mBigAllocOwners . end ( ) ;
auto it = osize > smallAllocSize ? self - > mBigAllocOwners . find ( ptr ) : self - > mBigAllocOwners . end ( ) ;
ScriptId id ;
if ( it ! = THIS - > mBigAllocOwners . end ( ) )
if ( it ! = self - > mBigAllocOwners . end ( ) )
{
if ( it - > second . mContainer )
id = ScriptId { * it - > second . mContainer , it - > second . mScriptIndex } ;
if ( ptr ! = newPtr | | nsize < = smallAllocSize )
THIS - > mBigAllocOwners . erase ( it ) ;
self - > mBigAllocOwners . erase ( it ) ;
}
else if ( bigAllocDelta > 0 )
{
id = THIS - > mActiveScriptId ;
if ( ! self - > mActiveScriptIdStack . empty ( ) )
id = self - > mActiveScriptIdStack . back ( ) ;
bigAllocDelta = nsize ;
}
if ( id . mContainer )
{
if ( static_cast < size_t > ( id . mIndex ) > = THIS - > mMemoryUsage . size ( ) )
THIS - > mMemoryUsage . resize ( id . mIndex + 1 ) ;
THIS - > mMemoryUsage [ id . mIndex ] + = bigAllocDelta ;
if ( static_cast < size_t > ( id . mIndex ) > = self - > mMemoryUsage . size ( ) )
self - > mMemoryUsage . resize ( id . mIndex + 1 ) ;
self - > mMemoryUsage [ id . mIndex ] + = bigAllocDelta ;
id . mContainer - > addMemoryUsage ( id . mIndex , bigAllocDelta ) ;
if ( newPtr & & nsize > smallAllocSize )
THIS - > mBigAllocOwners . emplace ( newPtr , AllocOwner { id . mContainer - > mThis , id . mIndex } ) ;
self - > mBigAllocOwners . emplace ( newPtr , AllocOwner { id . mContainer - > mThis , id . mIndex } ) ;
}
}
return newPtr ;
}
lua_State * LuaState : : createLuaRuntime ( LuaState * luaState )
{
if ( sProfilerEnabled )
{
Log ( Debug : : Info ) < < " Initializing LuaUtil::LuaState with profiler " ;
lua_State * L = lua_newstate ( & trackingAllocator , luaState ) ;
if ( L )
return L ;
else
{
sProfilerEnabled = false ;
Log ( Debug : : Error )
< < " Failed to initialize LuaUtil::LuaState with custom allocator; disabling Lua profiler " ;
}
}
Log ( Debug : : Info ) < < " Initializing LuaUtil::LuaState without profiler " ;
lua_State * L = luaL_newstate ( ) ;
if ( ! L )
throw std : : runtime_error ( " Can't create Lua runtime " ) ;
return L ;
}
LuaState : : LuaState ( const VFS : : Manager * vfs , const ScriptsConfiguration * conf , const LuaStateSettings & settings )
: mSettings ( settings )
, mLua ( sol : : default_at_panic , & trackingAllocator , this )
, mLuaHolder ( createLuaRuntime ( this ) )
, mSol ( mLuaHolder . get ( ) )
, mConf ( conf )
, mVFS ( vfs )
{
lua_sethook ( mLua . lua_state ( ) , & countHook , LUA_MASKCOUNT , countHookStep ) ;
Log ( Debug : : Verbose ) < < " Initializing LuaUtil::LuaState " ;
if ( sProfilerEnabled )
lua_sethook ( mLuaHolder . get ( ) , & countHook , LUA_MASKCOUNT , countHookStep ) ;
mLua . open_libraries ( sol : : lib : : base , sol : : lib : : coroutine , sol : : lib : : math , sol : : lib : : bit32 , sol : : lib : : string ,
m Sol . open_libraries ( sol : : lib : : base , sol : : lib : : coroutine , sol : : lib : : math , sol : : lib : : bit32 , sol : : lib : : string ,
sol : : lib : : table , sol : : lib : : os , sol : : lib : : debug ) ;
mLua [ " math " ] [ " randomseed " ] ( static_cast < unsigned > ( std : : time ( nullptr ) ) ) ;
mLua [ " math " ] [ " randomseed " ] = [ ] { } ;
m Sol [ " math " ] [ " randomseed " ] ( static_cast < unsigned > ( std : : time ( nullptr ) ) ) ;
m Sol [ " math " ] [ " randomseed " ] = [ ] { } ;
mLua [ " writeToLog " ] = [ ] ( std : : string_view s ) { Log ( Debug : : Level : : Info ) < < s ; } ;
m Sol [ " writeToLog " ] = [ ] ( std : : string_view s ) { Log ( Debug : : Level : : Info ) < < s ; } ;
// Some fixes for compatibility between different Lua versions
if ( mLua [ " unpack " ] = = sol : : nil )
mLua [ " unpack " ] = mLua [ " table " ] [ " unpack " ] ;
else if ( mLua [ " table " ] [ " unpack " ] = = sol : : nil )
mLua [ " table " ] [ " unpack " ] = mLua [ " unpack " ] ;
if ( m Sol [ " unpack " ] = = sol : : nil )
m Sol[ " unpack " ] = mSol [ " table " ] [ " unpack " ] ;
else if ( m Sol [ " table " ] [ " unpack " ] = = sol : : nil )
m Sol [ " table " ] [ " unpack " ] = m Sol [ " unpack " ] ;
if ( LUA_VERSION_NUM < = 501 )
{
m Lua . script ( R " (
m Sol . script ( R " (
local _pairs = pairs
local _ipairs = ipairs
pairs = function ( v ) return ( rawget ( getmetatable ( v ) or { } , ' __pairs ' ) or _pairs ) ( v ) end
@ -167,7 +194,7 @@ namespace LuaUtil
) " );
}
m Lua . script ( R " (
m Sol . script ( R " (
local printToLog = function ( . . . )
local strs = { }
for i = 1 , select ( ' # ' , . . . ) do
@ -212,31 +239,24 @@ namespace LuaUtil
end
) " );
mSandboxEnv = sol : : table ( m Lua , sol : : create ) ;
mSandboxEnv [ " _VERSION " ] = m Lua [ " _VERSION " ] ;
mSandboxEnv = sol : : table ( m Sol , sol : : create ) ;
mSandboxEnv [ " _VERSION " ] = m Sol [ " _VERSION " ] ;
for ( const std : : string & s : safeFunctions )
{
if ( m Lua [ s ] = = sol : : nil )
if ( m Sol [ s ] = = sol : : nil )
throw std : : logic_error ( " Lua function not found: " + s ) ;
mSandboxEnv [ s ] = m Lua [ s ] ;
mSandboxEnv [ s ] = m Sol [ s ] ;
}
for ( const std : : string & s : safePackages )
{
if ( m Lua [ s ] = = sol : : nil )
if ( m Sol [ s ] = = sol : : nil )
throw std : : logic_error ( " Lua package not found: " + s ) ;
mCommonPackages [ s ] = mSandboxEnv [ s ] = makeReadOnly ( m Lua [ s ] ) ;
mCommonPackages [ s ] = mSandboxEnv [ s ] = makeReadOnly ( m Sol [ s ] ) ;
}
mSandboxEnv [ " getmetatable " ] = m Lua [ " getSafeMetatable " ] ;
mSandboxEnv [ " getmetatable " ] = m Sol [ " getSafeMetatable " ] ;
mCommonPackages [ " os " ] = mSandboxEnv [ " os " ]
= makeReadOnly ( tableFromPairs < std : : string_view , sol : : function > ( { { " date " , mLua [ " os " ] [ " date " ] } ,
{ " difftime " , mLua [ " os " ] [ " difftime " ] } , { " time " , mLua [ " os " ] [ " time " ] } } ) ) ;
}
LuaState : : ~ LuaState ( )
{
// Should be cleaned before destructing mLua.
mCommonPackages . clear ( ) ;
mSandboxEnv = sol : : nil ;
= makeReadOnly ( tableFromPairs < std : : string_view , sol : : function > ( { { " date " , mSol [ " os " ] [ " date " ] } ,
{ " difftime " , mSol [ " os " ] [ " difftime " ] } , { " time " , mSol [ " os " ] [ " time " ] } } ) ) ;
}
sol : : table makeReadOnly ( const sol : : table & table , bool strictIndex )
@ -280,9 +300,9 @@ namespace LuaUtil
{
sol : : protected_function script = loadScriptAndCache ( path ) ;
sol : : environment env ( m Lua , sol : : create , mSandboxEnv ) ;
sol : : environment env ( m Sol , sol : : create , mSandboxEnv ) ;
std : : string envName = namePrefix + " [ " + path + " ]: " ;
env [ " print " ] = m Lua [ " printGen " ] ( envName ) ;
env [ " print " ] = m Sol [ " printGen " ] ( envName ) ;
env [ " _G " ] = env ;
env [ sol : : metatable_key ] [ " __metatable " ] = false ;
@ -298,18 +318,18 @@ namespace LuaUtil
else
return package ;
} ;
sol : : table loaded ( m Lua , sol : : create ) ;
sol : : table loaded ( m Sol , sol : : create ) ;
for ( const auto & [ key , value ] : mCommonPackages )
loaded [ key ] = maybeRunLoader ( value ) ;
for ( const auto & [ key , value ] : packages )
loaded [ key ] = maybeRunLoader ( value ) ;
env [ " require " ] = [ this , env , loaded , hiddenData , scriptId ]( std : : string_view packageName ) mutable {
env [ " require " ] = [ this , env , loaded , hiddenData ]( std : : string_view packageName ) mutable {
sol : : object package = loaded [ packageName ] ;
if ( package ! = sol : : nil )
return package ;
sol : : protected_function packageLoader = loadScriptAndCache ( packageNameToVfsPath ( packageName , mVFS ) ) ;
sol : : set_environment ( env , packageLoader ) ;
package = call ( scriptId, packageLoader, packageName ) ;
package = call ( packageLoader, packageName ) ;
loaded [ packageName ] = package ;
return package ;
} ;
@ -320,8 +340,8 @@ namespace LuaUtil
sol : : environment LuaState : : newInternalLibEnvironment ( )
{
sol : : environment env ( m Lua , sol : : create , mSandboxEnv ) ;
sol : : table loaded ( m Lua , sol : : create ) ;
sol : : environment env ( m Sol , sol : : create , mSandboxEnv ) ;
sol : : table loaded ( m Sol , sol : : create ) ;
for ( const std : : string & s : safePackages )
loaded [ s ] = static_cast < sol : : object > ( mSandboxEnv [ s ] ) ;
env [ " require " ] = [ this , loaded , env ] ( const std : : string & module ) mutable {
@ -347,7 +367,7 @@ namespace LuaUtil
{
auto iter = mCompiledScripts . find ( path ) ;
if ( iter ! = mCompiledScripts . end ( ) )
return m Lua . load ( iter - > second . as_string_view ( ) , path , sol : : load_mode : : binary ) ;
return m Sol . load ( iter - > second . as_string_view ( ) , path , sol : : load_mode : : binary ) ;
sol : : function res = loadFromVFS ( path ) ;
mCompiledScripts [ path ] = res . dump ( ) ;
return res ;
@ -356,7 +376,7 @@ namespace LuaUtil
sol : : function LuaState : : loadFromVFS ( const std : : string & path )
{
std : : string fileContent ( std : : istreambuf_iterator < char > ( * mVFS - > get ( path ) ) , { } ) ;
sol : : load_result res = m Lua . load ( fileContent , path , sol : : load_mode : : text ) ;
sol : : load_result res = m Sol . load ( fileContent , path , sol : : load_mode : : text ) ;
if ( ! res . valid ( ) )
throw std : : runtime_error ( " Lua error: " + res . get < std : : string > ( ) ) ;
return res ;
@ -365,7 +385,7 @@ namespace LuaUtil
sol : : function LuaState : : loadInternalLib ( std : : string_view libName )
{
const auto path = packageNameToPath ( libName , mLibSearchPaths ) ;
sol : : load_result res = m Lua . load_file ( Files : : pathToUnicodeString ( path ) , sol : : load_mode : : text ) ;
sol : : load_result res = m Sol . load_file ( Files : : pathToUnicodeString ( path ) , sol : : load_mode : : text ) ;
if ( ! res . valid ( ) )
throw std : : runtime_error ( " Lua error: " + res . get < std : : string > ( ) ) ;
return res ;