Add a hook to run the class/static constructor only once

This commit is contained in:
Volker Berlin 2022-03-06 14:27:33 +01:00
parent 28bf07567f
commit 097dfae696
2 changed files with 27 additions and 0 deletions

View File

@ -85,6 +85,15 @@ class JavaMethodWasmCodeBuilder extends WasmCodeBuilder {
reset( code.getLocalVariableTable(), method, null );
branchManager.reset( code );
if( "<clinit>".equals( method.getName() ) ) {
// Add a hook to run the class/static constructor only once
FunctionName name = new FunctionName( method.getClassName(), "<clisinit>", "" );
addGlobalInstruction( true, name, ValueType.i32, -1, -1 );
addBlockInstruction( WasmBlockOperator.BR_IF, 0, -1, -1 );
addConstInstruction( 1, ValueType.i32, -1, -1 );
addGlobalInstruction( false, name, ValueType.i32, -1, -1 );
}
byteCode = code.getByteCode();
AnyType returnType = new ValueTypeParser( method.getType().substring( method.getType().lastIndexOf( ')' ) + 1), getTypeManager() ).next();
writeCode( byteCode, code.getConstantPool(), method.getDeclaringClassFile(), returnType );

View File

@ -497,6 +497,24 @@ public abstract class WasmCodeBuilder {
protected void addGlobalInstruction( boolean load, Member ref, int javaCodePos, int lineNumber ) {
FunctionName name = new FunctionName( ref );
AnyType type = new ValueTypeParser( ref.getType(), types ).next();
addGlobalInstruction( load, name, type, javaCodePos, lineNumber );
}
/**
* Add a global instruction
*
* @param load
* true: if load
* @param name
* reference to a static field
* @param type
* the type of the static field
* @param javaCodePos
* the code position/offset in the Java method
* @param lineNumber
* the line number in the Java source code
*/
protected void addGlobalInstruction( boolean load, FunctionName name, AnyType type, int javaCodePos, int lineNumber ) {
instructions.add( new WasmGlobalInstruction( load, name, type, javaCodePos, lineNumber ) );
functions.markClassAsUsed( name.className );
}