Skip to content

Commit

Permalink
add call_indirect example
Browse files Browse the repository at this point in the history
  • Loading branch information
reklatsmasters committed Aug 16, 2017
1 parent d2030f0 commit 5818b15
Show file tree
Hide file tree
Showing 3 changed files with 102 additions and 0 deletions.
61 changes: 61 additions & 0 deletions #7-call-indirect/call.js
@@ -0,0 +1,61 @@

module.exports = loadWebAssembly

loadWebAssembly.supported = typeof WebAssembly !== 'undefined'

function loadWebAssembly (opts) {
if (!loadWebAssembly.supported) return null

var imp = opts && opts.imports
var wasm = toUint8Array('AGFzbQEAAAABBQFgAAF/AwQDAAAABAUBcAECAgYGAX8BQX8LBxACBXRhYmxlAQAEbWFpbgAACQgBAEEACwIBAgomAxoAIwBBAWokACMAQQFLBEBBACQACyMAEQAACwQAQQoLBABBFAs=')
var ready = null

var mod = {
buffer: wasm,
memory: null,
exports: null,
realloc: realloc,
onload: onload
}

onload(function () {})

return mod

function realloc (size) {
mod.exports.memory.grow(Math.ceil(Math.abs(size - mod.memory.length) / 65536))
mod.memory = new Uint8Array(mod.exports.memory.buffer)
}

function onload (cb) {
if (mod.exports) return cb()

if (ready) {
ready.then(cb.bind(null, null)).catch(cb)
return
}

try {
if (opts && opts.async) throw new Error('async')
setup({instance: new WebAssembly.Instance(new WebAssembly.Module(wasm), imp)})
} catch (err) {
ready = WebAssembly.instantiate(wasm, imp).then(setup)
}

onload(cb)
}

function setup (w) {
mod.exports = w.instance.exports
mod.memory = mod.exports.memory && mod.exports.memory.buffer && new Uint8Array(mod.exports.memory.buffer)
}
}

function toUint8Array (s) {
if (typeof atob === 'function') return new Uint8Array(atob(s).split('').map(charCodeAt))
return new (require('buf' + 'fer').Buffer)(s, 'base64')
}

function charCodeAt (c) {
return c.charCodeAt(0)
}
35 changes: 35 additions & 0 deletions #7-call-indirect/call.wat
@@ -0,0 +1,35 @@
;; This example shows the way to change export table.
(module
(table anyfunc (elem $internal_function$1 $internal_function$2))

(type $type_t (func (result i32)))

(export "table" (table 0))
(export "main" (func $public_function))

(global $i (mut i32) (i32.const -1))

;; public exported function
(func $public_function (type $type_t)
;; change ptr to internal function.
;; ++i
(set_global $i (i32.add (get_global $i) (i32.const 1)))

;; if (i > 1) i = 0
(if (i32.gt_u (get_global $i) (i32.const 1))
(set_global $i (i32.const 0))
)

;; proxy to internal function
;; use dynamic linking
(call_indirect $type_t (get_global $i))
)

(func $internal_function$1 (type $type_t)
(i32.const 10)
)

(func $internal_function$2 (type $type_t)
(i32.const 20)
)
)
6 changes: 6 additions & 0 deletions #7-call-indirect/index.js
@@ -0,0 +1,6 @@
const wasm = require('./call')().exports

console.log(wasm.main()) // 10
console.log(wasm.main()) // 20
console.log(wasm.main()) // 10
console.log(wasm.main()) // 20

0 comments on commit 5818b15

Please sign in to comment.