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 @@ -953,8 +953,17 @@ public static ImExpr destroyClass(ExprDestroy s, ImTranslator t, ImFunction f, S
ImMethod destroyFunc = t.destroyMethod.getFor(classDef);
Expr destroyed = s.getDestroyedObj();
ImExpr receiver = destroyed.imTranslateExpr(t, f);
return ImMethodCall(s, destroyFunc, ImTypeArguments(erasedReceiverTypeArguments(destroyed, receiver, classDef, t)),
receiver, ImExprs(), false);
ImTypeArguments typeArgs = ImTypeArguments(erasedReceiverTypeArguments(destroyed, receiver, classDef, t));
if (!t.isLuaTarget() || !(receiver.attrTyp() instanceof ImClassType receiverType)) {
return ImMethodCall(s, destroyFunc, typeArgs, receiver, ImExprs(), false);
}
// Checked here, before the dispatch picks a destructor and before any ondestroy runs (LuaStaleDestroy).
ImVar object = JassIm.ImVar(s, receiverType, "destroyed", false);
f.getLocals().add(object);
ImStmts stmts = ImStmts(ImSet(s, ImVarAccess(object), receiver));
LuaStaleDestroy.addCheck(t, s, stmts, object, receiverType, classDef);
return JassIm.ImStatementExpr(stmts,
ImMethodCall(s, destroyFunc, typeArgs, ImVarAccess(object), ImExprs(), false));

}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,9 @@ public void visit(ImFunctionCall call) {
if (stubName == null) {
stubName = LuaCodeList.nativeStubFor(f);
}
if (stubName == null) {
stubName = LuaStaleDestroy.nativeStubFor(f);
}
if (stubName == null) {
return;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
package de.peeeq.wurstscript.translation.imtranslation;

import de.peeeq.wurstscript.WurstOperator;
import de.peeeq.wurstscript.ast.Expr;
import de.peeeq.wurstscript.ast.FuncDef;
import de.peeeq.wurstscript.ast.StructureDef;
import de.peeeq.wurstscript.jassIm.ImClassType;
import de.peeeq.wurstscript.jassIm.ImExpr;
import de.peeeq.wurstscript.jassIm.ImFunction;
import de.peeeq.wurstscript.jassIm.ImStmts;
import de.peeeq.wurstscript.jassIm.ImVar;
import de.peeeq.wurstscript.jassIm.JassIm;
import de.peeeq.wurstscript.parser.WPos;
import de.peeeq.wurstscript.types.TypesHelper;
import de.peeeq.wurstscript.types.WurstTypeString;

import java.util.Collections;

/**
* Refuses a destroy through a stale reference on Lua, and tells the map about it.
*
* <p>On Lua every class shares one id space and an allocation hands out the most recently freed id, so a reference
* kept past its object's destroy can name an object of any class later. A destroy through it would run that object's
* destructor and free its id while the object is still in use, and the next allocation would share the id. Each
* {@code destroy} therefore checks, before it dispatches and before any {@code ondestroy} runs, that its object is
* still an instance of the type the caller destroys it as. The receiver is evaluated once. When the check fails,
* {@code __wurst_staleDestroy} records {@code count|id|class|destroyed as|file:line} and raises; nothing is destroyed.
* An id that is free (a plain double destroy) passes on to the deallocator, which reports it as before.
*
* <p>Not covered: a stale reference whose id was reused by an object of the same class or a subclass passes, since
* the check sees only the class. Jass is not checked either: it keeps a connected id pool per class and interface
* group, so a stale reference there names an object of a related type, while Lua keeps one global allocator for all
* classes. This check does not make the two allocators agree.
*
* <p>A map reads the record through {@code staleDestroyReport() returns string}, matched by declaration like the list
* operations: the annotation, the name, no parameters and a string result, of a plain package function (see
* {@link IntrinsicDeclarations}). The source body is what Jass and an older compiler run, and should answer "".
*/
public final class LuaStaleDestroy {

private static final String REPORT = "staleDestroyReport";

/** The stub name whose Lua body lives in {@code LuaNatives}. */
public static final String NATIVE_REPORT = "__wurst_staleDestroyReport";

/** The check's failure path, whose Lua body lives in {@code LuaNatives}. */
public static final String NATIVE_CHECK = "__wurst_staleDestroy";

/** The global the failure path writes the record to and the report reads. */
public static final String RECORD = "__wurst_staleDestroyRecord";

/** The global counting the stale destroys. */
public static final String COUNT = "__wurst_staleDestroyCount";

private LuaStaleDestroy() {
}

/** The {@code __wurst_} stub {@code f} is lowered to on Lua, or null if it is not the report. */
public static String nativeStubFor(ImFunction f) {
FuncDef fd = IntrinsicDeclarations.plainIntrinsic(f);
if (fd == null || !REPORT.equals(fd.getName())) {
return null;
}
return f.getParameters().isEmpty() && TypesHelper.isStringType(f.getReturnType()) ? NATIVE_REPORT : null;
}

/**
* Adds to {@code stmts} the check of {@code object}, a local the destroyed object was evaluated into, against
* {@code type}, the type the caller destroys it as.
*/
static void addCheck(ImTranslator t, Expr trace, ImStmts stmts, ImVar object, ImClassType type,
StructureDef destroyedAs) {
ImExpr notNull = JassIm.ImOperatorCall(WurstOperator.NOTEQ,
JassIm.ImExprs(JassIm.ImVarAccess(object), JassIm.ImNull(object.getType())));
// The class alone, without its type arguments: a parameterized instanceof observes the identity of an
// instantiation and makes EliminateGenerics specialise for it, which a check must not change. Every
// instantiation of an erased class is an instance of the class.
ImClassType erased = JassIm.ImClassType(type.getClassDef(), JassIm.ImTypeArguments());
ImExpr notInstance = JassIm.ImOperatorCall(WurstOperator.NOT,
JassIm.ImExprs(JassIm.ImInstanceof(JassIm.ImVarAccess(object), erased)));
ImExpr fails = JassIm.ImOperatorCall(WurstOperator.AND, JassIm.ImExprs(notNull, notInstance));
// The site is added by the Lua translation, from the call's trace: a cached function keeps its IM
// across an edit that moves it, while its traces are refreshed.
stmts.add(JassIm.ImIf(trace, fails, JassIm.ImStmts(JassIm.ImFunctionCall(trace, checkStub(t, trace),
JassIm.ImTypeArguments(), JassIm.ImExprs(JassIm.ImVarAccess(object),
JassIm.ImStringVal(destroyedAs.getName())), false, CallType.NORMAL)),
JassIm.ImStmts()));
}

/** {@code File.wurst:line} of {@code trace}, without the checkout path. */
public static String site(de.peeeq.wurstscript.ast.Element trace) {
WPos pos = trace.attrSource();
String file = pos.getFile().replace('\\', '/');
return file.substring(file.lastIndexOf('/') + 1) + ":" + pos.getLine();
}

private static ImFunction checkStub(ImTranslator t, Expr trace) {
for (ImFunction f : t.getImProg().getFunctions()) {
if (f.getName().equals(NATIVE_CHECK) && f.isNative()) {
return f;
}
}
ImFunction stub = JassIm.ImFunction(trace, NATIVE_CHECK, JassIm.ImTypeVars(),
JassIm.ImVars(JassIm.ImVar(trace, JassIm.ImAnyType(), "object", false),
JassIm.ImVar(trace, WurstTypeString.instance().imTranslateType(t), "expected", false)),
JassIm.ImVoid(), JassIm.ImVars(), JassIm.ImStmts(), Collections.singletonList(FunctionFlagEnum.IS_NATIVE));
t.getImProg().getFunctions().add(stub);
return stub;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import de.peeeq.wurstscript.attributes.CompileError;
import de.peeeq.wurstscript.jassIm.*;
import de.peeeq.wurstscript.luaAst.*;
import de.peeeq.wurstscript.translation.imtranslation.LuaStaleDestroy;
import de.peeeq.wurstscript.translation.imtranslation.EliminateLocalTypes;
import de.peeeq.wurstscript.translation.imtranslation.ImTranslator;
import de.peeeq.wurstscript.translation.imtranslation.LuaHashtable;
Expand All @@ -24,6 +25,8 @@ public class ExprTranslation {

public static final String TYPE_ID = "__typeId__";
public static final String WURST_SUPERTYPES = "__wurst_supertypes";
/** The class name on a class table, which the error of a stale destroy reports. */
public static final String WURST_CLASS_NAME = "__wurst_className";
static final String WURST_ABORT_THREAD_SENTINEL = "__wurst_abort_thread";
private static final Set<String> LUA_HANDLE_TO_INDEX = Set.of(
"widgetToIndex", "unitToIndex", "destructableToIndex", "itemToIndex", "abilityToIndex",
Expand Down Expand Up @@ -86,6 +89,9 @@ static String callErrorFunc(LuaTranslator tr, String msg, String stackPos) {
}

public static LuaExpr translate(ImFunctionCall e, LuaTranslator tr) {
if (LuaStaleDestroy.NATIVE_CHECK.equals(e.getFunc().getName()) && e.getFunc().isNative()) {
return staleDestroyCheck(e, tr);
}
// String concatenation is lowered to imTr.stringConcatFunc at the IM level
// (see EliminateLocalTypes). It is a plain, portable, uniquely-named IM
// function now (see LuaEnsureFunctions), so it needs no special-casing
Expand Down Expand Up @@ -618,6 +624,18 @@ public void visit(ImExitwhen exitwhen) {
LuaAst.LuaExprlist());
}

/** The check of a destroy (LuaStaleDestroy), given its site here, from the call's current trace. */
private static LuaExpr staleDestroyCheck(ImFunctionCall e, LuaTranslator tr) {
LuaExpr object = e.getArguments().get(0).translateToLua(tr);
ImStringVal expected = (ImStringVal) e.getArguments().get(1);
LuaExprStringVal site = LuaAst.LuaExprStringVal(LuaStaleDestroy.site(e.attrTrace()));
if (tr.isHotReload()) {
tr.stackPositions.add(site);
}
return LuaAst.LuaExprFunctionCall(tr.luaFunc.getFor(e.getFunc()),
LuaAst.LuaExprlist(object, LuaAst.LuaExprStringVal(expected.getValS()), site));
}

public static LuaExpr translate(ImStringVal e, LuaTranslator tr) {
LuaExprStringVal result = LuaAst.LuaExprStringVal(e.getValS());
if (tr.isHotReload() && isStackPosition(e)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -781,7 +781,7 @@ private static Statement statement(LuaTranslator tr, String scope, String owner,
revision = withoutPositions(tr, s);
if (a.getLeft() instanceof LuaExprFieldAccess field && (a.getRight() instanceof LuaExprFuncRef
|| field.getFieldName().equals(ExprTranslation.WURST_SUPERTYPES))) {
// A class's supertypes are read only by instanceof, when it runs, so a changed table is assigned again
// A class's supertypes are read only by instanceof and destroy, when they run, so a changed table is assigned again
// as a slot is bound again: objects made before then answer for the class as it is now.
kind = "slot";
} else if (!scope.equals("init") && a.getLeft() instanceof LuaExprVarAccess target && globals.contains(target.getVar())) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import de.peeeq.wurstscript.luaAst.LuaFunction;
import de.peeeq.wurstscript.luaAst.LuaVariable;
import de.peeeq.wurstscript.translation.imtranslation.LuaHashtable;
import de.peeeq.wurstscript.translation.imtranslation.LuaStaleDestroy;
import org.eclipse.jdt.annotation.Nullable;

import java.util.Arrays;
Expand Down Expand Up @@ -252,6 +253,23 @@ public class LuaNatives {
// as it is behind a trigger.
f.getBody().add(LuaAst.LuaLiteral("local i = 1 local c = t[1] while c do c() i = i + 1 c = t[i] end"));
});
addNative(LuaStaleDestroy.NATIVE_CHECK, f -> {
f.getParams().add(LuaAst.LuaVariable("object", LuaAst.LuaNoExpr()));
f.getParams().add(LuaAst.LuaVariable("expected", LuaAst.LuaNoExpr()));
f.getParams().add(LuaAst.LuaVariable("site", LuaAst.LuaNoExpr()));
// A free id is a double destroy, which the deallocator reports as before.
String count = LuaStaleDestroy.COUNT;
String actual = "descriptor." + ExprTranslation.WURST_CLASS_NAME;
f.getBody().add(LuaAst.LuaLiteral("local descriptor = __wurst_objectClass[object] "
+ "if descriptor == nil then return end "
+ count + " = (" + count + " or 0) + 1 "
+ LuaStaleDestroy.RECORD + " = " + count + " .. \"|\" .. object .. \"|\" .. " + actual
+ " .. \"|\" .. expected .. \"|\" .. site "
+ "error(\"Stale destroy: object \" .. object .. \" is a \" .. " + actual
+ " .. \", destroyed as a \" .. expected .. \" at \" .. site)"));
});
addNative(LuaStaleDestroy.NATIVE_REPORT, f ->
f.getBody().add(LuaAst.LuaLiteral("return " + LuaStaleDestroy.RECORD + " or \"\"")));
addNative("__wurst_keyedMapDestroy", f -> {
f.getParams().add(LuaAst.LuaVariable("t", LuaAst.LuaNoExpr()));
// The owner may still be reachable through an alias after destroy, so clear this table
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import de.peeeq.wurstscript.translation.imtranslation.ImTranslator;
import de.peeeq.wurstscript.translation.imtranslation.LuaFieldDefaults;
import de.peeeq.wurstscript.translation.imtranslation.LuaHashtable;
import de.peeeq.wurstscript.translation.imtranslation.LuaStaleDestroy;
import de.peeeq.wurstscript.translation.imtranslation.GenericTypes;
import de.peeeq.wurstscript.translation.imtranslation.LuaDispatchPreparation;
import de.peeeq.wurstscript.translation.imtranslation.LuaMultipleResults;
Expand All @@ -28,6 +29,7 @@
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static de.peeeq.wurstscript.translation.lua.translation.ExprTranslation.WURST_CLASS_NAME;
import static de.peeeq.wurstscript.translation.lua.translation.ExprTranslation.WURST_SUPERTYPES;

public class LuaTranslator {
Expand Down Expand Up @@ -1176,6 +1178,9 @@ public void visit(ImFunctionCall e) {
if (LuaReflection.isReflectionNative(e.getFunc())) {
reflectionCalls.add(e);
}
if (LuaStaleDestroy.NATIVE_CHECK.equals(e.getFunc().getName())) {
namesClasses = true;
}
}
});
if (reflectionCalls.isEmpty()) {
Expand Down Expand Up @@ -1203,6 +1208,8 @@ private void createInstanceOfFunction() {
private Map<ImClass, Set<ImVar>> fieldDefaultsOnAllocation = Collections.emptyMap();
/** Whether the program has an {@code instanceof}, the only reader of a class table's supertypes. */
private boolean readsSupertypes;
/** A destroy checks the class of its object (LuaStaleDestroy), whose report names the classes. */
private boolean namesClasses;
/** Whether the program reads the type id of an object, the only reader of a class table's type id. */
private boolean readsObjectTypeId;
/** The natives of {@code Reflection}, null when the program calls none. */
Expand Down Expand Up @@ -1967,6 +1974,13 @@ private void initClassTables(ImClass c) {
LuaAst.LuaTableConstructor(superClasses)
));
}
if (namesClasses) {
deferMainInit(LuaAst.LuaAssignment(LuaAst.LuaExprFieldAccess(
LuaAst.LuaExprVarAccess(classVar),
WURST_CLASS_NAME),
LuaAst.LuaExprStringVal(imTr.canonical(c).getName())
));
}

// set typeid metadata:
if (readsObjectTypeId) {
Expand Down
Loading
Loading