MCPcopy Create free account
hub / github.com/Snapchat/KeyDB / scriptingEnableGlobalsProtection

Function scriptingEnableGlobalsProtection

src/scripting.cpp:1103–1135  ·  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

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

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