diff --git a/src/de/inetsoftware/jwebassembly/module/JavaMethodWasmCodeBuilder.java b/src/de/inetsoftware/jwebassembly/module/JavaMethodWasmCodeBuilder.java index 5378d5d..f5a8789 100644 --- a/src/de/inetsoftware/jwebassembly/module/JavaMethodWasmCodeBuilder.java +++ b/src/de/inetsoftware/jwebassembly/module/JavaMethodWasmCodeBuilder.java @@ -85,6 +85,15 @@ class JavaMethodWasmCodeBuilder extends WasmCodeBuilder { reset( code.getLocalVariableTable(), method, null ); branchManager.reset( code ); + if( "".equals( method.getName() ) ) { + // Add a hook to run the class/static constructor only once + FunctionName name = new FunctionName( method.getClassName(), "", "" ); + 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 ); diff --git a/src/de/inetsoftware/jwebassembly/module/WasmCodeBuilder.java b/src/de/inetsoftware/jwebassembly/module/WasmCodeBuilder.java index 2d13aeb..3954b2a 100644 --- a/src/de/inetsoftware/jwebassembly/module/WasmCodeBuilder.java +++ b/src/de/inetsoftware/jwebassembly/module/WasmCodeBuilder.java @@ -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 ); }