wardite 1.1.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -16,9 +16,11 @@ Wasm全体のSHA-256、形式バージョン、生成コードの互換バージ
16
16
 
17
17
  既定の `--mir-cache-verify checksum` は長さと標本ブロックを照合する。標本外の破損は構造検査で見つかる場合があり、構造上正しい破損は見逃して誤った命令を実行する可能性がある。全体を確認するには `--mir-cache-verify sha256`、Ruby APIでは `mir_cache_verify: :sha256` を指定する。どちらのモードでも同じファイルを読み、構造検査を行う。[ADR 0009](adr/0009-efflorescence-mir2-cache-integrity-modes.md)
18
18
 
19
- 形式バージョン2への更新後、旧MIR2キャッシュは初回起動時に再生成される。MIR2キーを使う起動スナップショットも再生成される。スナップショットのファイル形式と全体SHA-256検査は維持する。
19
+ 形式バージョン3のペイロード先頭に、定義関数ごとのオフセットと長さを持つ関数表がある。更新後の初回起動で旧MIR2と、それをキーに使う起動スナップショットを再生成する。スナップショットの形式と全体SHA-256検査は維持する。[ADR 0010](adr/0010-efflorescence-mir2-cache-function-restore.md)
20
20
 
21
- セクションとローカル宣言の読み取り、import確認、Store初期化を毎回行う。Storeの構築前に、キャッシュのサイズ、ダイジェスト、モジュール構成、個数、opcode、コード幅、参照index、分岐先を確認する。ヒット時はWasmの命令本体をバイト列のまま保持し、Ruby APIから命令配列や中間MIRを取得するときにデコードする。ミスや破損時はStore構築とホスト解決の前に命令本体をデコードしてブロック型などを確認する。関数とWASI callableの参照は今回のインスタンスに解決し、Wasmのstartセクションを実行してからCLIが `_start` を呼ぶ。
21
+ セクションとローカル宣言の読み取り、import確認、Store初期化を毎回行う。Storeの構築前に、サイズ、ダイジェスト、モジュール構成、関数表を確認する。ヒット時はWasmの命令本体をバイト列のまま保持し、MIR2の各関数は最初のフレーム確保時に復元する。スナップショットから再開するフレームの関数は、再開位置を確認する前に復元する。opcode、コード幅、参照index、分岐先は関数の実行前に検査する。
22
+
23
+ `--mir-cache-eager` またはRuby APIの `mir_cache_eager: true` で全関数をロード時に復元・検査する。Ruby APIで `optimized_ir` や `dump_mir` を呼ぶと全関数を復元する。ロード時に破損が見つかった場合はキャッシュミスとして再ビルドする。遅延復元で破損が見つかった場合は、キャッシュのパスを含む例外で実行を止める。該当ファイルを削除して再実行する。
22
24
 
23
25
  キャッシュには実行ユーザーが管理するローカルディレクトリを使う。ダイジェストは整合性の検査に使い、入力の信頼はディレクトリの管理者に置く。256 MiBまでのファイルを扱う。破損や読み取り失敗は再ビルドし、書き込みは同じディレクトリの一時ファイルからrenameする。保存先に書き込めなくてもビルド済みのコードで実行する。opcodeや参照表の意味、生成コードや検証規則を変更する際は `MIRCache::CODE_VERSION` を更新する。
24
26
 
