wasmer

package
v0.1.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 16, 2023 License: MIT Imports: 8 Imported by: 0

Documentation

Overview

Package wasmer is a complete and mature WebAssembly runtime for Go based on Wasmer (https://github.com/wasmerio/wasmer).

Features

• Easy to use: The wasmer API mimics the standard WebAssembly API,

• Fast: wasmer executes the WebAssembly modules as fast as possible, close to native speed,

• Safe: All calls to WebAssembly will be fast, but more importantly, complete safe and sandboxed.

Quick Introduction

The wasmer Go package brings the required API to execute WebAssembly modules. In a nutshell, wasmer compiles the WebAssembly module into compiled code, and then executes it. wasmer is designed to work in various environments and platforms: From nano single-board computers to large and powerful servers, including more exotic ones. To address those requirements, Wasmer provides 2 engines and 3 compilers.

Succinctly, an engine is responsible to drive the compilation and the execution of a WebAssembly module. By extension, a headless engine can only execute a WebAssembly module, i.e. a module that has previously been compiled, or compiled, serialized and deserialized. By default, the wasmer package comes with 2 headless engines:

• Universal, the compiled machine code lives in memory,

• Dylib, the compiled machine code lives in a shared object file (.so, .dylib, or .dll), and is natively executed.

The wasmer Go packages comes with 3 compilers:

• Singlepass: Super fast compilation times, slower execution times. Not prone to JIT-bombs. Ideal for blockchains.

• Cranelift: Fast compilation times, fast execution times. Ideal for development.

• LLVM: Slow compilation times, very fast execution times (close to native). Ideal for production.

WebAssembly C API standard

Wasmer —the runtime— is written in Rust; C and C++ bindings exist. This Go package relies on the so-called wasm_c_api, https://github.com/WebAssembly/wasm-c-api, which is the new standard C API, implemented inside Wasmer as the Wasmer C API, https://wasmerio.github.io/wasmer/crates/wasmer_c_api/. This standard is characterized as a living standard. The API is not yet stable, even though it shows maturity overtime. However, the Wasmer C API provides some extensions, like the wasi_* or wasmer_* types and functions, which aren't yet defined by the standard. The Go package commits to keep a semantic versioning over the API, regardless what happens with the C API.

Examples

The very basic example is the following

// Let's assume we don't have WebAssembly bytes at hand. We
// will write WebAssembly manually.
wasmBytes := []byte(`
	(module
	  (type (func (param i32 i32) (result i32)))
	  (func (type 0)
	    local.get 0
	    local.get 1
	    i32.add)
	  (export "sum" (func 0)))
`)

// Create an Engine
engine := wasmer.NewEngine()

// Create a Store
store := wasmer.NewStore(engine)

// Let's compile the module.
module, err := wasmer.NewModule(store, wasmBytes)

if err != nil {
	fmt.Println("Failed to compile module:", err)
}

// Create an empty import object.
importObject := wasmer.NewImportObject()

// Let's instantiate the WebAssembly module.
instance, err := wasmer.NewInstance(module, importObject)

if err != nil {
	panic(fmt.Sprintln("Failed to instantiate the module:", err))
}

// Now let's execute the `sum` function.
sum, err := instance.Exports.GetFunction("sum")

if err != nil {
	panic(fmt.Sprintln("Failed to get the `add_one` function:", err))
}

result, err := sum(1, 2)

if err != nil {
	panic(fmt.Sprintln("Failed to call the `add_one` function:", err))
}

fmt.Println("Results of `sum`:", result)

// Output:
// Results of `sum`: 3

That's it. Now explore the API! Some pointers for the adventurers:

• The basic elements are Module and Instance,

• Exports of an instance are represented by the Exports type,

• Maybe your module needs to import Function, Memory, Global or Table? Well, there is the ImportObject for that!

Index

Constants

View Source
const (
	// Represents the Cranelift compiler.
	CRANELIFT = CompilerKind(C.CRANELIFT)

	// Represents the LLVM compiler.
	LLVM = CompilerKind(C.LLVM)

	// Represents the Singlepass compiler.
	SINGLEPASS = CompilerKind(C.SINGLEPASS)
)
View Source
const (
	Unreachable        Opcode = 0
	Nop                       = 1
	Block                     = 2
	Loop                      = 3
	If                        = 4
	Else                      = 5
	Try                       = 6
	Catch                     = 7
	CatchAll                  = 8
	Delegate                  = 9
	Throw                     = 10
	Rethrow                   = 11
	Unwind                    = 12
	End                       = 13
	Br                        = 14
	BrIf                      = 15
	BrTable                   = 16
	Return                    = 17
	Call                      = 18
	CallIndirect              = 19
	ReturnCall                = 20
	ReturnCallIndirect        = 21
	Drop                      = 22
	Select                    = 23
	TypedSelect               = 24
	LocalGet                  = 25
	LocalSet                  = 26
	LocalTee                  = 27
	GlobalGet                 = 28
	GlobalSet                 = 29
	I32Load                   = 30
	I64Load                   = 31
	F32Load                   = 32
	F64Load                   = 33
	I32Load8S                 = 34
	I32Load8U                 = 35
	I32Load16S                = 36
	I32Load16U                = 37
	I64Load8S                 = 38
	I64Load8U                 = 39
	I64Load16S                = 40
	I64Load16U                = 41
	I64Load32S                = 42
	I64Load32U                = 43
	I32Store                  = 44
	I64Store                  = 45
	F32Store                  = 46
	F64Store                  = 47
	I32Store8                 = 48
	I32Store16                = 49
	I64Store8                 = 50
	I64Store16                = 51
	I64Store32                = 52
	MemorySize                = 53
	MemoryGrow                = 54
	I32Const                  = 55
	I64Const                  = 56
	F32Const                  = 57
	F64Const                  = 58
	RefNull                   = 59
	RefIsNull                 = 60
	RefFunc                   = 61
	I32Eqz                    = 62
	I32Eq                     = 63
	I32Ne                     = 64
	I32LtS                    = 65
	I32LtU                    = 66
	I32GtS                    = 67
	I32GtU                    = 68
	I32LeS                    = 69
	I32LeU                    = 70
	I32GeS                    = 71
	I32GeU                    = 72
	I64Eqz                    = 73
	I64Eq                     = 74
	I64Ne                     = 75
	I64LtS                    = 76
	I64LtU                    = 77
	I64GtS                    = 78
	I64GtU                    = 79
	I64LeS                    = 80
	I64LeU                    = 81
	I64GeS                    = 82
	I64GeU                    = 83
	F32Eq                     = 84
	F32Ne                     = 85
	F32Lt                     = 86
	F32Gt                     = 87
	F32Le                     = 88
	F32Ge                     = 89
	F64Eq                     = 90
	F64Ne                     = 91
	F64Lt                     = 92
	F64Gt                     = 93
	F64Le                     = 94
	F64Ge                     = 95
	I32Clz                    = 96
	I32Ctz                    = 97
	I32Popcnt                 = 98
	I32Add                    = 99
	I32Sub                    = 100
	I32Mul                    = 101
	I32DivS                   = 102
	I32DivU                   = 103
	I32RemS                   = 104
	I32RemU                   = 105
	I32And                    = 106
	I32Or                     = 107
	I32Xor                    = 108
	I32Shl                    = 109
	I32ShrS                   = 110
	I32ShrU                   = 111
	I32Rotl                   = 112
	I32Rotr                   = 113
	I64Clz                    = 114
	I64Ctz                    = 115
	I64Popcnt                 = 116
	I64Add                    = 117
	I64Sub                    = 118
	I64Mul                    = 119
	I64DivS                   = 120
	I64DivU                   = 121
	I64RemS                   = 122
	I64RemU                   = 123
	I64And                    = 124
	I64Or                     = 125
	I64Xor                    = 126
	I64Shl                    = 127
	I64ShrS                   = 128
	I64ShrU                   = 129
	I64Rotl                   = 130
	I64Rotr                   = 131
	F32Abs                    = 132
	F32Neg                    = 133
	F32Ceil                   = 134
	F32Floor                  = 135
	F32Trunc                  = 136
	F32Nearest                = 137
	F32Sqrt                   = 138
	F32Add                    = 139
	F32Sub                    = 140
	F32Mul                    = 141
	F32Div                    = 142
	F32Min                    = 143
	F32Max                    = 144
	F32Copysign               = 145
	F64Abs                    = 146
	F64Neg                    = 147
	F64Ceil                   = 148
	F64Floor                  = 149
	F64Trunc                  = 150
	F64Nearest                = 151
	F64Sqrt                   = 152
	F64Add                    = 153
	F64Sub                    = 154
	F64Mul                    = 155
	F64Div                    = 156
	F64Min                    = 157
	F64Max                    = 158
	F64Copysign               = 159
	I32WrapI64                = 160
	I32TruncF32S              = 161
	I32TruncF32U              = 162
	I32TruncF64S              = 163
	I32TruncF64U              = 164
	I64ExtendI32S             = 165
	I64ExtendI32U             = 166
	I64TruncF32S              = 167
	I64TruncF32U              = 168
	I64TruncF64S              = 169
	I64TruncF64U              = 170
	F32ConvertI32S            = 171
	F32ConvertI32U            = 172
	F32ConvertI64S            = 173
	F32ConvertI64U            = 174
	F32DemoteF64              = 175
	F64ConvertI32S            = 176
	F64ConvertI32U            = 177
	F64ConvertI64S            = 178
	F64ConvertI64U            = 179
	F64PromoteF32             = 180
	I32ReinterpretF32         = 181
	I64ReinterpretF64         = 182
	F32ReinterpretI32         = 183
	F64ReinterpretI64         = 184
	I32Extend8S               = 185
	I32Extend16S              = 186
	I64Extend8S               = 187
	I64Extend16S              = 188
	I64Extend32S              = 189
	I32TruncSatF32S           = 190
	I32TruncSatF32U           = 191
	I32TruncSatF64S           = 192
	I32TruncSatF64U           = 193
	I64TruncSatF32S           = 194
	I64TruncSatF32U           = 195
	I64TruncSatF64S           = 196
	I64TruncSatF64U           = 197
	MemoryInit                = 198
	DataDrop                  = 199
	MemoryCopy                = 200
	MemoryFill                = 201
	TableInit                 = 202
	ElemDrop                  = 203
	TableCopy                 = 204
	TableFill                 = 205
	TableGet                  = 206
	TableSet                  = 207
	TableGrow                 = 208
	// REVIEW
	OpTableSize               = 209
	MemoryAtomicNotify        = 210
	MemoryAtomicWait32        = 211
	MemoryAtomicWait64        = 212
	AtomicFence               = 213
	I32AtomicLoad             = 214
	I64AtomicLoad             = 215
	I32AtomicLoad8U           = 216
	I32AtomicLoad16U          = 217
	I64AtomicLoad8U           = 218
	I64AtomicLoad16U          = 219
	I64AtomicLoad32U          = 220
	I32AtomicStore            = 221
	I64AtomicStore            = 222
	I32AtomicStore8           = 223
	I32AtomicStore16          = 224
	I64AtomicStore8           = 225
	I64AtomicStore16          = 226
	I64AtomicStore32          = 227
	I32AtomicRmwAdd           = 228
	I64AtomicRmwAdd           = 229
	I32AtomicRmw8AddU         = 230
	I32AtomicRmw16AddU        = 231
	I64AtomicRmw8AddU         = 232
	I64AtomicRmw16AddU        = 233
	I64AtomicRmw32AddU        = 234
	I32AtomicRmwSub           = 235
	I64AtomicRmwSub           = 236
	I32AtomicRmw8SubU         = 237
	I32AtomicRmw16SubU        = 238
	I64AtomicRmw8SubU         = 239
	I64AtomicRmw16SubU        = 240
	I64AtomicRmw32SubU        = 241
	I32AtomicRmwAnd           = 242
	I64AtomicRmwAnd           = 243
	I32AtomicRmw8AndU         = 244
	I32AtomicRmw16AndU        = 245
	I64AtomicRmw8AndU         = 246
	I64AtomicRmw16AndU        = 247
	I64AtomicRmw32AndU        = 248
	I32AtomicRmwOr            = 249
	I64AtomicRmwOr            = 250
	I32AtomicRmw8OrU          = 251
	I32AtomicRmw16OrU         = 252
	I64AtomicRmw8OrU          = 253
	I64AtomicRmw16OrU         = 254
	I64AtomicRmw32OrU         = 255
	I32AtomicRmwXor           = 256
	I64AtomicRmwXor           = 257
	I32AtomicRmw8XorU         = 258
	I32AtomicRmw16XorU        = 259
	I64AtomicRmw8XorU         = 260
	I64AtomicRmw16XorU        = 261
	I64AtomicRmw32XorU        = 262
	I32AtomicRmwXchg          = 263
	I64AtomicRmwXchg          = 264
	I32AtomicRmw8XchgU        = 265
	I32AtomicRmw16XchgU       = 266
	I64AtomicRmw8XchgU        = 267
	I64AtomicRmw16XchgU       = 268
	I64AtomicRmw32XchgU       = 269
	I32AtomicRmwCmpxchg       = 270
	I64AtomicRmwCmpxchg       = 271
	I32AtomicRmw8CmpxchgU     = 272
	I32AtomicRmw16CmpxchgU    = 273
	I64AtomicRmw8CmpxchgU     = 274
	I64AtomicRmw16CmpxchgU    = 275
	I64AtomicRmw32CmpxchgU    = 276
	V128Load                  = 277
	V128Store                 = 278
	V128Const                 = 279
	I8x16Splat                = 280
	I8x16ExtractLaneS         = 281
	I8x16ExtractLaneU         = 282
	I8x16ReplaceLane          = 283
	I16x8Splat                = 284
	I16x8ExtractLaneS         = 285
	I16x8ExtractLaneU         = 286
	I16x8ReplaceLane          = 287
	I32x4Splat                = 288
	I32x4ExtractLane          = 289
	I32x4ReplaceLane          = 290
	I64x2Splat                = 291
	I64x2ExtractLane          = 292
	I64x2ReplaceLane          = 293
	F32x4Splat                = 294
	F32x4ExtractLane          = 295
	F32x4ReplaceLane          = 296
	F64x2Splat                = 297
	F64x2ExtractLane          = 298
	F64x2ReplaceLane          = 299
	I8x16Eq                   = 300
	I8x16Ne                   = 301
	I8x16LtS                  = 302
	I8x16LtU                  = 303
	I8x16GtS                  = 304
	I8x16GtU                  = 305
	I8x16LeS                  = 306
	I8x16LeU                  = 307
	I8x16GeS                  = 308
	I8x16GeU                  = 309
	I16x8Eq                   = 310
	I16x8Ne                   = 311
	I16x8LtS                  = 312
	I16x8LtU                  = 313
	I16x8GtS                  = 314
	I16x8GtU                  = 315
	I16x8LeS                  = 316
	I16x8LeU                  = 317
	I16x8GeS                  = 318
	I16x8GeU                  = 319
	I32x4Eq                   = 320
	I32x4Ne                   = 321
	I32x4LtS                  = 322
	I32x4LtU                  = 323
	I32x4GtS                  = 324
	I32x4GtU                  = 325
	I32x4LeS                  = 326
	I32x4LeU                  = 327
	I32x4GeS                  = 328
	I32x4GeU                  = 329
	I64x2Eq                   = 330
	I64x2Ne                   = 331
	I64x2LtS                  = 332
	I64x2GtS                  = 333
	I64x2LeS                  = 334
	I64x2GeS                  = 335
	F32x4Eq                   = 336
	F32x4Ne                   = 337
	F32x4Lt                   = 338
	F32x4Gt                   = 339
	F32x4Le                   = 340
	F32x4Ge                   = 341
	F64x2Eq                   = 342
	F64x2Ne                   = 343
	F64x2Lt                   = 344
	F64x2Gt                   = 345
	F64x2Le                   = 346
	F64x2Ge                   = 347
	V128Not                   = 348
	V128And                   = 349
	V128AndNot                = 350
	V128Or                    = 351
	V128Xor                   = 352
	V128Bitselect             = 353
	V128AnyTrue               = 354
	I8x16Abs                  = 355
	I8x16Neg                  = 356
	I8x16AllTrue              = 357
	I8x16Bitmask              = 358
	I8x16Shl                  = 359
	I8x16ShrS                 = 360
	I8x16ShrU                 = 361
	I8x16Add                  = 362
	I8x16AddSatS              = 363
	I8x16AddSatU              = 364
	I8x16Sub                  = 365
	I8x16SubSatS              = 366
	I8x16SubSatU              = 367
	I8x16MinS                 = 368
	I8x16MinU                 = 369
	I8x16MaxS                 = 370
	I8x16MaxU                 = 371
	I8x16Popcnt               = 372
	I16x8Abs                  = 373
	I16x8Neg                  = 374
	I16x8AllTrue              = 375
	I16x8Bitmask              = 376
	I16x8Shl                  = 377
	I16x8ShrS                 = 378
	I16x8ShrU                 = 379
	I16x8Add                  = 380
	I16x8AddSatS              = 381
	I16x8AddSatU              = 382
	I16x8Sub                  = 383
	I16x8SubSatS              = 384
	I16x8SubSatU              = 385
	I16x8Mul                  = 386
	I16x8MinS                 = 387
	I16x8MinU                 = 388
	I16x8MaxS                 = 389
	I16x8MaxU                 = 390
	I16x8ExtAddPairwiseI8x16S = 391
	I16x8ExtAddPairwiseI8x16U = 392
	I32x4Abs                  = 393
	I32x4Neg                  = 394
	I32x4AllTrue              = 395
	I32x4Bitmask              = 396
	I32x4Shl                  = 397
	I32x4ShrS                 = 398
	I32x4ShrU                 = 399
	I32x4Add                  = 400
	I32x4Sub                  = 401
	I32x4Mul                  = 402
	I32x4MinS                 = 403
	I32x4MinU                 = 404
	I32x4MaxS                 = 405
	I32x4MaxU                 = 406
	I32x4DotI16x8S            = 407
	I32x4ExtAddPairwiseI16x8S = 408
	I32x4ExtAddPairwiseI16x8U = 409
	I64x2Abs                  = 410
	I64x2Neg                  = 411
	I64x2AllTrue              = 412
	I64x2Bitmask              = 413
	I64x2Shl                  = 414
	I64x2ShrS                 = 415
	I64x2ShrU                 = 416
	I64x2Add                  = 417
	I64x2Sub                  = 418
	I64x2Mul                  = 419
	F32x4Ceil                 = 420
	F32x4Floor                = 421
	F32x4Trunc                = 422
	F32x4Nearest              = 423
	F64x2Ceil                 = 424
	F64x2Floor                = 425
	F64x2Trunc                = 426
	F64x2Nearest              = 427
	F32x4Abs                  = 428
	F32x4Neg                  = 429
	F32x4Sqrt                 = 430
	F32x4Add                  = 431
	F32x4Sub                  = 432
	F32x4Mul                  = 433
	F32x4Div                  = 434
	F32x4Min                  = 435
	F32x4Max                  = 436
	F32x4PMin                 = 437
	F32x4PMax                 = 438
	F64x2Abs                  = 439
	F64x2Neg                  = 440
	F64x2Sqrt                 = 441
	F64x2Add                  = 442
	F64x2Sub                  = 443
	F64x2Mul                  = 444
	F64x2Div                  = 445
	F64x2Min                  = 446
	F64x2Max                  = 447
	F64x2PMin                 = 448
	F64x2PMax                 = 449
	I32x4TruncSatF32x4S       = 450
	I32x4TruncSatF32x4U       = 451
	F32x4ConvertI32x4S        = 452
	F32x4ConvertI32x4U        = 453
	I8x16Swizzle              = 454
	I8x16Shuffle              = 455
	V128Load8Splat            = 456
	V128Load16Splat           = 457
	V128Load32Splat           = 458
	V128Load32Zero            = 459
	V128Load64Splat           = 460
	V128Load64Zero            = 461
	I8x16NarrowI16x8S         = 462
	I8x16NarrowI16x8U         = 463
	I16x8NarrowI32x4S         = 464
	I16x8NarrowI32x4U         = 465
	I16x8ExtendLowI8x16S      = 466
	I16x8ExtendHighI8x16S     = 467
	I16x8ExtendLowI8x16U      = 468
	I16x8ExtendHighI8x16U     = 469
	I32x4ExtendLowI16x8S      = 470
	I32x4ExtendHighI16x8S     = 471
	I32x4ExtendLowI16x8U      = 472
	I32x4ExtendHighI16x8U     = 473
	I64x2ExtendLowI32x4S      = 474
	I64x2ExtendHighI32x4S     = 475
	I64x2ExtendLowI32x4U      = 476
	I64x2ExtendHighI32x4U     = 477
	I16x8ExtMulLowI8x16S      = 478
	I16x8ExtMulHighI8x16S     = 479
	I16x8ExtMulLowI8x16U      = 480
	I16x8ExtMulHighI8x16U     = 481
	I32x4ExtMulLowI16x8S      = 482
	I32x4ExtMulHighI16x8S     = 483
	I32x4ExtMulLowI16x8U      = 484
	I32x4ExtMulHighI16x8U     = 485
	I64x2ExtMulLowI32x4S      = 486
	I64x2ExtMulHighI32x4S     = 487
	I64x2ExtMulLowI32x4U      = 488
	I64x2ExtMulHighI32x4U     = 489
	V128Load8x8S              = 490
	V128Load8x8U              = 491
	V128Load16x4S             = 492
	V128Load16x4U             = 493
	V128Load32x2S             = 494
	V128Load32x2U             = 495
	V128Load8Lane             = 496
	V128Load16Lane            = 497
	V128Load32Lane            = 498
	V128Load64Lane            = 499
	V128Store8Lane            = 500
	V128Store16Lane           = 501
	V128Store32Lane           = 502
	V128Store64Lane           = 503
	I8x16RoundingAverageU     = 504
	I16x8RoundingAverageU     = 505
	I16x8Q15MulrSatS          = 506
	F32x4DemoteF64x2Zero      = 507
	F64x2PromoteLowF32x4      = 508
	F64x2ConvertLowI32x4S     = 509
	F64x2ConvertLowI32x4U     = 510
	I32x4TruncSatF64x2SZero   = 511
	I32x4TruncSatF64x2UZero   = 512
)
View Source
const (
	// Represents an extern of kind function.
	FUNCTION = ExternKind(C.WASM_EXTERN_FUNC)

	// Represents an extern of kind global.
	GLOBAL = ExternKind(C.WASM_EXTERN_GLOBAL)

	// Represents an extern of kind table.
	TABLE = ExternKind(C.WASM_EXTERN_TABLE)

	// Represents an extern of kind memory.
	MEMORY = ExternKind(C.WASM_EXTERN_MEMORY)
)
View Source
const (
	// Represents a global that is immutable.
	IMMUTABLE = GlobalMutability(C.WASM_CONST)

	// Represents a global that is mutable.
	MUTABLE = GlobalMutability(C.WASM_VAR)
)
View Source
const (
	// A 32-bit integer. In WebAssembly, integers are
	// sign-agnostic, i.E. this can either be signed or unsigned.
	I32 = ValueKind(C.WASM_I32)

	// A 64-bit integer. In WebAssembly, integers are
	// sign-agnostic, i.E. this can either be signed or unsigned.
	I64 = ValueKind(C.WASM_I64)

	// A 32-bit float.
	F32 = ValueKind(C.WASM_F32)

	// A 64-bit float.
	F64 = ValueKind(C.WASM_F64)

	// An externref value which can hold opaque data to the
	// WebAssembly instance itself.
	AnyRef = ValueKind(C.WASM_ANYREF)

	// A first-class reference to a WebAssembly function.
	FuncRef = ValueKind(C.WASM_FUNCREF)
)
View Source
const (
	// Latest version. It's a “floating” version, i.e. it's an
	// alias to the latest version. Using this version is a way to
	// ensure that modules will run only if they come with the
	// latest WASI version (in case of security issues for
	// instance), by just updating the runtime.
	WASI_VERSION_LATEST = WasiVersion(C.LATEST)

	// Represents the wasi_unstable version.
	WASI_VERSION_SNAPSHOT0 = WasiVersion(C.SNAPSHOT0)

	// Represents the wasi_snapshot_preview1 version.
	WASI_VERSION_SNAPSHOT1 = WasiVersion(C.SNAPSHOT1)

	// Represents an invalid version.
	WASI_VERSION_INVALID = WasiVersion(C.INVALID_VERSION)
)
View Source
const (
	// Represents the Universal engine.
	UNIVERSAL = EngineKind(C.UNIVERSAL)
)
View Source
const WasmMaxPages = uint(0x10000)

Represents the maximum number of pages.

View Source
const WasmMinPages = uint(0x100)

Represents the minimum number of pages.

View Source
const WasmPageSize = uint(0x10000)

Represents a memory page size.

Variables

This section is empty.

Functions

func IsCompilerAvailable

func IsCompilerAvailable(compiler CompilerKind) bool

IsCompilerAvailable checks that the given compiler is available in this current version of `wasmer-go`.

IsCompilerAvailable(CRANELIFT)

func IsEngineAvailable

func IsEngineAvailable(engine EngineKind) bool

IsEngineAvailable checks that the given engine is available in this current version of `wasmer-go`.

IsEngineAvailable(UNIVERSAL)

func LimitMaxUnbound

func LimitMaxUnbound() uint32

LimitMaxUnbound returns the value used to represent an unbound limit, i.e. when a limit only has a min but not a max. See Limit.

func ValidateModule

func ValidateModule(store *Store, bytes []byte) error

ValidateModule validates a new Module against the given Store.

It takes two arguments, the Store and the WebAssembly module as a byte array. The function returns an error describing why the bytes are invalid, otherwise it returns nil.

wasmBytes := []byte(`...`)
engine := wasmer.NewEngine()
store := wasmer.NewStore(engine)
err := wasmer.ValidateModule(store, wasmBytes)

isValid := err != nil

func Wat2Wasm

func Wat2Wasm(wat string) ([]byte, error)

Wat2Wasm parses a string as either WAT code or a binary Wasm module.

See https://webassembly.github.io/spec/core/text/index.html.

Note: This is not part of the standard Wasm C API. It is Wasmer specific.

wat := "(module)"
wasm, _ := Wat2Wasm(wat)
engine := wasmer.NewEngine()
store := wasmer.NewStore(engine)
module, _ := wasmer.NewModule(store, wasmBytes)

Types

type CompilerKind

type CompilerKind C.wasmer_compiler_t

CompilerKind represents the possible compiler types.

func (CompilerKind) String

func (self CompilerKind) String() string

Strings returns the CompilerKind as a string.

CRANELIFT.String() // "cranelift"
LLVM.String() // "llvm"

type Config

type Config struct {
	// contains filtered or unexported fields
}

Config holds the compiler and the Engine used by the Store.

func NewConfig

func NewConfig() *Config

NewConfig instantiates and returns a new Config.

config := NewConfig()

func (*Config) PushMeteringMiddleware

func (self *Config) PushMeteringMiddleware(maxGasUsageAllowed uint64, opMap map[Opcode]uint32) *Config

PushMeteringMiddleware allows the middleware metering to be engaged on a map of opcode to cost

  config := NewConfig()
	 opmap := map[uint32]uint32{
		End: 		1,
		LocalGet: 	1,
		I32Add: 	4,
	 }
  config.PushMeteringMiddleware(7865444, opmap)

func (*Config) PushMeteringMiddlewarePtr

func (self *Config) PushMeteringMiddlewarePtr(maxGasUsageAllowed uint64, p unsafe.Pointer) *Config

PushMeteringMiddlewarePtr allows the middleware metering to be engaged on an unsafe.Pointer this pointer must be a to C based function with a signature of:

extern uint64_t cost_delegate_func(enum wasmer_parser_operator_t op);

package main

#include <wasmer.h> extern uint64_t metering_delegate_alt(enum wasmer_parser_operator_t op); import "C" import "unsafe"

func getInternalCPointer() unsafe.Pointer {
	  return unsafe.Pointer(C.metering_delegate_alt)
}

//export metering_delegate_alt

func metering_delegate_alt(op C.wasmer_parser_operator_t) C.uint64_t {
	v, b := opCodeMap[Opcode(op)]
  if !b {
	   return 0 // no value means no cost
  }
  return C.uint64_t(v)
}

void main(){
   config := NewConfig()
   config.PushMeteringMiddlewarePtr(800000000, getInternalCPointer())
}

func (*Config) UseCraneliftCompiler

func (self *Config) UseCraneliftCompiler() *Config

UseCraneliftCompiler sets the compiler to Cranelift in the configuration.

config := NewConfig()
config.UseCraneliftCompiler()

This method might fail if the Cranelift compiler isn't available. Check `IsCompilerAvailable` to learn more.

func (*Config) UseLLVMCompiler

func (self *Config) UseLLVMCompiler() *Config

UseLLVMCompiler sets the compiler to LLVM in the configuration.

config := NewConfig()
config.UseLLVMCompiler()

This method might fail if the LLVM compiler isn't available. Check `IsCompilerAvailable` to learn more.

func (*Config) UseSinglepassCompiler

func (self *Config) UseSinglepassCompiler() *Config

UseSinglepassCompiler sets the compiler to Singlepass in the configuration.

config := NewConfig()
config.UseSinglepassCompiler()

This method might fail if the Singlepass compiler isn't available. Check `IsCompilerAvailable` to learn more.

func (*Config) UseTarget

func (self *Config) UseTarget(target *Target) *Config

Use a specific target for doing cross-compilation.

triple, _ := NewTriple("aarch64-unknown-linux-gnu")
cpuFeatures := NewCpuFeatures()
target := NewTarget(triple, cpuFeatures)

config := NewConfig()
config.UseTarget(target)

func (*Config) UseUniversalEngine

func (self *Config) UseUniversalEngine() *Config

UseNativeEngine sets the engine to Universal in the configuration.

config := NewConfig()
config.UseUniversalEngine()

This method might fail if the Universal engine isn't available. Check `IsEngineAvailable` to learn more.

type CpuFeatures

type CpuFeatures struct {
	// contains filtered or unexported fields
}

CpuFeatures holds a set of CPU features. They are identified by their stringified names. The reference is the GCC options:

https://gcc.gnu.org/onlinedocs/gcc/x86-Options.html,

https://gcc.gnu.org/onlinedocs/gcc/ARM-Options.html,

https://gcc.gnu.org/onlinedocs/gcc/AArch64-Options.html.

At the time of writing this documentation (it might be outdated in the future), the supported featurse are the following:

• sse2,

• sse3,

• ssse3,

• sse4.1,

• sse4.2,

• popcnt,

• avx,

• bmi,

• bmi2,

• avx2,

• avx512dq,

• avx512vl,

• lzcnt.

func NewCpuFeatures

func NewCpuFeatures() *CpuFeatures

NewCpuFeatures creates a new CpuFeatures, which is a set of CPU features.

func (*CpuFeatures) Add

func (self *CpuFeatures) Add(feature string) error

Add adds a new CPU feature to the existing set.

type Engine

type Engine struct {
	// contains filtered or unexported fields
}

Engine is used by the Store to drive the compilation and the execution of a WebAssembly module.

func NewEngine

func NewEngine() *Engine

NewEngine instantiates and returns a new Engine with the default configuration.

engine := NewEngine()

func NewEngineWithConfig

func NewEngineWithConfig(config *Config) *Engine

NewEngineWithConfig instantiates and returns a new Engine with the given configuration.

config := NewConfig()
engine := NewEngineWithConfig(config)

func NewUniversalEngine

func NewUniversalEngine() *Engine

NewUniversalEngine instantiates and returns a new Universal engine.

engine := NewUniversalEngine()

type EngineKind

type EngineKind C.wasmer_engine_t

EngineKind represents the possible engine types.

func (EngineKind) String

func (self EngineKind) String() string

Strings returns the EngineKind as a string.

JIT.String() // "jit"
NATIVE.String() // "native"

type Error

type Error struct {
	// contains filtered or unexported fields
}

Error represents a Wasmer runtime error.

func (*Error) Error

func (error *Error) Error() string

Error returns the Error's message.

type ExportType

type ExportType struct {
	// contains filtered or unexported fields
}

ExportType is a descriptor for an exported WebAssembly value.

func NewExportType

func NewExportType(name string, ty IntoExternType) *ExportType

NewExportType instantiates a new ExportType with a name and an extern type.

Note: An extern type is anything implementing IntoExternType: FunctionType, GlobalType, MemoryType, TableType.

valueType := NewValueType(I32)
globalType := NewGlobalType(valueType, CONST)
exportType := NewExportType("a_global", globalType)

func (*ExportType) Close

func (self *ExportType) Close()

Force to close the ExportType.

A runtime finalizer is registered on the ExportType, but it is possible to force the destruction of the ExportType by calling Close manually.

func (*ExportType) Name

func (self *ExportType) Name() string

Name returns the name of the export type.

exportType := NewExportType("a_global", globalType)
exportType.Name() // "global"

func (*ExportType) Type

func (self *ExportType) Type() *ExternType

Type returns the type of the export type.

exportType := NewExportType("a_global", globalType)
exportType.Type() // ExternType

type Exports

type Exports struct {
	// contains filtered or unexported fields
}

Exports is a special kind of map that allows easily unwrapping the types of instances.

func (*Exports) Close

func (self *Exports) Close()

Force to close the Exports.

A runtime finalizer is registered on the Exports, but it is possible to force the destruction of the Exports by calling Close manually.

func (*Exports) Get

func (self *Exports) Get(name string) (*Extern, error)

Get retrieves and returns an Extern by its name.

Note: If the name does not refer to an existing export, Get will return an Error.

instance, _ := NewInstance(module, NewImportObject())
extern, error := instance.Exports.Get("an_export")

func (*Exports) GetFunction

func (self *Exports) GetFunction(name string) (NativeFunction, error)

GetFunction retrieves a exported function by its name and returns it as a native Go function.

The difference with GetRawFunction is that Function.Native has been called on the exported function.

Note: If the name does not refer to an existing export, GetFunction will return an Error.

Note: If the export is not a function, GetFunction will return nil as its result.

instance, _ := NewInstance(module, NewImportObject())
exportedFunc, error := instance.Exports.GetFunction("an_exported_function")

if error != nil && exportedFunc != nil {
    exportedFunc()
}

func (*Exports) GetGlobal

func (self *Exports) GetGlobal(name string) (*Global, error)

GetGlobal retrieves and returns a exported Global by its name.

Note: If the name does not refer to an existing export, GetGlobal will return an Error.

Note: If the export is not a global, GetGlobal will return nil as a result.

instance, _ := NewInstance(module, NewImportObject())
exportedGlobal, error := instance.Exports.GetGlobal("an_exported_global")

func (*Exports) GetMemory

func (self *Exports) GetMemory(name string) (*Memory, error)

GetMemory retrieves and returns a exported Memory by its name.

Note: If the name does not refer to an existing export, GetMemory will return an Error.

Note: If the export is not a memory, GetMemory will return nil as a result.

instance, _ := NewInstance(module, NewImportObject())
exportedMemory, error := instance.Exports.GetMemory("an_exported_memory")

func (*Exports) GetRawFunction

func (self *Exports) GetRawFunction(name string) (*Function, error)

GetRawFunction retrieves and returns an exported Function by its name.

Note: If the name does not refer to an existing export, GetRawFunction will return an Error.

Note: If the export is not a function, GetRawFunction will return nil as its result.

instance, _ := NewInstance(module, NewImportObject())
exportedFunc, error := instance.Exports.GetRawFunction("an_exported_function")

if error != nil && exportedFunc != nil {
    exportedFunc.Call()
}

func (*Exports) GetTable

func (self *Exports) GetTable(name string) (*Table, error)

GetTable retrieves and returns a exported Table by its name.

Note: If the name does not refer to an existing export, GetTable will return an Error.

Note: If the export is not a table, GetTable will return nil as a result.

instance, _ := NewInstance(module, NewImportObject())
exportedTable, error := instance.Exports.GetTable("an_exported_table")

func (*Exports) GetWasiStartFunction

func (self *Exports) GetWasiStartFunction() (NativeFunction, error)

GetWasiStartFunction is similar to GetFunction("_start"). It saves you the cost of knowing the name of the WASI start function.

type Extern

type Extern struct {
	// contains filtered or unexported fields
}

Extern is the runtime representation of an entity that can be imported or exported.

func (*Extern) IntoExtern

func (self *Extern) IntoExtern() *Extern

func (*Extern) IntoFunction

func (self *Extern) IntoFunction() *Function

IntoFunction converts the Extern into a Function.

Note:️ If the Extern is not a Function, IntoFunction will return nil as its result.

function, _ := instance.Exports.GetFunction("exported_function")
extern = function.IntoExtern()
_ := extern.IntoFunction()

func (*Extern) IntoGlobal

func (self *Extern) IntoGlobal() *Global

IntoGlobal converts the Extern into a Global.

Note:️ If the Extern is not a Global, IntoGlobal will return nil as its result.

global, _ := instance.Exports.GetGlobal("exported_global")
extern = global.IntoExtern()
_ := extern.IntoGlobal()

func (*Extern) IntoMemory

func (self *Extern) IntoMemory() *Memory

IntoMemory converts the Extern into a Memory.

Note:️ If the Extern is not a Memory, IntoMemory will return nil as its result.

memory, _ := instance.Exports.GetMemory("exported_memory")
extern = memory.IntoExtern()
_ := extern.IntoMemory()

func (*Extern) IntoTable

func (self *Extern) IntoTable() *Table

IntoTable converts the Extern into a Table.

Note:️ If the Extern is not a Table, IntoTable will return nil as its result.

table, _ := instance.Exports.GetTable("exported_table")
extern = table.IntoExtern()
_ := extern.IntoTable()

func (*Extern) Kind

func (self *Extern) Kind() ExternKind

Kind returns the Extern's ExternKind.

global, _ := instance.Exports.GetGlobal("exported_global")
_ = global.IntoExtern().Kind()

func (*Extern) Type

func (self *Extern) Type() *ExternType

Type returns the Extern's ExternType.

global, _ := instance.Exports.GetGlobal("exported_global")
_ = global.IntoExtern().Type()

type ExternKind

type ExternKind C.wasm_externkind_t

Represents the kind of an Extern.

func (ExternKind) String

func (self ExternKind) String() string

String returns the ExternKind as a string.

FUNCTION.String() // "func"
GLOBAL.String()   // "global"
TABLE.String()    // "table"
MEMORY.String()   // "memory"

type ExternType

type ExternType struct {
	// contains filtered or unexported fields
}

ExternType classifies imports and external values with their respective types.

See also

Specification: https://webassembly.github.io/spec/core/syntax/types.html#external-types

func (*ExternType) IntoFunctionType

func (self *ExternType) IntoFunctionType() *FunctionType

IntoFunctionType converts the ExternType into a FunctionType.

Note:️ If the ExternType is not a FunctionType, IntoFunctionType will return nil as its result.

function, _ := instance.Exports.GetFunction("exported_function")
externType = function.IntoExtern().Type()
_ := externType.IntoFunctionType()

func (*ExternType) IntoGlobalType

func (self *ExternType) IntoGlobalType() *GlobalType

IntoGlobalType converts the ExternType into a GlobalType.

Note:️ If the ExternType is not a GlobalType, IntoGlobalType will return nil as its result.

global, _ := instance.Exports.GetGlobal("exported_global")
externType = global.IntoExtern().Type()
_ := externType.IntoGlobalType()

func (*ExternType) IntoMemoryType

func (self *ExternType) IntoMemoryType() *MemoryType

IntoMemoryType converts the ExternType into a MemoryType.

Note:️ If the ExternType is not a MemoryType, IntoMemoryType will return nil as its result.

memory, _ := instance.Exports.GetMemory("exported_memory")
externType = memory.IntoExtern().Type()
_ := externType.IntoMemoryType()

func (*ExternType) IntoTableType

func (self *ExternType) IntoTableType() *TableType

IntoTableType converts the ExternType into a TableType.

Note:️ If the ExternType is not a TableType, IntoTableType will return nil as its result.

table, _ := instance.Exports.GetTable("exported_table")
externType = table.IntoExtern().Type()
_ := externType.IntoTableType()

func (*ExternType) Kind

func (self *ExternType) Kind() ExternKind

Kind returns the ExternType's ExternKind

global, _ := instance.Exports.GetGlobal("exported_global")
extern = global.IntoExtern()
_ = extern.Kind()

type Frame

type Frame struct {
	// contains filtered or unexported fields
}

Frame represents a frame of a WebAssembly stack trace.

func (*Frame) FunctionIndex

func (self *Frame) FunctionIndex() uint32

FunctionIndex returns the function index in the original WebAssembly module that this frame corresponds to.

func (*Frame) FunctionOffset

func (self *Frame) FunctionOffset() uint

FunctionOffset returns the byte offset from the beginning of the function in the original WebAssembly file to the instruction this frame points to.

func (*Frame) Instance

func (self *Frame) Instance()

func (*Frame) ModuleOffset

func (self *Frame) ModuleOffset() uint

ModuleOffset returns the byte offset from the beginning of the original WebAssembly file to the instruction this frame points to.

type Function

type Function struct {
	// contains filtered or unexported fields
}

Function is a WebAssembly function instance.

func NewFunction

func NewFunction(store *Store, ty *FunctionType, function func([]Value) ([]Value, error)) *Function

NewFunction instantiates a new Function in the given Store.

It takes three arguments, the Store, the FunctionType and the definition for the Function.

The function definition must be a native Go function with a Value array as its single argument. The function must return a Value array or an error.

Note:️ Even if the function does not take any argument (or use any argument) it must receive a Value array as its single argument. At runtime, this array will be empty. The same applies to the result.

hostFunction := wasmer.NewFunction(
	store,
	wasmer.NewFunctionType(
		wasmer.NewValueTypes(), // zero argument
		wasmer.NewValueTypes(wasmer.I32), // one i32 result
	),
	func(args []wasmer.Value) ([]wasmer.Value, error) {
		return []wasmer.Value{wasmer.NewI32(42)}, nil
	},
)

func NewFunctionWithEnvironment

func NewFunctionWithEnvironment(store *Store, ty *FunctionType, userEnvironment interface{}, functionWithEnv func(interface{}, []Value) ([]Value, error)) *Function

NewFunctionWithEnvironment is similar to NewFunction except that the user-defined host function (in Go) accepts an additional first parameter which is an environment. This environment can be anything. It is typed as interface{}.

type MyEnvironment struct {
	foo int32
}

environment := &MyEnvironment {
	foo: 42,
}

hostFunction := wasmer.NewFunction(
	store,
	wasmer.NewFunctionType(
		wasmer.NewValueTypes(), // zero argument
		wasmer.NewValueTypes(wasmer.I32), // one i32 result
	),
	environment,
	func(environment interface{}, args []wasmer.Value) ([]wasmer.Value, error) {
		_ := environment.(*MyEnvironment)

		return []wasmer.Value{wasmer.NewI32(42)}, nil
	},
)

func (*Function) Call

func (self *Function) Call(parameters ...interface{}) (interface{}, error)

Call will call the Function and return its results as native Go values.

function, _ := instance.Exports.GetFunction("exported_function")
_ = function.Call(1, 2, 3)

func (*Function) IntoExtern

func (self *Function) IntoExtern() *Extern

IntoExtern converts the Function into an Extern.

function, _ := instance.Exports.GetFunction("exported_function")
extern := function.IntoExtern()

func (*Function) Native

func (self *Function) Native() NativeFunction

Native will turn the Function into a native Go function that can be then called.

function, _ := instance.Exports.GetFunction("exported_function")
nativeFunction = function.Native()
_ = nativeFunction(1, 2, 3)

func (*Function) ParameterArity

func (self *Function) ParameterArity() uint

ParameterArity returns the number of arguments the Function expects as per its definition.

function, _ := instance.Exports.GetFunction("exported_function")
arity := function.ParameterArity()

func (*Function) ResultArity

func (self *Function) ResultArity() uint

ParameterArity returns the number of results the Function will return.

function, _ := instance.Exports.GetFunction("exported_function")
arity := function.ResultArity()

func (*Function) Type

func (self *Function) Type() *FunctionType

Type returns the Function's FunctionType.

function, _ := instance.Exports.GetFunction("exported_function")
ty := function.Type()

type FunctionType

type FunctionType struct {
	// contains filtered or unexported fields
}

FunctionType classifies the signature of functions, mapping a vector of parameters to a vector of results. They are also used to classify the inputs and outputs of instructions.

See also

Specification: https://webassembly.github.io/spec/core/syntax/types.html#function-types

func NewFunctionType

func NewFunctionType(params []*ValueType, results []*ValueType) *FunctionType

NewFunctionType instantiates a new FunctionType from two ValueType arrays: the parameters and the results.

params := wasmer.NewValueTypes()
results := wasmer.NewValueTypes(wasmer.I32)
functionType := wasmer.NewFunctionType(params, results)

func (*FunctionType) IntoExternType

func (self *FunctionType) IntoExternType() *ExternType

IntoExternType converts the FunctionType into an ExternType.

function, _ := instance.Exports.GetFunction("exported_function")
functionType := function.Type()
externType = functionType.IntoExternType()

func (*FunctionType) Params

func (self *FunctionType) Params() []*ValueType

Params returns the parameters definitions from the FunctionType as a ValueType array

params := wasmer.NewValueTypes()
results := wasmer.NewValueTypes(wasmer.I32)
functionType := wasmer.NewFunctionType(params, results)
paramsValueTypes = functionType.Params()

func (*FunctionType) Results

func (self *FunctionType) Results() []*ValueType

Results returns the results definitions from the FunctionType as a ValueType array

params := wasmer.NewValueTypes()
results := wasmer.NewValueTypes(wasmer.I32)
functionType := wasmer.NewFunctionType(params, results)
resultsValueTypes = functionType.Results()

type Global

type Global struct {
	// contains filtered or unexported fields
}

Global stores a single value of the given GlobalType.

See also

https://webassembly.github.io/spec/core/syntax/modules.html#globals

func NewGlobal

func NewGlobal(store *Store, ty *GlobalType, value Value) *Global

NewGlobal instantiates a new Global in the given Store.

It takes three arguments, the Store, the GlobalType and the Value for the Global.

valueType := NewValueType(I32)
globalType := NewGlobalType(valueType, CONST)
global := NewGlobal(store, globalType, NewValue(42, I32))

func (*Global) Get

func (self *Global) Get() (interface{}, error)

Get returns the Global's value as a native Go value.

global, _ := instance.Exports.GetGlobal("exported_global")
value, _ := global.Get()

func (*Global) IntoExtern

func (self *Global) IntoExtern() *Extern

IntoExtern converts the Global into an Extern.

global, _ := instance.Exports.GetGlobal("exported_global")
extern := global.IntoExtern()

func (*Global) Set

func (self *Global) Set(value interface{}, kind ValueKind) error

Set sets the Global's value.

It takes two arguments, the Global's value as a native Go value and the value's ValueKind.

global, _ := instance.Exports.GetGlobal("exported_global")
_ = global.Set(1, I32)

func (*Global) Type

func (self *Global) Type() *GlobalType

Type returns the Global's GlobalType.

global, _ := instance.Exports.GetGlobal("exported_global")
ty := global.Type()

type GlobalMutability

type GlobalMutability C.wasm_mutability_t

func (GlobalMutability) String

func (self GlobalMutability) String() string

String returns the GlobalMutability as a string.

IMMUTABLE.String() // "const"
MUTABLE.String()   // "var"

type GlobalType

type GlobalType struct {
	// contains filtered or unexported fields
}

GlobalType classifies global variables, which hold a value and can either be mutable or immutable.

See also

Specification: https://webassembly.github.io/spec/core/syntax/types.html#global-types

func NewGlobalType

func NewGlobalType(valueType *ValueType, mutability GlobalMutability) *GlobalType

NewGlobalType instantiates a new GlobalType from a ValueType and a GlobalMutability

valueType := NewValueType(I32)
globalType := NewGlobalType(valueType, IMMUTABLE)

func (*GlobalType) IntoExternType

func (self *GlobalType) IntoExternType() *ExternType

IntoExternType converts the GlobalType into an ExternType.

valueType := NewValueType(I32)
globalType := NewGlobalType(valueType, IMMUTABLE)
externType = globalType.IntoExternType()

func (*GlobalType) Mutability

func (self *GlobalType) Mutability() GlobalMutability

Mutability returns the GlobalType's GlobalMutability

valueType := NewValueType(I32)
globalType := NewGlobalType(valueType, IMMUTABLE)
globalType.Mutability().String() // "const"

func (*GlobalType) ValueType

func (self *GlobalType) ValueType() *ValueType

ValueType returns the GlobalType's ValueType

valueType := NewValueType(I32)
globalType := NewGlobalType(valueType, IMMUTABLE)
globalType.ValueType().Kind().String() // "i32"

type ImportObject

type ImportObject struct {
	// contains filtered or unexported fields
}

ImportObject contains all of the import data used when instantiating a WebAssembly module.

func NewImportObject

func NewImportObject() *ImportObject

NewImportObject instantiates a new empty ImportObject.

imports := NewImportObject()

func (*ImportObject) ContainsNamespace

func (self *ImportObject) ContainsNamespace(name string) bool

ContainsNamespace returns true if the ImportObject contains the given namespace (or module name)

imports := NewImportObject()
_ = imports.ContainsNamespace("env") // false

func (*ImportObject) Register

func (self *ImportObject) Register(namespaceName string, namespace map[string]IntoExtern)

Register registers a namespace (or module name) in the ImportObject.

It takes two arguments: the namespace name and a map with imports names as key and externs as values.

Note:️ An extern is anything implementing IntoExtern: Function, Global, Memory, Table.

 imports := NewImportObject()
 importObject.Register(
 	"env",
 	map[string]wasmer.IntoExtern{
 		"host_function": hostFunction,
 		"host_global": hostGlobal,
 	},
)

Note:️ The namespace (or module name) may be empty:

imports := NewImportObject()
importObject.Register(
	"",
	map[string]wasmer.IntoExtern{
 		"host_function": hostFunction,
		"host_global": hostGlobal,
	},
)

type ImportType

type ImportType struct {
	// contains filtered or unexported fields
}

ImportType is a descriptor for an imported value into a WebAssembly module.

func NewImportType

func NewImportType(module string, name string, ty IntoExternType) *ImportType

NewImportType instantiates a new ImportType with a module name (or namespace), a name and an extern type.

Note:️ An extern type is anything implementing IntoExternType: FunctionType, GlobalType, MemoryType, TableType.

valueType := NewValueType(I32)
globalType := NewGlobalType(valueType, CONST)
importType := NewImportType("ns", "host_global", globalType)

func (*ImportType) Close

func (self *ImportType) Close()

Force to close the ImportType.

A runtime finalizer is registered on the ImportType, but it is possible to force the destruction of the ImportType by calling Close manually.

func (*ImportType) Module

func (self *ImportType) Module() string

Module returns the ImportType's module name (or namespace).

valueType := NewValueType(I32)
globalType := NewGlobalType(valueType, CONST)
importType := NewImportType("ns", "host_global", globalType)
_ = importType.Module()

func (*ImportType) Name

func (self *ImportType) Name() string

Name returns the ImportType's name.

valueType := NewValueType(I32)
globalType := NewGlobalType(valueType, CONST)
importType := NewImportType("ns", "host_global", globalType)
_ = importType.Name()

func (*ImportType) Type

func (self *ImportType) Type() *ExternType

Type returns the ImportType's type as an ExternType.

valueType := NewValueType(I32)
globalType := NewGlobalType(valueType, CONST)
importType := NewImportType("ns", "host_global", globalType)
_ = importType.Type()

type Instance

type Instance struct {
	Exports *Exports
	// contains filtered or unexported fields
}

func NewInstance

func NewInstance(module *Module, imports *ImportObject) (*Instance, error)

NewInstance instantiates a new Instance.

It takes two arguments, the Module and an ImportObject.

Note:️ Instantiating a module may return TrapError if the module's start function traps.

wasmBytes := []byte(`...`)
engine := wasmer.NewEngine()
store := wasmer.NewStore(engine)
module, err := wasmer.NewModule(store, wasmBytes)
importObject := wasmer.NewImportObject()
instance, err := wasmer.NewInstance(module, importObject)

func (*Instance) Close

func (self *Instance) Close()

Force to close the Instance.

A runtime finalizer is registered on the Instance, but it is possible to force the destruction of the Instance by calling Close manually.

func (*Instance) GetRemainingPoints

func (self *Instance) GetRemainingPoints() uint64

GetRemainingPoints exposes wasm meterings remaining gas or points

func (*Instance) MeteringPointsExhausted

func (self *Instance) MeteringPointsExhausted() bool

GetRemainingPoints a bool to determine if the engine has been shutdown from meter exhaustion

func (*Instance) SetRemainingPoints

func (self *Instance) SetRemainingPoints(newLimit uint64)

SetRemainingPoints imposes a new gas limit on the wasm engine

type IntoExtern

type IntoExtern interface {
	IntoExtern() *Extern
}

IntoExtern is an interface implemented by entity that can be imported of exported.

type IntoExternType

type IntoExternType interface {
	IntoExternType() *ExternType
}

type Limits

type Limits struct {
	// contains filtered or unexported fields
}

Limits classify the size range of resizeable storage associated with memory types and table types.

See also

Specification: https://webassembly.github.io/spec/core/syntax/types.html#limits

func NewLimits

func NewLimits(minimum uint32, maximum uint32) (*Limits, error)

NewLimits instantiates a new Limits which describes the Memory used. The minimum and maximum parameters are "number of memory pages".

️Note: Each page is 64 KiB in size.

Note: You cannot Memory.Grow the Memory beyond the maximum defined here.

func (*Limits) Maximum

func (self *Limits) Maximum() uint32

Maximum returns the maximum size of the Memory allocated in "number of pages".

Each page is 64 KiB in size.

Note: You cannot Memory.Grow beyond this defined maximum size.

func (*Limits) Minimum

func (self *Limits) Minimum() uint32

Minimum returns the minimum size of the Memory allocated in "number of pages".

Note:️ Each page is 64 KiB in size.

type Memory

type Memory struct {
	// contains filtered or unexported fields
}

Memory is a vector of raw uninterpreted bytes.

See also

Specification: https://webassembly.github.io/spec/core/syntax/modules.html#memories

func NewMemory

func NewMemory(store *Store, ty *MemoryType) *Memory

NewMemory instantiates a new Memory in the given Store.

It takes two arguments, the Store and the MemoryType for the Memory.

memory := wasmer.NewMemory(
    store,
    wasmer.NewMemoryType(wasmer.NewLimits(1, 4)),
)

func (*Memory) Data

func (self *Memory) Data() []byte

Data returns the Memory's contents as an byte array.

memory, _ := instance.Exports.GetMemory("exported_memory")
data := memory.Data()

func (*Memory) DataSize

func (self *Memory) DataSize() uint

Size returns the Memory's size as a number of bytes.

memory, _ := instance.Exports.GetMemory("exported_memory")
size := memory.DataSize()

func (*Memory) Grow

func (self *Memory) Grow(delta Pages) bool

Grow grows the Memory's size by a given number of Pages (the delta).

memory, _ := instance.Exports.GetMemory("exported_memory")
grown := memory.Grow(2)

func (*Memory) IntoExtern

func (self *Memory) IntoExtern() *Extern

IntoExtern converts the Memory into an Extern.

memory, _ := instance.Exports.GetMemory("exported_memory")
extern := memory.IntoExtern()

func (*Memory) Size

func (self *Memory) Size() Pages

Size returns the Memory's size as Pages.

memory, _ := instance.Exports.GetMemory("exported_memory")
size := memory.Size()

func (*Memory) Type

func (self *Memory) Type() *MemoryType

Type returns the Memory's MemoryType.

memory, _ := instance.Exports.GetMemory("exported_memory")
ty := memory.Type()

type MemoryType

type MemoryType struct {
	// contains filtered or unexported fields
}

MemoryType classifies linear memories and their size range.

See also

Specification: https://webassembly.github.io/spec/core/syntax/types.html#memory-types

func NewMemoryType

func NewMemoryType(limits *Limits) *MemoryType

NewMemoryType instantiates a new MemoryType given some Limits.

limits := NewLimits(1, 4)
memoryType := NewMemoryType(limits)

func (*MemoryType) IntoExternType

func (self *MemoryType) IntoExternType() *ExternType

IntoExternType converts the MemoryType into an ExternType.

limits := NewLimits(1, 4)
memoryType := NewMemoryType(limits)
externType = memoryType.IntoExternType()

func (*MemoryType) Limits

func (self *MemoryType) Limits() *Limits

Limits returns the MemoryType's Limits.

limits := NewLimits(1, 4)
memoryType := NewMemoryType(limits)
_ = memoryType.Limits()

type Module

type Module struct {
	// contains filtered or unexported fields
}

Module contains stateless WebAssembly code that has already been compiled and can be instantiated multiple times.

WebAssembly programs are organized into modules, which are the unit of deployment, loading, and compilation. A module collects definitions for types, functions, tables, memories, and globals. In addition, it can declare imports and exports and provide initialization logic in the form of data and element segments or a start function.

See also

Specification: https://webassembly.github.io/spec/core/syntax/modules.html#modules

func DeserializeModule

func DeserializeModule(store *Store, bytes []byte) (*Module, error)

DeserializeModule deserializes an byte array to a Module.

wasmBytes := []byte(`...`)
engine := wasmer.NewEngine()
store := wasmer.NewStore(engine)
module, _ := wasmer.NewModule(store, wasmBytes)
bytes, err := module.Serialize()
//...
deserializedModule, err := wasmer.DeserializeModule(store, bytes)

func NewModule

func NewModule(store *Store, bytes []byte) (*Module, error)

NewModule instantiates a new Module with the given Store.

It takes two arguments, the Store and the Wasm module as a byte array of WAT code.

wasmBytes := []byte(`...`)
engine := wasmer.NewEngine()
store := wasmer.NewStore(engine)
module, err := wasmer.NewModule(store, wasmBytes)

func (*Module) Close

func (self *Module) Close()

Force to close the Module.

A runtime finalizer is registered on the Module, but it is possible to force the destruction of the Module by calling Close manually.

func (*Module) Exports

func (self *Module) Exports() []*ExportType

Exports returns the Module's exports as an ExportType array.

wasmBytes := []byte(`...`)
engine := wasmer.NewEngine()
store := wasmer.NewStore(engine)
module, _ := wasmer.NewModule(store, wasmBytes)
exports := module.Exports()

func (*Module) Imports

func (self *Module) Imports() []*ImportType

Imports returns the Module's imports as an ImportType array.

wasmBytes := []byte(`...`)
engine := wasmer.NewEngine()
store := wasmer.NewStore(engine)
module, _ := wasmer.NewModule(store, wasmBytes)
imports := module.Imports()

func (*Module) Name

func (self *Module) Name() string

Name returns the Module's name.

Note:️ This is not part of the standard Wasm C API. It is Wasmer specific.

wasmBytes := []byte(`(module $moduleName)`)
engine := wasmer.NewEngine()
store := wasmer.NewStore(engine)
module, _ := wasmer.NewModule(store, wasmBytes)
name := module.Name()

func (*Module) Serialize

func (self *Module) Serialize() ([]byte, error)

Serialize serializes the module and returns the Wasm code as an byte array.

wasmBytes := []byte(`...`)
engine := wasmer.NewEngine()
store := wasmer.NewStore(engine)
module, _ := wasmer.NewModule(store, wasmBytes)
bytes, err := module.Serialize()

type NativeFunction

type NativeFunction = func(...interface{}) (interface{}, error)

NativeFunction is a type alias representing a host function that can be called as any Go function.

type Opcode

type Pages

type Pages C.wasm_memory_pages_t

Units of WebAssembly pages (as specified to be 65,536 bytes).

func (*Pages) ToBytes

func (self *Pages) ToBytes() uint

ToBytes converts a Pages to a native Go uint which is the Pages' size in bytes.

memory, _ := instance.Exports.GetMemory("exported_memory")
size := memory.Size().ToBytes()

func (*Pages) ToUint32

func (self *Pages) ToUint32() uint32

ToUint32 converts a Pages to a native Go uint32 which is the Pages' size.

memory, _ := instance.Exports.GetMemory("exported_memory")
size := memory.Size().ToUint32()

type Store

type Store struct {
	Engine *Engine
	// contains filtered or unexported fields
}

Store represents all global state that can be manipulated by WebAssembly programs. It consists of the runtime representation of all instances of functions, tables, memories, and globals that have been allocated during the life time of the abstract machine.

The Store holds the Engine (that is — amongst many things — used to compile the Wasm bytes into a valid module artifact).

See also

Specification: https://webassembly.github.io/spec/core/exec/runtime.html#store

func NewStore

func NewStore(engine *Engine) *Store

NewStore instantiates a new Store with an Engine.

engine := NewEngine()
store := NewStore(engine)

func (*Store) Close

func (self *Store) Close()

Force to close the Store.

A runtime finalizer is registered on the Store, but it is possible to force the destruction of the Store by calling Close manually.

type Table

type Table struct {
	// contains filtered or unexported fields
}

A table instance is the runtime representation of a table. It holds a vector of function elements and an optional maximum size, if one was specified in the table type at the table’s definition site.

See also

Specification: https://webassembly.github.io/spec/core/exec/runtime.html#table-instances

func (*Table) IntoExtern

func (self *Table) IntoExtern() *Extern

IntoExtern converts the Table into an Extern.

table, _ := instance.Exports.GetTable("exported_table")
extern := table.IntoExtern()

func (*Table) Size

func (self *Table) Size() TableSize

Size returns the Table's size.

table, _ := instance.Exports.GetTable("exported_table")
size := table.Size()

type TableSize

type TableSize C.wasm_table_size_t

TableSize represents the size of a table.

func (*TableSize) ToUint32

func (self *TableSize) ToUint32() uint32

ToUint32 converts a TableSize to a native Go uint32.

table, _ := instance.Exports.GetTable("exported_table")
size := table.Size().ToUint32()

type TableType

type TableType struct {
	// contains filtered or unexported fields
}

TableType classifies tables over elements of element types within a size range.

See also

Specification: https://webassembly.github.io/spec/core/syntax/types.html#table-types

func NewTableType

func NewTableType(valueType *ValueType, limits *Limits) *TableType

NewTableType instantiates a new TableType given a ValueType and some Limits.

valueType := NewValueType(I32)
limits := NewLimits(1, 4)
tableType := NewTableType(valueType, limits)
_ = tableType.IntoExternType()

func (*TableType) IntoExternType

func (self *TableType) IntoExternType() *ExternType

IntoExternType converts the TableType into an ExternType.

valueType := NewValueType(I32)
limits := NewLimits(1, 4)
tableType := NewTableType(valueType, limits)
_ = tableType.IntoExternType()

func (*TableType) Limits

func (self *TableType) Limits() *Limits

Limits returns the TableType's Limits.

valueType := NewValueType(I32)
limits := NewLimits(1, 4)
tableType := NewTableType(valueType, limits)
_ = tableType.Limits()

func (*TableType) ValueType

func (self *TableType) ValueType() *ValueType

ValueType returns the TableType's ValueType.

valueType := NewValueType(I32)
limits := NewLimits(1, 4)
tableType := NewTableType(valueType, limits)
_ = tableType.ValueType()

type Target

type Target struct {
	// contains filtered or unexported fields
}

Target represents a triple + CPU features pairs.

func NewTarget

func NewTarget(triple *Triple, cpuFeatures *CpuFeatures) *Target

NewTarget creates a new target.

triple, err := NewTriple("aarch64-unknown-linux-gnu")
cpuFeatures := NewCpuFeatures()
target := NewTarget(triple, cpuFeatures)

type Trace

type Trace struct {
	// contains filtered or unexported fields
}

Trace represents a WebAssembly trap.

type Trap

type Trap struct {
	// contains filtered or unexported fields
}

Trap stores trace message with backtrace when an error happened.

func NewTrap

func NewTrap(store *Store, message string) *Trap

Creates a new trap with a message.

engine := wasmer.NewEngine()
store := wasmer.NewStore(engine)
trap := NewTrap(store, "oops")

func (*Trap) Message

func (self *Trap) Message() string

Message returns the message attached to the current Trap.

func (*Trap) Origin

func (self *Trap) Origin() *Frame

Origin returns the top frame of WebAssembly stack responsible for this trap.

frame := trap.Origin()

func (*Trap) Trace

func (self *Trap) Trace() *Trace

Trace returns the trace of WebAssembly frames for this trap.

type TrapError

type TrapError struct {
	// contains filtered or unexported fields
}

TrapError represents a trap produced during Wasm execution.

See also

Specification: https://webassembly.github.io/spec/core/intro/overview.html#trap

func (*TrapError) Error

func (self *TrapError) Error() string

Error returns the TrapError's message.

func (*TrapError) Origin

func (self *TrapError) Origin() *Frame

Origin returns the TrapError's origin as a Frame.

func (*TrapError) Trace

func (self *TrapError) Trace() []*Frame

Trace returns the TrapError's trace as a Frame array.

type Triple

type Triple struct {
	// contains filtered or unexported fields
}

Triple; historically such things had three fields, though they have added additional fields over time.

func NewTriple

func NewTriple(triple string) (*Triple, error)

NewTriple creates a new triple, otherwise it returns an error specifying why the provided triple isn't valid.

triple, err := NewTriple("aarch64-unknown-linux-gnu")

func NewTripleFromHost

func NewTripleFromHost() *Triple

NewTripleFromHost creates a new triple from the current host.

type Value

type Value struct {
	// contains filtered or unexported fields
}

Value; WebAssembly computations manipulate values of basic value types:

• Integer (32 or 64 bit width),

• Floating-point (32 or 64 bit width),

• Vectors (128 bits, with 32 or 64 bit lanes).

See Also

Specification: https://webassembly.github.io/spec/core/exec/runtime.html#values

func NewF32

func NewF32(value interface{}) Value

NewF32 instantiates a new F32 Value with the given value.

Note: If a Wasm value cannot be created from the given value, NewF32 will panic.

value := NewF32(4.2)

func NewF64

func NewF64(value interface{}) Value

NewF64 instantiates a new F64 Value with the given value.

Note: If a Wasm value cannot be created from the given value, NewF64 will panic.

value := NewF64(4.2)

func NewI32

func NewI32(value interface{}) Value

NewI32 instantiates a new I32 Value with the given value.

Note: If a Wasm value cannot be created from the given value, NewI32 will panic.

value := NewI32(42)

func NewI64

func NewI64(value interface{}) Value

NewI64 instantiates a new I64 Value with the given value.

Note: If a Wasm value cannot be created from the given value, NewI64 will panic.

value := NewI64(42)

func NewValue

func NewValue(value interface{}, kind ValueKind) Value

NewValue instantiates a new Value with the given value and ValueKind.

Note: If a Wasm value cannot be created from the given value,

value := NewValue(42, I32)

func (*Value) F32

func (self *Value) F32() float32

F32 returns the Value's value as a native Go float32.

Note: It panics if the value is not of type F32.

value := NewF32(4.2)
_ = value.F32()

func (*Value) F64

func (self *Value) F64() float64

F64 returns the Value's value as a native Go float64.

Note: It panics if the value is not of type F64.

value := NewF64(4.2)
_ = value.F64()

func (*Value) I32

func (self *Value) I32() int32

I32 returns the Value's value as a native Go int32.

Note: It panics if the value is not of type I32.

value := NewI32(42)
_ = value.I32()

func (*Value) I64

func (self *Value) I64() int64

I64 returns the Value's value as a native Go int64.

Note: It panics if the value is not of type I64.

value := NewI64(42)
_ = value.I64()

func (*Value) Kind

func (self *Value) Kind() ValueKind

Kind returns the Value's ValueKind.

value := NewF64(4.2)
_ = value.Kind()

func (*Value) Unwrap

func (self *Value) Unwrap() interface{}

Unwrap returns the Value's value as a native Go value.

value := NewF64(4.2)
_ = value.Unwrap()

type ValueKind

type ValueKind C.wasm_valkind_t

ValueKind represents the kind of a value.

func (ValueKind) IsNumber

func (self ValueKind) IsNumber() bool

IsNumber returns true if the ValueKind is a number type.

I32.IsNumber()     // true
I64.IsNumber()     // true
F32.IsNumber()     // true
F64.IsNumber()     // true
AnyRef.IsNumber()  // false
FuncRef.IsNumber() // false

func (ValueKind) IsReference

func (self ValueKind) IsReference() bool

IsReference returns true if the ValueKind is a reference.

I32.IsReference()     // false
I64.IsReference()     // false
F32.IsReference()     // false
F64.IsReference()     // false
AnyRef.IsReference()  // true
FuncRef.IsReference() // true

func (ValueKind) String

func (self ValueKind) String() string

String returns the ValueKind as a string.

I32.String()     // "i32"
I64.String()     // "i64"
F32.String()     // "f32"
F64.String()     // "f64"
AnyRef.String()  // "anyref"
FuncRef.String() // "funcref"

type ValueType

type ValueType struct {
	// contains filtered or unexported fields
}

ValueType classifies the individual values that WebAssembly code can compute with and the values that a variable accepts.

func NewValueType

func NewValueType(kind ValueKind) *ValueType

NewValueType instantiates a new ValueType given a ValueKind.

valueType := NewValueType(I32)

func NewValueTypes

func NewValueTypes(kinds ...ValueKind) []*ValueType

NewValueTypes instantiates a new ValueType array from a list of ValueKind. Note that this list may be empty.

valueTypes := NewValueTypes(I32, I64, F32)

Note:️ NewValueTypes is specifically designed to help you declare function types, e.g. with NewFunctionType:

functionType := NewFunctionType(
	NewValueTypes(), // arguments
	NewValueTypes(I32), // results
)

func (*ValueType) Kind

func (self *ValueType) Kind() ValueKind

Kind returns the ValueType's ValueKind

valueType := NewValueType(I32)
_ = valueType.Kind()

type WasiEnvironment

type WasiEnvironment struct {
	// contains filtered or unexported fields
}

WasiEnvironment represents the environment provided to the WASI imports (see NewFunctionWithEnvironment which is designed for user-defined host function; that's the same idea here but applied to WASI functions and other imports).

func (*WasiEnvironment) GenerateImportObject

func (self *WasiEnvironment) GenerateImportObject(module *Module) (*ImportObject, error)

GenerateImportObject generates an import object, that can be extended and passed to NewInstance.

wasiEnv, _ := NewWasiStateBuilder("test-program").
	Argument("--foo").
	Environment("ABC", "DEF").
	Environment("X", "ZY").
	MapDirectory("the_host_current_directory", ".").
	Finalize()

importObject, _ := wasiEnv.GenerateImportObject(store, module)
instance, _ := NewInstance(module, importObject)
start, _ := instance.Exports.GetWasiStartFunction()

start()

func (*WasiEnvironment) ReadStderr

func (self *WasiEnvironment) ReadStderr() []byte

ReadStderr reads the WASI module stderr if captured with WasiStateBuilder.CaptureStderr. See ReadStdout to see an example.

func (*WasiEnvironment) ReadStdout

func (self *WasiEnvironment) ReadStdout() []byte

ReadStdout reads the WASI module stdout if captured with WasiStateBuilder.CaptureStdout

wasiEnv, _ := NewWasiStateBuilder("test-program").
	Argument("--foo").
	Environment("ABC", "DEF").
	Environment("X", "ZY").
	MapDirectory("the_host_current_directory", ".").
	CaptureStdout().
	Finalize()

importObject, _ := wasiEnv.GenerateImportObject(store, module)
instance, _ := NewInstance(module, importObject)
start, _ := instance.Exports.GetWasiStartFunction()

start()

stdout := string(wasiEnv.ReadStdout())

type WasiStateBuilder

type WasiStateBuilder struct {
	// contains filtered or unexported fields
}

WasiStateBuilder is a convenient API for configuring WASI.

func NewWasiStateBuilder

func NewWasiStateBuilder(programName string) *WasiStateBuilder

NewWasiStateBuilder creates a new WASI state builder, starting by configuring the WASI program name.

wasiStateBuilder := NewWasiStateBuilder("test-program")

func (*WasiStateBuilder) Argument

func (self *WasiStateBuilder) Argument(argument string) *WasiStateBuilder

Argument configures a new argument to the WASI module.

wasiStateBuilder := NewWasiStateBuilder("test-program").
	Argument("--foo")

func (*WasiStateBuilder) CaptureStderr

func (self *WasiStateBuilder) CaptureStderr() *WasiStateBuilder

CaptureStderr configures the WASI module to capture its stderr.

func (*WasiStateBuilder) CaptureStdout

func (self *WasiStateBuilder) CaptureStdout() *WasiStateBuilder

CaptureStdout configures the WASI module to capture its stdout.

wasiStateBuilder := NewWasiStateBuilder("test-program").
	Argument("--foo").
	Environment("KEY", "VALUE").
	MapDirectory("the_host_current_directory", ".")
	CaptureStdout()

func (*WasiStateBuilder) Environment

func (self *WasiStateBuilder) Environment(key string, value string) *WasiStateBuilder

Environment configures a new environment variable for the WASI module.

wasiStateBuilder := NewWasiStateBuilder("test-program").
	Argument("--foo").
	Environment("KEY", "VALUE")

func (*WasiStateBuilder) Finalize

func (self *WasiStateBuilder) Finalize(store *Store) (*WasiEnvironment, error)

Finalize tells the state builder to produce a WasiEnvironment. It consumes the current WasiStateBuilder.

It can return an error if the state builder contains invalid configuration.

wasiEnvironment, err := NewWasiStateBuilder("test-program").
	Argument("--foo").
	Environment("KEY", "VALUE").
	MapDirectory("the_host_current_directory", ".")
	CaptureStdout().
  Finalize()

func (*WasiStateBuilder) InheritStderr

func (self *WasiStateBuilder) InheritStderr() *WasiStateBuilder

InheritStderr configures the WASI module to inherit the stderr from the host.

func (*WasiStateBuilder) InheritStdin

func (self *WasiStateBuilder) InheritStdin() *WasiStateBuilder

InheritStdin configures the WASI module to inherit the stdin from the host.

func (*WasiStateBuilder) InheritStdout

func (self *WasiStateBuilder) InheritStdout() *WasiStateBuilder

InheritStdout configures the WASI module to inherit the stdout from the host.

func (*WasiStateBuilder) MapDirectory

func (self *WasiStateBuilder) MapDirectory(alias string, directory string) *WasiStateBuilder

MapDirectory configures a new directory to pre-open with a different name exposed to the WASI module.

wasiStateBuilder := NewWasiStateBuilder("test-program").
	Argument("--foo").
	Environment("KEY", "VALUE").
	MapDirectory("the_host_current_directory", ".")

func (*WasiStateBuilder) PreopenDirectory

func (self *WasiStateBuilder) PreopenDirectory(preopenDirectory string) *WasiStateBuilder

PreopenDirectory configures a new directory to pre-open.

This opens the given directory at the virtual root /, and allows the WASI module to read and write to the given directory.

wasiStateBuilder := NewWasiStateBuilder("test-program").
	Argument("--foo").
	Environment("KEY", "VALUE").
	PreopenDirectory("bar")

type WasiVersion

type WasiVersion C.wasi_version_t

WasiVersion represents the possible WASI versions.

func GetWasiVersion

func GetWasiVersion(module *Module) WasiVersion

GetWasiVersion returns the WASI version of the given Module if any, WASI_VERSION_INVALID otherwise.

wasiVersion := GetWasiVersion(module)

func (WasiVersion) String

func (self WasiVersion) String() string

String returns the WasiVersion as a string.

WASI_VERSION_SNAPSHOT0.String() //  "wasi_unstable"
WASI_VERSION_SNAPSHOT1.String() // "wasi_snapshot_preview1"

Directories

Path Synopsis
packaged
include
See https://github.com/golang/go/issues/26366.
See https://github.com/golang/go/issues/26366.
lib
See https://github.com/golang/go/issues/26366.
See https://github.com/golang/go/issues/26366.
lib/darwin-aarch64
See https://github.com/golang/go/issues/26366.
See https://github.com/golang/go/issues/26366.
lib/darwin-amd64
See https://github.com/golang/go/issues/26366.
See https://github.com/golang/go/issues/26366.
lib/linux-aarch64
See https://github.com/golang/go/issues/26366.
See https://github.com/golang/go/issues/26366.
lib/linux-amd64
See https://github.com/golang/go/issues/26366.
See https://github.com/golang/go/issues/26366.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL