Skip to content

Commit

Permalink
[ch06] Linear Memory in WebAssembly
Browse files Browse the repository at this point in the history
  • Loading branch information
zaki-yama committed Jul 2, 2021
1 parent 88e003d commit 65808c3
Show file tree
Hide file tree
Showing 4 changed files with 62 additions and 0 deletions.
30 changes: 30 additions & 0 deletions the-art-of-webassembly/ch06/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# Chapter 6 Linear Memory

- linear memory とはなにか
- JS と Wasm の間でデータを共有するために linear memory をどう使うのか
- JS 内で linear memory をどう作成するのか

## Linear Memory in WebAssembly

- ローカル変数をスタックに格納するというのは、stack pointer をインクリメント/デクリメントすればいいのでシンプル
- しかし、WAT における制限として、スタックを使えるローカル変数は数値型 4 種類しか使えない
- C における `malloc` や C++や JS における `new` のようなアロケーションコマンドは、ヒープ上に割り当てを行いますが、これらの言語に含まれるメモリ管理ライブラリは、必要なメモリブロックを格納するのに十分な大きさのヒープ上のメモリの空きセクションを探す必要があります。その結果、図 6-2 に示すように、割り当てられたメモリセグメントが未割り当てのメモリで区切られる、メモリフラグメンテーションが発生する可能性があります。
- WebAssembly の linear memory は pages と呼ばれる大きなチャンクにアロケートされ、一度アロケートされるとデアロケートすることはできない
- WebAssembly のメモリはアセンブリ言語っぽいメモリ管理である: あなたが決めたページ数を WebAssembly モジュールにアロケートしたら、どこに・何のためにメモリを使っているのかを追跡する必要がある

### Pages

- 1 ページ 64KB (現在はこのサイズは変更不可)
- 最大ページ数は 32,767、メモリサイズの最大値は 2GB

#### Creating Pages in Your Code

```wat
(memory 1)
```

#### Creating Memory in the Embedded Environment

```js
const memory = new WebAssembly.Memory({ initial: 1 });
```
18 changes: 18 additions & 0 deletions the-art-of-webassembly/ch06/pointer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
const fs = require("fs");
const bytes = fs.readFileSync(__dirname + "/pointer.wasm");
const memory = new WebAssembly.Memory({ initial: 1, maximum: 4 });

const importObject = {
env: {
mem: memory,
},
};

(async () => {
const obj = await WebAssembly.instantiate(
new Uint8Array(bytes),
importObject
);
const pointer_value = obj.instance.exports.get_ptr();
console.log(`pointer_value=${pointer_value}`);
})();
Binary file added the-art-of-webassembly/ch06/pointer.wasm
Binary file not shown.
14 changes: 14 additions & 0 deletions the-art-of-webassembly/ch06/pointer.wat
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
(module
(memory 1)
(global $pointer i32 (i32.const 128))
(func $init
(i32.store
(global.get $pointer) ;; store at address $pointer
(i32.const 99) ;; value stored
)
)
(func (export "get_ptr") (result i32)
(i32.load (global.get $pointer)) ;; return value at location $pointer
)
(start $init)
)

0 comments on commit 65808c3

Please sign in to comment.