@@ -55,6 +55,8 @@ public class BinaryModuleWriter extends ModuleWriter implements InstructionOpcod
5555
5656 private Map <String , Function > functions = new LinkedHashMap <>();
5757
58+ private Map <String , Global > globals = new LinkedHashMap <>();
59+
5860 private Map <String , String > exports = new LinkedHashMap <>();
5961
6062 private Map <String , ImportFunction > imports = new LinkedHashMap <>();
@@ -86,6 +88,7 @@ public void close() throws IOException {
8688 writeTypeSection ();
8789 writeImportSection ();
8890 writeFunctionSection ();
91+ writeGlobalSection ();
8992 writeExportSection ();
9093 writeCodeSection ();
9194
@@ -163,6 +166,27 @@ private void writeFunctionSection() throws IOException {
163166 }
164167 }
165168
169+ /**
170+ * Write the global section to the output. This section contains a declaring of global (static) variables.
171+ *
172+ * @throws IOException
173+ * if any I/O error occur
174+ */
175+ private void writeGlobalSection () throws IOException {
176+ int count = globals .size ();
177+ if ( count > 0 ) {
178+ WasmOutputStream stream = new WasmOutputStream ();
179+ stream .writeVaruint32 ( count );
180+ for ( Global var : globals .values () ) {
181+ stream .write ( var .type .getCode () );
182+ stream .write ( var .mutability ? 1 : 0 );
183+ writeConst ( stream , 0 , var .type );
184+ stream .writeOpCode ( END );
185+ }
186+ wasm .writeSection ( SectionType .Global , stream , null );
187+ }
188+ }
189+
166190 /**
167191 * Write the export section to the output. This section contains a mapping from the external index to the type signature index.
168192 *
@@ -307,6 +331,22 @@ protected void writeMethodFinish( List<ValueType> locals ) throws IOException {
307331 */
308332 @ Override
309333 protected void writeConst ( Number value , ValueType valueType ) throws IOException {
334+ writeConst ( codeStream , value , valueType );
335+ }
336+
337+ /**
338+ * Write a constant number value
339+ *
340+ * @param codeStream
341+ * the target stream
342+ * @param value
343+ * the value
344+ * @param valueType
345+ * the data type of the number
346+ * @throws IOException
347+ * if any I/O error occur
348+ */
349+ private static void writeConst ( WasmOutputStream codeStream , Number value , ValueType valueType ) throws IOException {
310350 switch ( valueType ) {
311351 case i32 :
312352 codeStream .writeOpCode ( I32_CONST );
0 commit comments