@@ -121,3 +123,30 @@ ruby benchmark/measure_mir_cache_verify.rb "$ruby_wasm" "$baseline_dir/build/war
121
123
  ```
122
124
 
123
125
  CRubyとSpinelで各436フィクスチャのparity、全288テスト、型チェックが通った。Ruby 4.0.9の `-e`、`require_relative`、`exit 7` の出力と終了コードは、両モードのキャッシュヒットでWasmtimeと一致した。CRubyとSpinelが生成した同一MIRの両ダイジェストを照合し、標本外の不正なopcodeとindexは構造検査で拒否されることも確認した。
126
+
127
+ ## 関数復元の計測
128
+
129
+ Apple M3 Pro、macOS 27.0.1 arm64で、変更前(`f602d11`)、段階1の直接読み込み(`a38c88b`)、段階2の遅延復元を比較した。すべてSpinel `6e7fc1355` にリポジトリ同梱のパッチを適用したコンパイラで `-O2` ビルドした。ゲストはRuby 4.0.9 Wasmの `--disable-gems -e 'puts RUBY_VERSION'`。各条件でMIR2キャッシュを事前に作り、OSのファイルキャッシュがウォームな状態で、ウォームアップ1回後に各6回、新規プロセスを交互に実行した。
130
+
131
+ | スナップショット | 条件 | ロード(秒) | CLI全体(秒) | ピークRSS(MiB) |
132
+ |---|---|---:|---:|---:|
133
+ | なし | 変更前 | 0.437 | 1.217 | 991.8 |
134
+ | なし | 段階1 | 0.343 | 1.115 | 894.7 |
135
+ | なし | 段階2 | 0.132 | 0.954 | 712.6 |
136
+ | あり | 変更前 | 0.437 | 0.541 | 944.6 |
137
+ | あり | 段階1 | 0.350 | 0.434 | 848.1 |
138
+ | あり | 段階2 | 0.142 | 0.232 | 620.6 |
139
+
140
+ 表は中央値。段階1でスナップショットなしのロードが21.5%短縮した。段階2では段階1に比べ、CLI全体がスナップショットなしで14.5%、ありで46.7%短縮し、ピークRSSもそれぞれ20.4%、26.8%減った。段階2のスナップショットは、再開するフレームの関数を復元してからプログラムを再開する。
141
+
142
+ スナップショットなしの `CLI全体 - load_from_buffer` の中央値は段階1が0.773秒、段階2が0.821秒だった。計測コードを加えた両ビルドで `start_wasi` から `at_exit` までと、その間の関数復元の累計を各10回測った。遅延復元の中央値は0.052秒。復元時間を除いたゲスト区間は段階1が0.763秒、段階2が0.764秒で、測定範囲は重なった。起動時間とRSSの表は計測コードを加える前のバイナリで採取した。[全サンプル](../benchmark/results/efflorescence-mir2-function-restore.json)
143
+
144
+ CRubyの `FramePool#acquire` で数えた使用関数は、`puts RUBY_DESCRIPTION` で943/6,049(15.6%)、`require_relative` を使うスクリプトで975/6,049(16.1%)だった。各ケースとも上位121関数で呼び出し回数の90%に達した。
145
+
146
+ ```sh
147
+ ruby benchmark/measure_mir_cache_restore.rb "$ruby_wasm" "$before_bin" "$direct_bin" build/wardite
148
+ SNAPSHOT=1 ruby benchmark/measure_mir_cache_restore.rb "$ruby_wasm" "$before_bin" "$direct_bin" build/wardite
149
+ WARDITE_VERIFY_MIR_CACHE_PARITY=1 bundle exec rake parity
150
+ ```
151
+
152
+ 両段階で、CRubyとSpinelのキャッシュ保存・ヒットを各436フィクスチャで照合した。生成Cでは `Decoder#read_function` と `Reader#read_into` に boxed 配列の生成・変換がないことを確認した。遅延復元では直接呼び出し、`call_indirect`、ホストからの再入、例外ハンドラを検証した。標本外の破損は、その関数を呼ぶとファイル名付きのエラーになり、呼ばない場合は正常に終わった。
@@ -2,7 +2,7 @@
2
2
 
