MCPcopy Create free account
hub / github.com/F-Stack/f-stack / scriptingEnableGlobalsProtection

Function scriptingEnableGlobalsProtection

app/redis-6.2.6/src/scripting.c:1087–1119  ·  view source on GitHub ↗

This function installs metamethods in the global table _G that prevent * the creation of globals accidentally. * * It should be the last to be called in the scripting engine initialization * sequence, because it may interact with creation of globals. */

Source from the content-addressed store, hash-verified

1085 * It should be the last to be called in the scripting engine initialization
1086 * sequence, because it may interact with creation of globals. */
1087void scriptingEnableGlobalsProtection(lua_State *lua) {
1088 char *s[32];
1089 sds code = sdsempty();
1090 int j = 0;
1091
1092 /* strict.lua from: http://metalua.luaforge.net/src/lib/strict.lua.html.
1093 * Modified to be adapted to Redis. */
1094 s[j++]="local dbg=debug\n";
1095 s[j++]="local mt = {}\n";
1096 s[j++]="setmetatable(_G, mt)\n";
1097 s[j++]="mt.__newindex = function (t, n, v)\n";
1098 s[j++]=" if dbg.getinfo(2) then\n";
1099 s[j++]=" local w = dbg.getinfo(2, \"S\").what\n";
1100 s[j++]=" if w ~= \"main\" and w ~= \"C\" then\n";
1101 s[j++]=" error(\"Script attempted to create global variable '\"..tostring(n)..\"'\", 2)\n";
1102 s[j++]=" end\n";
1103 s[j++]=" end\n";
1104 s[j++]=" rawset(t, n, v)\n";
1105 s[j++]="end\n";
1106 s[j++]="mt.__index = function (t, n)\n";
1107 s[j++]=" if dbg.getinfo(2) and dbg.getinfo(2, \"S\").what ~= \"C\" then\n";
1108 s[j++]=" error(\"Script attempted to access nonexistent global variable '\"..tostring(n)..\"'\", 2)\n";
1109 s[j++]=" end\n";
1110 s[j++]=" return rawget(t, n)\n";
1111 s[j++]="end\n";
1112 s[j++]="debug = nil\n";
1113 s[j++]=NULL;
1114
1115 for (j = 0; s[j] != NULL; j++) code = sdscatlen(code,s[j],strlen(s[j]));
1116 luaL_loadbuffer(lua,code,sdslen(code),"@enable_strict_lua");
1117 lua_pcall(lua,0,0,0);
1118 sdsfree(code);
1119}
1120
1121/* Initialize the scripting environment.
1122 *

Callers 1

scriptingInitFunction · 0.85

Calls 6

sdsemptyFunction · 0.85
sdscatlenFunction · 0.85
luaL_loadbufferFunction · 0.85
sdslenFunction · 0.85
lua_pcallFunction · 0.85
sdsfreeFunction · 0.85

Tested by

no test coverage detected