github.com/bananabytelabs/wazero@v0.0.0-20240105073314-54b22a776da8/internal/testing/binaryencoding/encoder.go (about) 1 package binaryencoding 2 3 import ( 4 "github.com/bananabytelabs/wazero/internal/leb128" 5 "github.com/bananabytelabs/wazero/internal/wasm" 6 ) 7 8 var sizePrefixedName = []byte{4, 'n', 'a', 'm', 'e'} 9 10 // EncodeModule implements wasm.EncodeModule for the WebAssembly 1.0 (20191205) Binary Format. 11 // Note: If saving to a file, the conventional extension is wasm 12 // See https://www.w3.org/TR/2019/REC-wasm-core-1-20191205/#binary-format%E2%91%A0 13 func EncodeModule(m *wasm.Module) (bytes []byte) { 14 bytes = append(Magic, version...) 15 if m.SectionElementCount(wasm.SectionIDType) > 0 { 16 bytes = append(bytes, encodeTypeSection(m.TypeSection)...) 17 } 18 if m.SectionElementCount(wasm.SectionIDImport) > 0 { 19 bytes = append(bytes, encodeImportSection(m.ImportSection)...) 20 } 21 if m.SectionElementCount(wasm.SectionIDFunction) > 0 { 22 bytes = append(bytes, EncodeFunctionSection(m.FunctionSection)...) 23 } 24 if m.SectionElementCount(wasm.SectionIDTable) > 0 { 25 bytes = append(bytes, encodeTableSection(m.TableSection)...) 26 } 27 if m.SectionElementCount(wasm.SectionIDMemory) > 0 { 28 bytes = append(bytes, encodeMemorySection(m.MemorySection)...) 29 } 30 if m.SectionElementCount(wasm.SectionIDGlobal) > 0 { 31 bytes = append(bytes, encodeGlobalSection(m.GlobalSection)...) 32 } 33 if m.SectionElementCount(wasm.SectionIDExport) > 0 { 34 bytes = append(bytes, encodeExportSection(m.ExportSection)...) 35 } 36 if m.SectionElementCount(wasm.SectionIDStart) > 0 { 37 bytes = append(bytes, EncodeStartSection(*m.StartSection)...) 38 } 39 if m.SectionElementCount(wasm.SectionIDElement) > 0 { 40 bytes = append(bytes, encodeElementSection(m.ElementSection)...) 41 } 42 if m.SectionElementCount(wasm.SectionIDCode) > 0 { 43 bytes = append(bytes, encodeCodeSection(m.CodeSection)...) 44 } 45 if m.SectionElementCount(wasm.SectionIDData) > 0 { 46 bytes = append(bytes, encodeDataSection(m.DataSection)...) 47 } 48 if dc := m.DataCountSection; dc != nil { 49 bytes = append(bytes, encodeSection(wasm.SectionIDDataCount, leb128.EncodeUint32(*dc))...) 50 } 51 if m.SectionElementCount(wasm.SectionIDCustom) > 0 { 52 // >> The name section should appear only once in a module, and only after the data section. 53 // See https://www.w3.org/TR/2019/REC-wasm-core-1-20191205/#binary-namesec 54 if m.NameSection != nil { 55 nameSection := append(sizePrefixedName, EncodeNameSectionData(m.NameSection)...) 56 bytes = append(bytes, encodeSection(wasm.SectionIDCustom, nameSection)...) 57 } 58 for _, custom := range m.CustomSections { 59 bytes = append(bytes, encodeCustomSection(custom)...) 60 } 61 } 62 return 63 } 64 65 func encodeCustomSection(c *wasm.CustomSection) []byte { 66 content := append(leb128.EncodeUint32(uint32(len(c.Name))), c.Name...) 67 content = append(content, c.Data...) 68 return encodeSection(wasm.SectionIDCustom, content) 69 }