3
3
  [ADR 0008の6a](adr/0008-efflorescence-ruby-wasm-phase2.md#6a-spinelに書き込み可能なstringビューを実装)では、Spinelに `IO::Buffer.for(string) { |buffer| ... }` を追加し、Efflorescenceの `memory.fill` で書き込み可能なビューを使った。ブロック中はStringの変更を拒否する。正常終了と例外でロックを解除し、渡したバッファを解放する。凍結Stringは読み取り専用。Spinelの回帰フィクスチャをCRuby 4.0.9と照合した。
4
4
 
5
- Spinel側のコミットは `255955a06a0311df92f6b422c69d65ff2f39fe6e`。WarditeのCIでは固定したSpinel `6e7fc13556709bf7d7ba4af5bd1d12bebc00733e` に `spinel/patches/0001-io-buffer-string-view.patch` を適用する。
5
+ Spinel側の当初の実装は `255955a06a0311df92f6b422c69d65ff2f39fe6e`。現在のCIで使うリビジョンには、ブロック付き `IO::Buffer.for` の実装が含まれる。
6
6
 
7
7
  Apple M3 ProのSpinel `-O2` で、初回のfillでページを確保してから256 MiBを3回埋めた。バイトループは628.70–632.33 ms、Stringビューと `buffer.clear` は4.13–4.67 msだった。Ruby 4.0.9のWasmは `-e 'puts RUBY_VERSION; puts 6*7'` を実行し、標準出力の `4.0.9` と `42` を確認した。
8
8
 
@@ -16,11 +16,13 @@ CRubyのホストAPIは `Memory#data` のStringを引き続き使える。両ホ
16
16
 
17
17
  ## ビルド
18
18
 
19
- Spinel側では `a9a35b85d75ca273558f7e25a875cc240fc0f5a3` で、`IO::Buffer.new` の領域割り当て失敗を `Errno::ENOMEM` として伝える。WarditeのCIは固定したSpinelに両方のパッチを適用し、パッチのハッシュをツールチェーンキャッシュのキーに含める。同じ構成をローカルでビルドするには、Spinelのクリーンな作業ツリーを `spinel_src` に指定し、Warditeのルートから実行する。
19
+ WarditeのCIは [Spinel upstreamの `58ee6361`](https://github.com/matz/spinel/commit/58ee6361642befd3770516137c41a6553f0262d1) に固定する。このリビジョンは `IO::Buffer.new` の領域割り当て失敗を `IO::Buffer::AllocationError` として伝える。CIはコミットとビルド環境でツールチェーンを識別し、Actionsキャッシュ、`main` の成功済み実行のArtifact、ソースからのビルドの順で取得する。インストール一式の `spinel.tar.gz` は、保存元のActions実行ページからダウンロードできる。Artifactにはリポジトリの既定の保持期間を適用する。
20
+
21
+ 同じリビジョンをローカルでビルドするには、クローン先のパスを `spinel_src` に指定し、Warditeのルートから実行する。
20
22
 
21
23
  ```sh
22
- git -C "$spinel_src" switch --detach 6e7fc13556709bf7d7ba4af5bd1d12bebc00733e
23
- git -C "$spinel_src" apply "$PWD"/spinel/patches/*.patch
24
+ git clone https://github.com/matz/spinel.git "$spinel_src"
25
+ git -C "$spinel_src" switch --detach 58ee6361642befd3770516137c41a6553f0262d1
24
26
  make -C "$spinel_src" deps
25
27
  make -C "$spinel_src" all
26
28
  make spinel SPINEL="$spinel_src/bin/spinel"
@@ -43,6 +43,7 @@ module Wardite
43
43
  @mir_profile = false
44
44
  @mir_cache = nil
45
45
  @mir_cache_verify = :checksum
46
+ @mir_cache_eager = false
46
47
  @snapshot = nil
47
48
  @memsize = 1
48
49
  parser = RUBY_ENGINE == "spinel" ? SpinelOptions : OptionParser
@@ -69,6 +70,7 @@ module Wardite
69
70
  opts.on("--mir-dump", "Print semantic and optimized MIR") { @mir_dump = true }
70
71
  opts.on("--mir-profile", "Instrument MIR execution (do not use for timing)") { @mir_profile = true }
71
72
  opts.on("--mir-cache DIR", "Reuse MIR2 in a local directory") { |dir| @mir_cache = dir }
73
+ opts.on("--mir-cache-eager", "Restore and check every cached MIR2 function at load time") { @mir_cache_eager = true }
72
74
  opts.on("--mir-cache-verify MODE", "Verify the MIR2 cache with checksum (default) or sha256") do |mode|
73
75
  unless mode == "checksum" || mode == "sha256"
74
76
  raise Wardite::ArgumentError, "--mir-cache-verify expects checksum or sha256"
@@ -124,7 +126,7 @@ module Wardite
124
126
  ins = File.open(file, "rb") do |f|
125
127
  Wardite::BinaryLoader.load_from_buffer(f, enable_wasi: wasi, engine: new_engine ? :efflorescence : :stack,
126
128
  disabled_optimizations: disabled_optimizations, mir_profile: mir_profile,
127
- mir_cache: mir_dump ? nil : mir_cache, mir_cache_verify: @mir_cache_verify)
129
+ mir_cache: mir_dump ? nil : mir_cache, mir_cache_verify: @mir_cache_verify, mir_cache_eager: @mir_cache_eager)
128
130
  end
129
131
  if memsize > 1
130
132
  ins.store.memories[0].grow(memsize)
@@ -673,7 +673,8 @@ module Wardite
673
673
  attr_reader :pool_index #: Integer
674
674
  attr_reader :parameter_types #: Array[Symbol]
675
675
  attr_reader :result_types #: Array[Symbol]
676
- attr_reader :local_count #: Integer
676
+ attr_accessor :local_count #: Integer
677
+ attr_accessor :cache_pending #: bool
677
678
  attr_reader :instructions #: Array[Wardite::Efflorescence::Instruction]
678
679
  attr_reader :initial_registers #: Array[Integer]
679
680
  attr_reader :constant_registers #: Array[Integer]
@@ -703,6 +704,7 @@ module Wardite
703
704
  @parameter_types = parameter_types.dup
704
705
  @result_types = result_types.dup
705
706
  @local_count = local_count
707
+ @cache_pending = false
706
708
  @register_types = parameter_types + (local_types || Array.new(local_count, :i32))
707
709
  @handlers = []
708
710
  @flat_handlers = []
@@ -1131,10 +1133,12 @@ module Wardite
1131
1133
 
1132
1134
  # @rbs function: Wardite::Efflorescence::Function
1133
1135
  # @rbs reuse: bool
1134
- def initialize(function, reuse)
1136
+ # @rbs cache: Wardite::Efflorescence::MIRCache?
1137
+ def initialize(function, reuse, cache = nil)
1135
1138
  @function = function
1136
1139
  @reuse = reuse
1137
- @clear_references = function.uses_eh
1140
+ @cache = cache
1141
+ @clear_references = false
1138
1142
  @free = [] #: Array[Wardite::Efflorescence::Frame]
1139
1143
  @created = 0
1140
1144
  end
@@ -1149,6 +1153,11 @@ module Wardite
1149
1153
  return frame
1150
1154
  end
1151
1155
  end
1156
+ if @function.cache_pending
1157
+ cache = @cache || raise(Wardite::EvalError, "missing MIR2 cache for pending function")
1158
+ cache.restore_function(@function)
1159
+ end
1160
+ @clear_references = @function.uses_eh
1152
1161
  @created += 1
1153
1162
  Frame.new(@function, destination)
1154
1163
  end
@@ -12,7 +12,7 @@ module Wardite
12
12
  # optimizer/validator fixes, and changes to the metadata used by the VM.
13
13
  class MIRCache
14
14
  MAGIC = "WARDMIR\0".b
15
- FORMAT_VERSION = 2
15
+ FORMAT_VERSION = 3
16
16
  CODE_VERSION = 1
17
17
  DIGEST_SIZE = 32
18
18
  LENGTH_SIZE = 8
@@ -38,10 +38,15 @@ module Wardite
38
38
  # All records are little-endian. Vectors carry a nonnegative 32-bit element count.
39
39
  # A record count is bounded by the bytes still available to decode it.
40
40
  class Reader
41
+ attr_reader :offset #: Integer
42
+
41
43
  # @rbs bytes: String
42
- def initialize(bytes)
44
+ # @rbs offset: Integer
45
+ # @rbs length: Integer?
46
+ def initialize(bytes, offset: 0, length: nil)
43
47
  @bytes = bytes
44
- @offset = 0
48
+ @offset = offset
49
+ @limit = length ? offset + length : bytes.bytesize
45
50
  end
46
51
 
47
52
  # @rbs length: Integer
@@ -80,6 +85,35 @@ module Wardite
80
85
  result
81
86
  end
82
87
 
88
+ # @rbs target: Array[Integer]
89
+ # @rbs format: String
90
+ # @rbs width: Integer
91
+ # @rbs return: void
92
+ def read_into(target, format, width)
93
+ if RUBY_ENGINE == "spinel"
94
+ length = count(width)
95
+ offset = @offset
96
+ limit = offset + length * width
97
+ target.clear
98
+ IO::Buffer.for(@bytes) do |buffer|
99
+ if width == 8
100
+ while offset < limit
101
+ target << buffer.get_value(:s64, offset)
102
+ offset += 8
103
+ end
104
+ else
105
+ while offset < limit
106
+ target << buffer.get_value(:s32, offset)
107
+ offset += 4
108
+ end
109
+ end
110
+ end
111
+ @offset = limit
112
+ else
113
+ target.replace(vector(format, width))
114
+ end
115
+ end
116
+
83
117
  # @rbs return: Array[Symbol]
84
118
  def types
85
119
  vector("C", 1).map { |id| TYPES[id] || raise(Invalid) }
@@ -87,7 +121,7 @@ module Wardite
87
121
 
88
122
  # @rbs return: void
89
123
  def finish
90
- raise Invalid unless @offset == @bytes.bytesize
124
+ raise Invalid unless @offset == @limit
91
125
  end
92
126
 
93
127
  private
@@ -95,7 +129,7 @@ module Wardite
95
129
  # @rbs length: Integer
96
130
  # @rbs return: void
97
131
  def ensure_bytes(length)
98
- raise Invalid if length > @bytes.bytesize - @offset
132
+ raise Invalid if length > @limit - @offset
99
133
  end
100
134
  end
101
135
 
@@ -178,6 +212,8 @@ module Wardite
178
212
  class Decoder
179
213
  include Opcode
180
214
 
215
+ attr_reader :functions #: Array[Function]
216
+
181
217
  # Reuse the semantic register roles for fixed operands. Lowering
182
218
  # moves direct call arguments into a side table and leaves optional
183
219
  # destinations and return operands to be checked against signatures.
@@ -210,13 +246,18 @@ module Wardite
210
246
  end
211
247
  end.freeze #: Array[Symbol?]
212
248
 
213
- # @rbs reader: Reader
249
+ # @rbs payload: String
214
250
  # @rbs instance: Wardite::Instance
215
251
  # @rbs entries: Array[FunctionEntry]
216
- def initialize(reader, instance, entries)
217
- @reader = reader
218
- @instance = instance
252
+ def initialize(payload, instance, entries)
253
+ @payload = payload
254
+ @reader = Reader.new(payload)
219
255
  @entries = entries
256
+ @bodies = instance.code_section&.func_codes || []
257
+ @tags = instance.tags
258
+ @functions = []
259
+ @offsets = [] #: Array[Integer]
260
+ @lengths = [] #: Array[Integer]
220
261
  @import_count = instance.import_section.imports.size
221
262
  @defined_count = entries.size - @import_count
222
263
  @data_count = instance.data_section&.segments&.size || 0
@@ -232,56 +273,71 @@ module Wardite
232
273
  end
233
274
  end
234
275
 
235
- # @rbs return: Array[Function]
236
- def decode
237
- raise Invalid unless @reader.count(4) == @defined_count
276
+ # @rbs layout: String
277
+ # @rbs return: void
278
+ def declare(layout)
279
+ raise Invalid unless @reader.count(8) == @defined_count && @bodies.size == @defined_count
280
+ @defined_count.times do
281
+ @offsets << @reader.integer
282
+ @lengths << @reader.integer
283
+ end
284
+ raise Invalid unless @reader.bytes(@reader.count(1)) == layout
285
+
286
+ cursor = @reader.offset
287
+ @defined_count.times do |pool_index|
288
+ offset = @offsets.fetch(pool_index)
289
+ length = @lengths.fetch(pool_index)
290
+ raise Invalid unless offset == cursor && length > 0 && length <= @payload.bytesize - cursor
291
+ cursor += length
238
292
 
239
- functions = [] #: Array[Function]
240
- call_records = [] #: Array[Array[[Integer, Array[Integer]]]]
241
- bodies = @instance.code_section&.func_codes || []
242
- bodies.each_with_index do |body, pool_index|
243
293
  index = @import_count + pool_index
244
- function = read_function(body, @entries.fetch(index), index)
245
- functions << function
246
- call_records << read_sites(function)
294
+ entry = @entries.fetch(index)
295
+ function = Function.new(index, entry.parameter_types, entry.result_types, 0, pool_index: pool_index)
296
+ function.cache_pending = true
297
+ @functions << function
247
298
  end
248
- @reader.finish
299
+ raise Invalid unless cursor == @payload.bytesize
300
+ end
249
301
 
250
- functions.zip(call_records).each do |function, records|
251
- raise Invalid unless records
252
- records.each do |index, arguments|
253
- callee = functions.fetch(index)
254
- check_arguments(function, arguments, callee.parameter_types)
255
- function.add_call_site(CallSite.new(callee, arguments))
256
- end
257
- check_code(function)
258
- end
259
- functions
302
+ # A failed decode must never expose a partially filled function. Keep
303
+ # the slot unavailable even if a Ruby caller catches the error.
304
+ # @rbs function: Function
305
+ # @rbs return: void
306
+ def restore(function)
307
+ index = function.pool_index
308
+ length = @lengths.fetch(index)
309
+ raise Invalid unless length > 0
310
+ @lengths[index] = 0
311
+ @reader = Reader.new(@payload, offset: @offsets.fetch(index), length: length)
312
+ read_function(@bodies.fetch(index), function)
313
+ read_sites(function, @functions)
314
+ @reader.finish
315
+ check_code(function)
316
+ function.cache_pending = false
260
317
  end
261
318
 
262
319
  private
263
320
 
264
321
  # @rbs body: Wardite::CodeSection::CodeBody
265
- # @rbs entry: FunctionEntry
266
- # @rbs index: Integer
267
- # @rbs return: Function
268
- def read_function(body, entry, index)
322
+ # @rbs function: Function
323
+ # @rbs return: void
324
+ def read_function(body, function)
269
325
  flags = @reader.integer
270
326
  raise Invalid unless flags.between?(0, FUNCTION_FLAGS)
271
327
 
272
328
  types = @reader.types
273
- params = entry.parameter_types
329
+ params = function.parameter_types
274
330
  first_local = params.size
275
- first_temporary = first_local + body.locals_count.sum
331
+ function.local_count = body.locals_count.sum
332
+ first_temporary = first_local + function.local_count
276
333
  raise Invalid unless first_temporary <= types.size && types.take(first_local) == params
277
334
 
278
335
  local_index = first_local
279
- body.locals_type.zip(body.locals_count).each do |type, count|
280
- raise Invalid unless count && types.slice(local_index, count)&.all? { |actual| actual == type }
336
+ body.locals_type.each_with_index do |type, index|
337
+ count = body.locals_count.fetch(index)
338
+ raise Invalid unless types.slice(local_index, count)&.all? { |actual| actual == type }
281
339
  local_index += count
282
340
  end
283
- locals = types.slice(first_local, first_temporary - first_local) || raise(Invalid)
284
- function = Function.new(index, params, entry.result_types, locals.size, local_types: locals, pool_index: entry.defined_index)
285
341
  function.uses_i64 = (flags & USES_I64) != 0
286
342
  function.uses_float = (flags & USES_FLOAT) != 0
287
343
  function.uses_eh = (flags & USES_EH) != 0
@@ -289,9 +345,11 @@ module Wardite
289
345
  function.uses_dynamic_calls = (flags & USES_DYNAMIC_CALLS) != 0
290
346
  raise Invalid if !function.uses_eh && types.include?(:exnref)
291
347
 
292
- initial = @reader.vector("q<", 8)
348
+ initial = function.initial_registers
349
+ @reader.read_into(initial, "q<", 8)
293
350
  raise Invalid unless initial.size == types.size
294
- constants = @reader.vector("l<", 4)
351
+ constants = function.constant_registers
352
+ @reader.read_into(constants, "l<", 4)
295
353
  previous = first_temporary - 1
296
354
  constants.each do |slot|
297
355
  raise Invalid unless slot > previous && slot < types.size
@@ -308,24 +366,25 @@ module Wardite
308
366
  end
309
367
  end
310
368
  function.register_types.replace(types)
311
- function.initial_registers.replace(initial)
312
- function.constant_registers.replace(constants)
313
369
 
314
- code = @reader.vector("q<", 8)
370
+ code = function.bytecode
371
+ @reader.read_into(code, "q<", 8)
315
372
  raise Invalid if code.empty? || code.size % Lowerer::WIDTH != 0
316
- # Keep the lowerer's integer array representation in Spinel.
317
- function.bytecode.replace(code)
318
- function
319
373
  end
320
374
 
321
375
  # @rbs function: Function
322
- # @rbs return: Array[[Integer, Array[Integer]]]
323
- def read_sites(function)
324
- calls = Array.new(@reader.count(8)) do
376
+ # @rbs functions: Array[Function]
377
+ # @rbs return: void
378
+ def read_sites(function, functions)
379
+ @reader.count(8).times do
325
380
  index = @reader.integer
326
381
  raise Invalid unless index.between?(0, @defined_count - 1)
327
- [index, @reader.vector("l<", 4)]
328
- end #: Array[[Integer, Array[Integer]]]
382
+ callee = functions[index] || raise(Invalid)
383
+ site = CallSite.new(callee, [])
384
+ @reader.read_into(site.arguments, "l<", 4)
385
+ check_arguments(function, site.arguments, callee.parameter_types)
386
+ function.add_call_site(site)
387
+ end
329
388
  @reader.count(20).times { function.dynamic_sites << read_dynamic_site(function) }
330
389
  @reader.count(16).times { function.memory_sites << read_memory_site(function) }
331
390
  @reader.count(8).times do
@@ -339,7 +398,6 @@ module Wardite
339
398
  clauses = Array.new(@reader.count(20)) { read_catch(function, handler_count) }
340
399
  function.flat_handlers << HandlerDescriptor.new(clauses)
341
400
  end
342
- calls
343
401
  end
344
402
 
345
403
  # @rbs function: Function
@@ -349,7 +407,6 @@ module Wardite
349
407
  table_index = @reader.integer
350
408
  params = @reader.types
351
409
  results = @reader.types
352
- arguments = @reader.vector("l<", 4)
353
410
  if host_index == -1
354
411
  raise Invalid unless table_index == 0 && @table_type == :funcref &&
355
412
  @signatures.key?([params, results]) && results.size <= 1 &&
@@ -359,8 +416,10 @@ module Wardite
359
416
  host = @entries.fetch(host_index)
360
417
  raise Invalid unless params == host.parameter_types && results == host.result_types
361
418
  end
362
- check_arguments(function, arguments, params)
363
- DynamicCallSite.new(host_index, arguments, params, results, table_index: table_index)
419
+ site = DynamicCallSite.new(host_index, [], params, results, table_index: table_index)
420
+ @reader.read_into(site.arguments, "l<", 4)
421
+ check_arguments(function, site.arguments, params)
422
+ site
364
423
  end
365
424
 
366
425
  # @rbs function: Function
@@ -439,7 +498,7 @@ module Wardite
439
498
  # @rbs tag: Integer
440
499
  # @rbs return: Array[Symbol]
441
500
  def tag_types(tag)
442
- at(@instance.tags, tag).parameter_types
501
+ at(@tags, tag).parameter_types
443
502
  end
444
503
 
445
504
  # @rbs function: Function
@@ -479,7 +538,8 @@ module Wardite
479
538
  # @rbs wasm: String
480
539
  # @rbs configuration: Configuration
481
540
  # @rbs verify: Symbol
482
- def initialize(directory, wasm, configuration, verify: :checksum)
541
+ # @rbs eager: bool
542
+ def initialize(directory, wasm, configuration, verify: :checksum, eager: false)
483
543
  versions = [FORMAT_VERSION, CODE_VERSION].pack("L<2")
484
544
  disabled = configuration.disabled.uniq.sort.join(",")
485
545
  key_data = versions + Digest::SHA256.digest(wasm) + disabled
@@ -490,39 +550,71 @@ module Wardite
490
550
  @directory = File.expand_path(directory)
491
551
  @path = File.join(@directory, "#{key.unpack1("H*")}.mir2")
492
552
  @verify = verify
553
+ @eager = eager
554
+ @decoder = nil #: Decoder?
493
555
  end
494
556
 
495
557
  # Restore against module declarations so a miss can decode and check the
496
558
  # Wasm bodies before Store initialization or any host lookup.
497
559
  # @rbs instance: Wardite::Instance
498
560
  # @rbs return: Array[Function]?
499
- def read(instance)
500
- reader = Reader.new(read_verified_payload)
561
+ def read_functions(instance)
562
+ payload = read_verified_payload
501
563
  entries = module_entries(instance)
502
- raise Invalid unless reader.bytes(reader.count(1)) == encode_layout(instance, entries)
503
- functions = Decoder.new(reader, instance, entries).decode
564
+ decoder = Decoder.new(payload, instance, entries)
565
+ decoder.declare(encode_layout(instance, entries))
566
+ if @eager
567
+ decoder.functions.each { |function| decoder.restore(function) }
568
+ else
569
+ @decoder = decoder
570
+ end
504
571
  $stderr.puts "MIR2 cache hit: #{@path}" if ENV["WARDITE_TRACE"]
505
- functions
572
+ decoder.functions
506
573
  rescue SystemCallError, IOError, Invalid
507
574
  $stderr.puts "MIR2 cache miss: #{@path}" if ENV["WARDITE_TRACE"]
508
575
  nil
509
576
  end
510
577
 
578
+ # @rbs function: Function
579
+ # @rbs return: void
580
+ def restore_function(function)
581
+ return unless function.cache_pending
582
+
583
+ decoder = @decoder || raise(Invalid)
584
+ decoder.restore(function)
585
+ rescue Invalid
586
+ raise Wardite::EvalError, "invalid MIR2 function #{function.index} in #{@path}. Delete this cache file and retry."
587
+ end
588
+
589
+ # @rbs return: void
590
+ def restore_all
591
+ decoder = @decoder
592
+ return unless decoder
593
+
594
+ decoder.functions.each { |function| restore_function(function) }
595
+ @decoder = nil
596
+ end
597
+
511
598
  # @rbs instance: Wardite::Instance
512
599
  # @rbs ir: IR
513
600
  # @rbs return: void
514
- def write(instance, ir)
601
+ def write_ir(instance, ir)
515
602
  FileUtils.mkdir_p(@directory)
516
- writer = Writer.new
517
603
  layout = encode_layout(instance, ir.entries)
518
- writer.integers(layout.bytesize)
519
- writer.bytes << layout
520
- writer.integers(ir.functions.size)
604
+ table = Writer.new
605
+ table.integers(ir.functions.size)
606
+ records = Writer.new
607
+ offset = 8 + 8 * ir.functions.size + layout.bytesize
521
608
  ir.functions.each do |function|
522
- writer.function(function)
523
- return if @header.bytesize + INTEGRITY_SIZE + writer.bytes.bytesize > MAX_BYTES
524
- end
525
- payload = writer.bytes
609
+ start = records.bytes.bytesize
610
+ records.function(function)
611
+ table.integers(offset + start, records.bytes.bytesize - start)
612
+ return if @header.bytesize + INTEGRITY_SIZE + offset + records.bytes.bytesize > MAX_BYTES
613
+ end
614
+ table.integers(layout.bytesize)
615
+ payload = table.bytes
616
+ payload << layout
617
+ payload << records.bytes
526
618
  length = [payload.bytesize].pack("Q<")
527
619
  prefix = @header + length + MIRCache.sample_checksum(payload, length) + Digest::SHA256.digest(payload)
528
620
  MIRCache.publish(@directory, @path, prefix, payload)
@@ -149,7 +149,8 @@ module Wardite
149
149
  frames << SavedFrame.new(pool_index, pc, return_register, registers, handlers)
150
150
  end
151
151
  raise MIRCache::Invalid if frames.empty?
152
- frames.each_with_index { |frame, index| check_frame(functions, frames, index) }
152
+ cache = vm.mir_cache || raise(MIRCache::Invalid)
153
+ frames.each_with_index { |frame, index| check_frame(functions, frames, index, cache) }
153
154
  memory = store.memories[0]
154
155
  pages = reader.integer
155
156
  used = reader.vector("l<", 4)
@@ -191,10 +192,12 @@ module Wardite
191
192
  # @rbs functions: Array[Wardite::Efflorescence::Function]
192
193
  # @rbs frames: Array[Wardite::Efflorescence::SavedFrame]
193
194
  # @rbs index: Integer
195
+ # @rbs cache: Wardite::Efflorescence::MIRCache
194
196
  # @rbs return: void
195
- def check_frame(functions, frames, index)
197
+ def check_frame(functions, frames, index, cache)
196
198
  frame = frames.fetch(index)
197
199
  function = functions[frame.pool_index] || raise(MIRCache::Invalid)
200
+ cache.restore_function(function)
198
201
  code = function.bytecode
199
202
  pc = frame.pc
200
203
  raise MIRCache::Invalid unless pc >= 0 && pc < code.size && pc % Lowerer::WIDTH == 0
@@ -47,7 +47,7 @@ module Wardite
47
47
  translator = Translator.new(instance)
48
48
  linked = translator.link
49
49
  if mir_cache && !profile && !cache_checked
50
- cached_functions = mir_cache.read(instance)
50
+ cached_functions = mir_cache.read_functions(instance)
51
51
  end
52
52
  @mir_cache_hit = !cached_functions.nil?
53
53
  @ir = if cached_functions
@@ -56,7 +56,7 @@ module Wardite
56
56
  build_mir(translator, linked, profile)
57
57
  end
58
58
  if mir_cache && !profile && !@mir_cache_hit
59
- mir_cache.write(instance, @ir)
59
+ mir_cache.write_ir(instance, @ir)
60
60
  end
61
61
  start = instance.start_section
62
62
  if start
@@ -170,6 +170,7 @@ module Wardite
170
170
 
171
171
  # @rbs return: void
172
172
  def restore_inspection_ir
173
+ @mir_cache&.restore_all
173
174
  linked = IR.new([], entries: @ir.entries, hosts: @ir.hosts)
174
175
  build_mir(Translator.new(@instance), linked, false)
175
176
  end
@@ -485,7 +486,7 @@ module Wardite
485
486
  # @rbs return: Array[Wardite::Efflorescence::FramePool]
486
487
  def new_pools
487
488
  pools = [] #: Array[Wardite::Efflorescence::FramePool]
488
- @ir.functions.each { |function| pools << FramePool.new(function, @reuse_frames) }
489
+ @ir.functions.each { |function| pools << FramePool.new(function, @reuse_frames, @mir_cache) }
489
490
  pools
490
491
  end
491
492
 
data/lib/wardite/load.rb CHANGED
@@ -331,8 +331,9 @@ module Wardite
331
331
  # @rbs mir_profile: bool
332
332
  # @rbs mir_cache: String?
333
333
  # @rbs mir_cache_verify: Symbol
334
+ # @rbs mir_cache_eager: bool
334
335
  # @rbs return: Instance
335
- def self.load_from_buffer(buf, import_object: {}, enable_wasi: true, engine: :stack, disabled_optimizations: [], mir_profile: false, mir_cache: nil, mir_cache_verify: :checksum)
336
+ def self.load_from_buffer(buf, import_object: {}, enable_wasi: true, engine: :stack, disabled_optimizations: [], mir_profile: false, mir_cache: nil, mir_cache_verify: :checksum, mir_cache_eager: false)
336
337
  start = Time.now.to_f #: Float
337
338
  unless mir_cache_verify == :checksum || mir_cache_verify == :sha256
338
339
  raise ArgumentError, "MIR cache verification must be checksum or sha256"
@@ -347,7 +348,7 @@ module Wardite
347
348
  bytes = buf.read || "".b
348
349
  configuration = Efflorescence::Configuration.new(disabled_optimizations)
349
350
  disabled_optimizations = configuration.disabled
350
- cache = Efflorescence::MIRCache.new(mir_cache, bytes, configuration, verify: mir_cache_verify)
351
+ cache = Efflorescence::MIRCache.new(mir_cache, bytes, configuration, verify: mir_cache_verify, eager: mir_cache_eager)
351
352
  @buf = StringIO.new(bytes)
352
353
  end
353
354
  end
@@ -2,5 +2,5 @@
2
2
  # rbs_inline: enabled
3
3
 
4
4
  module Wardite
5
- VERSION = "1.1.0" #: String
5
+ VERSION = "1.2.0" #: String
6
6
  end
data/lib/wardite.rb CHANGED
@@ -66,7 +66,7 @@ module Wardite
66
66
  check_module_features(engine)
67
67
  cached_functions = nil #: Array[Efflorescence::Function]?
68
68
  if engine == :efflorescence && mir_cache && !mir_profile
69
- cached_functions = mir_cache.read(self)
69
+ cached_functions = mir_cache.read_functions(self)
70
70
  end
71
71
  types = type_section
72
72
  code_section&.func_codes&.each do |body|