Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -1479,7 +1479,11 @@ private static void appendRuntime(LuaTranslator tr, LuaCompilationUnit model, St
model.add(LuaAst.LuaLiteral(KEPT_INITIALIZERS + " = {}"));
model.add(LuaAst.LuaLiteral(CONSTANT_VALUES + " = {}"));
model.add(LuaAst.LuaLiteral(CONSTANT_LENGTHS + " = {}"));
model.add(LuaAst.LuaLiteral(String.join("\n",
// With -stacktraces the code a payload runs pushes frames, and an install which fails (the init of a package it
// adds raises) never pops them: the depth is put back after it, as after each hook.
LuaVariable depthVar = tr.stackTraceDepth();
String depth = depthVar == null ? null : depthVar.getName();
List<String> apply = new ArrayList<>(List.of(
"function " + APPLY_FUNCTION + "(source)",
" local chunk, err = load(source, \"=wurst hot reload\", \"t\", _ENV)",
" if not chunk then return false, err end",
Expand All @@ -1492,14 +1496,22 @@ private static void appendRuntime(LuaTranslator tr, LuaCompilationUnit model, St
" return false, \"payload \" .. tostring(version) .. \" is not newer than \" .. " + VERSION_GLOBAL,
" end",
" " + WARNINGS + " = {}",
" " + CURRENT_BATCH + " = version",
" local installed, installErr = pcall(install)",
" " + CURRENT_BATCH + " = version"));
if (depth != null) {
apply.add(" local depth = " + depth);
}
apply.add(" local installed, installErr = pcall(install)");
if (depth != null) {
apply.add(" " + depth + " = depth");
}
apply.addAll(List.of(
" if not installed then",
" return false, \"the payload failed while it was installed, so the map may run old and new bodies: \" .. tostring(installErr)",
" end",
" " + VERSION_GLOBAL + " = version",
" return true",
"end")));
"end"));
model.add(LuaAst.LuaLiteral(String.join("\n", apply)));
model.add(LuaAst.LuaLiteral(WARNINGS + " = {}"));
model.add(LuaAst.LuaLiteral(String.join("\n",
"function " + WARN_FUNCTION + "(text)",
Expand All @@ -1510,12 +1522,6 @@ private static void appendRuntime(LuaTranslator tr, LuaCompilationUnit model, St
"end")));
// A hook takes no parameters but, with -stacktraces, the position of its call, as every function does; without,
// Lua drops the argument. The frames a failing hook pushed are never popped, so the depth is put back after it.
String depth = null;
for (ImVar v : tr.imTr.stackTraceStorage) {
if (!(v.getType() instanceof ImArrayType)) {
depth = tr.luaVar.getFor(v).getName();
}
}
List<String> runHook = new ArrayList<>(List.of("function " + HOOK_FUNCTION + "(hook, name)"));
if (depth != null) {
runHook.add(" local depth = " + depth);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -713,8 +713,20 @@ LuaFunction callbackAdapterFor(ImFunction target) {
xpcallArgs.add(LuaAst.LuaExprVarAccess(dots));
}
LuaExprFunctionCallByName xpcall = LuaAst.LuaExprFunctionCallByName("xpcall", xpcallArgs);
// With -stacktraces a raising target leaves the frames it and its callees pushed: xpcall unwinds past their
// pops. The handler still has to see them, and it runs before the unwind, so the depth is put back after
// xpcall returns. A target called synchronously inside another instrumented function (ForGroup, pcall)
// returns to that function's depth, which is the depth on entry here. Jass cannot catch, so a crashed Jass
// thread leaves the depth raised as well; there the difference is in the runtime, not in the translation.
LuaVariable depth = stackTraceDepth();
LuaVariable savedDepth = null;
if (depth != null) {
savedDepth = LuaAst.LuaVariable("__wurst_depth", LuaAst.LuaExprVarAccess(depth));
adapter.getBody().add(savedDepth);
}
if (target.getReturnType() instanceof ImVoid) {
adapter.getBody().add(xpcall);
restoreStackTraceDepth(adapter, depth, savedDepth);
} else {
// Keep exactly the first callback result. Returning select(2, xpcall(...)) directly
// could leak additional Lua return values into a surrounding argument list.
Expand All @@ -724,12 +736,31 @@ LuaFunction callbackAdapterFor(ImFunction target) {
adapter.getBody().add(result);
adapter.getBody().add(LuaAst.LuaAssignment(
LuaAst.LuaLiteral("_, result"), xpcall));
restoreStackTraceDepth(adapter, depth, savedDepth);
adapter.getBody().add(LuaAst.LuaReturn(LuaAst.LuaExprVarAccess(result)));
}
luaModel.add(adapter);
return adapter;
}

private static void restoreStackTraceDepth(LuaFunction adapter, @Nullable LuaVariable depth,
@Nullable LuaVariable savedDepth) {
if (depth != null && savedDepth != null) {
adapter.getBody().add(LuaAst.LuaAssignment(LuaAst.LuaExprVarAccess(depth),
LuaAst.LuaExprVarAccess(savedDepth)));
}
}

/** The global holding the stack-trace depth ({@code StackTraceInjector2}) in a {@code -stacktraces} build, else null. */
@Nullable LuaVariable stackTraceDepth() {
for (ImVar v : imTr.stackTraceStorage) {
if (!(v.getType() instanceof ImArrayType)) {
return luaVar.getFor(v);
}
}
return null;
}

private LuaFunction callbackErrorHandler() {
if (callbackErrorHandler != null) {
return callbackErrorHandler;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -182,11 +182,26 @@ private static void emitLuaInitXpcall(ImFunction initFunc, List<LuaStatement> re
String packageName = tr.imTr.luaInitFunctions.getOrDefault(initFunc, "?");
// no local/do-block: locals hidden in literals are invisible to the
// 200-locals accounting in enforceLuaLocalLimits
// With -stacktraces a raising init leaves the frames it pushed, as a raising callback does
// (LuaTranslator.callbackAdapterFor): the depth is put back after xpcall, once the handler has printed them.
// Package inits run one after another, never nested, so one global holds the depth. Jass cannot catch:
// a crashed Jass init leaves its frames too.
LuaVariable depth = tr.stackTraceDepth();
String depthName = depth == null ? null : depth.getName();
if (depthName != null) {
res.add(LuaAst.LuaLiteral(INIT_DEPTH + " = " + depthName));
}
res.add(LuaAst.LuaLiteral("if not xpcall(" + funcName + ", " + tr.initErrorHandler().getName() + ") then"));
if (depthName != null) {
res.add(LuaAst.LuaLiteral(" " + depthName + " = " + INIT_DEPTH));
}
res.add(LuaAst.LuaLiteral(" " + ExprTranslation.callErrorFunc(tr, "\"Could not initialize package " + packageName + ".\"")));
res.add(LuaAst.LuaLiteral("end"));
}

/** The stack-trace depth before the package init which runs, in a {@code -stacktraces} build. */
private static final String INIT_DEPTH = "__wurst_initStackDepth";

public static void translate(ImExitwhen s, List<LuaStatement> res, LuaTranslator tr) {
LuaIf r = LuaAst.LuaIf(s.getCondition().translateToLua(tr),
LuaAst.LuaStatements(LuaAst.LuaBreak()),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7548,6 +7548,142 @@ public void callbackAdapterOfANullaryTargetTakesNoVarargs() throws IOException {
java.util.regex.Pattern.compile("function __wurst_callback_\\w+\\(\\.\\.\\.\\)").matcher(compiled).find());
}

/**
* With -stacktraces, a callback that raises leaves the frames it pushed: xpcall unwinds past their pops. The
* adapter puts the depth back after xpcall, so a later trace has none of them. Measured from inside an
* instrumented function which runs the callback synchronously, as ForGroup does, for an ordinary Lua error and for
* the thread abort, which the error handler does not report.
*/
@Test
public void raisingCallbackLeavesNoStackFramesBehind() {
test().testLua(true).stacktraces().executeProg().lines(
"package Test",
"native testSuccess()",
"native testFail(string msg)",
"native I2S(int i) returns string",
"@extern native pcall(code callback) returns bool",
"@extern native assert(boolean b)",
"function getStackTraceString() returns string",
" return \"\"",
"string array traces",
"function boom()",
" assert(false)",
"function abortThread()",
" I2S(1 div 0)",
"function failWithError()",
" boom()",
"function failWithAbort()",
" abortThread()",
"function snapshot() returns string",
" return getStackTraceString()",
"function measure(int which) returns string",
" if which == 1",
" pcall(function failWithError)",
" else if which == 2",
" pcall(function failWithAbort)",
" return snapshot()",
"init",
" for i = 0 to 2",
" traces[i] = measure(i)",
" if traces[1] != traces[0]",
" testFail(\"an error left frames: \" + traces[1] + \" instead of \" + traces[0])",
" else if traces[2] != traces[0]",
" testFail(\"an abort left frames: \" + traces[2] + \" instead of \" + traces[0])",
" else",
" testSuccess()");
}

/** The same for a package init that raises: the next init's trace has none of its frames. */
@Test
public void raisingPackageInitLeavesNoStackFramesBehind() throws Exception {
String name = "raisingPackageInitLeavesNoStackFramesBehind";
test().testLua(true).stacktraces().lines(
"package Probe",
"native I2S(int i) returns string",
"@extern native print(string s)",
"@extern native assert(boolean b)",
"function getStackTraceString() returns string",
" return \"\"",
"function snapshot() returns string",
" return getStackTraceString()",
"public function report()",
" print(\"#trace\" + snapshot())",
"public function boom()",
" assert(false)",
"public function abortThread()",
" I2S(1 div 0)",
"endpackage",
"package First", "import Probe", "init", " report()", "endpackage",
"package BrokenByError", "import Probe", "init", " boom()", "endpackage",
"package BrokenByAbort", "import Probe", "init", " abortThread()", "endpackage",
"package Last", "import First", "import BrokenByError", "import BrokenByAbort", "import Probe", "init",
" report()", "endpackage");
String luaExecutable;
try {
luaExecutable = getLuaExecutable();
} catch (IllegalStateException e) {
throw new org.testng.SkipException("Skipped the Lua run (luac checked the script): " + e.getMessage());
}
StringBuilder chunk = new StringBuilder();
for (String runtimeFile : new String[]{"wc3shim.lua", "common.j.lua", "blizzard.j.lua"}) {
chunk.append("dofile('").append(new File("src/test/resources/luaruntime", runtimeFile).getPath()
.replace('\\', '/')).append("');");
}
chunk.append("dofile('").append(new File(TEST_OUTPUT_PATH, "lua/LuaBackendAuditTests_" + name + ".lua")
.getPath().replace('\\', '/')).append("'); main()");
Process p = new ProcessBuilder(luaExecutable, "-e", chunk.toString()).redirectErrorStream(true).start();
String output = new String(p.getInputStream().readAllBytes(), java.nio.charset.StandardCharsets.UTF_8).replace("\r\n", "\n");
assertEquals(output, 0, p.waitFor());
List<String> traces = new ArrayList<>();
for (String block : output.split("#trace")) {
if (block.startsWith(" Stacktrace:")) {
// A trace ends where the next line printed without indentation starts.
StringBuilder trace = new StringBuilder();
for (String line : block.split("\n")) {
if (!trace.isEmpty() && !line.startsWith(" ")) {
break;
}
trace.append(line).append("\n");
}
traces.add(trace.toString());
}
}
assertEquals(output, 2, traces.size());
assertTrue(output, output.contains("lua init error"));
// Last runs after both broken inits; First may too (the init order follows the dependencies only).
for (String trace : traces) {
assertFalse(output, trace.contains("boom") || trace.contains("abortThread"));
}
assertEquals(output, traces.get(0).split("\n").length, traces.get(1).split("\n").length);
}

/** Without -stacktraces there is no depth to keep, and the adapters are what they were. */
@Test
public void callbackAdapterWithoutStacktracesKeepsNoDepth() throws IOException {
test().testLua(true).executeProg().lines(
"package Test",
"native testSuccess()",
"@extern native pcall(code callback) returns bool",
"int calls = 0",
"function tick()",
" calls++",
"function tickAndAccept() returns boolean",
" calls++",
" return true",
"init",
" if pcall(function tick) and pcall(function tickAndAccept) and calls == 2",
" testSuccess()");
String compiled = compiledLua("callbackAdapterWithoutStacktracesKeepsNoDepth");
assertTrue(compiled, java.util.regex.Pattern.compile(
"function __wurst_callback_tick\\w*\\(\\) \\n\\txpcall\\(tick\\w*, __wurst_callback_error\\w*\\)\\nend\\n")
.matcher(compiled).find());
assertTrue(compiled, java.util.regex.Pattern.compile(
"function __wurst_callback_tickAndAccept\\w*\\(\\) \\n\\tlocal _\\n\\tlocal result\\n"
+ "\\t_, result = xpcall\\(tickAndAccept\\w*, __wurst_callback_error\\w*\\)\\n\\treturn result\\nend\\n")
.matcher(compiled).find());
assertFalse(compiled, compiled.contains("depth") || compiled.contains("wurst_stack"));
}

/**
* Reading a never-written array slot must not permanently store an entry
* for it - merely probing a sparse array would otherwise grow it
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2459,6 +2459,32 @@ public void failingReloadHookLeavesNoFramesBehind() throws Exception {
assertFalse(output, output.contains("explode"));
}

/**
* A payload whose install fails (here the init of a package it adds raises) leaves the -stacktraces stack as it
* found it: the frames the init pushed are not in the traces the map takes after.
*/
@Test
public void failedInstallLeavesNoFramesBehind() throws Exception {
RunArgs traced = HOT_RELOAD.with("-stacktraces");
String name = "failedInstallLeavesNoFramesBehind";
String[] base = concat(MAIN_PACKAGE, new String[] {
"function getStackTraceString() returns string", " return \"\"",
"public function traceNow() returns string", " return getStackTraceString()",
"init", " traceNow()"});
String[] added = concat(base, new String[] {"endpackage",
"package Broken", "import Main", "native I2S(int i) returns string",
"function explode()", " I2S(1 div 0)", "init", " explode()"});
test().testLua(true).stacktraces().luaHotReload(base).lines(base);
LuaHotReload.Manifest before = compileLuaHotReloadManifest(false, traced, new CU(name, String.join("\n", base) + "\n"));
LuaHotReload.Manifest after = compileLuaHotReloadManifest(false, traced, new CU(name, String.join("\n", added) + "\n"));
String output = applyInLua("test-output/lua/LuaHotReloadTests_" + name + ".lua",
List.of(LuaHotReload.payload(before, after, LuaHotReload.History.NONE, 1).source()),
luaName(before, "traceNow") + "('after the payload')").replace("\r\n", "\n");
assertTrue(output, output.startsWith("false "));
assertTrue(output, output.contains("after the payload"));
assertFalse(output, output.contains("explode"));
}

/** A hook is called with nothing, so it has no type arguments either. */
@Test
public void reloadHookIsNotGeneric() {
Expand Down
Loading