wardite 1.0.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.
Files changed (64) hide show
  1. checksums.yaml +4 -4
  2. data/Makefile +9 -1
  3. data/README.md +65 -7
  4. data/Steepfile +1 -0
  5. data/assets/wardite.svg +12 -0
  6. data/benchmark/count_ruby_wasm_functions.rb +37 -0
  7. data/benchmark/measure_mir_cache_restore.rb +59 -0
  8. data/benchmark/measure_mir_cache_verify.rb +58 -0
  9. data/benchmark/measure_ruby_wasm_cache_hit.rb +59 -0
  10. data/benchmark/measure_ruby_wasm_startup.rb +43 -0
  11. data/benchmark/results/efflorescence-mir2-cache-integrity.json +390 -0
  12. data/benchmark/results/efflorescence-mir2-function-restore.json +480 -0
  13. data/benchmark/results/efflorescence-unboxed-globals.json +3451 -0
  14. data/docs/adr/0007-efflorescence-ruby-wasm-phase1.md +75 -0
  15. data/docs/adr/0008-efflorescence-ruby-wasm-phase2.md +75 -0
  16. data/docs/adr/0009-efflorescence-mir2-cache-integrity-modes.md +77 -0
  17. data/docs/adr/0010-efflorescence-mir2-cache-function-restore.md +80 -0
  18. data/docs/adr/0011-efflorescence-unboxed-globals.md +89 -0
  19. data/docs/adr/0012-efflorescence-startup-snapshot.md +173 -0
  20. data/docs/adr/0013-efflorescence-frame-acquisition.md +114 -0
  21. data/docs/efflorescence-generated-c-guards.md +5 -0
  22. data/docs/efflorescence-mir2-cache.md +152 -0
  23. data/docs/efflorescence-ruby-wasm-phase1.md +90 -0
  24. data/docs/efflorescence-spinel-linear-memory.md +74 -0
  25. data/docs/efflorescence-startup-snapshot.md +60 -0
  26. data/docs/efflorescence-unboxed-globals.md +61 -0
  27. data/lib/wardite/alu_f32.generated.rb +10 -2
  28. data/lib/wardite/alu_f64.generated.rb +10 -2
  29. data/lib/wardite/alu_i32.generated.rb +40 -8
  30. data/lib/wardite/alu_i64.generated.rb +55 -11
  31. data/lib/wardite/cli/cli.rb +58 -6
  32. data/lib/wardite/efflorescence/ir.rb +26 -4
  33. data/lib/wardite/efflorescence/mir_cache.rb +749 -0
  34. data/lib/wardite/efflorescence/register_validation.rb +128 -56
  35. data/lib/wardite/efflorescence/snapshot.rb +232 -0
  36. data/lib/wardite/efflorescence/store_access.rb +103 -8
  37. data/lib/wardite/efflorescence/translator.rb +10 -3
  38. data/lib/wardite/efflorescence/vm.rb +203 -38
  39. data/lib/wardite/efflorescence/wasi.rb +0 -56
  40. data/lib/wardite/efflorescence.rb +6 -0
  41. data/lib/wardite/load.rb +109 -24
  42. data/lib/wardite/version.rb +1 -1
  43. data/lib/wardite/wasi/spinel.rb +41 -0
  44. data/lib/wardite/wasi.rb +483 -268
  45. data/lib/wardite.rb +218 -70
  46. data/scripts/build_spinel_zig.rb +121 -0
  47. data/scripts/gen_alu.rb +55 -11
  48. data/scripts/verify_ruby_wasm.rb +70 -0
  49. data/sig/generated/wardite/cli/cli.rbs +15 -0
  50. data/sig/generated/wardite/efflorescence/ir.rbs +12 -2
  51. data/sig/generated/wardite/efflorescence/mir_cache.rbs +263 -0
  52. data/sig/generated/wardite/efflorescence/register_validation.rbs +31 -3
  53. data/sig/generated/wardite/efflorescence/snapshot.rbs +84 -0
  54. data/sig/generated/wardite/efflorescence/store_access.rbs +13 -2
  55. data/sig/generated/wardite/efflorescence/translator.rbs +5 -1
  56. data/sig/generated/wardite/efflorescence/vm.rbs +68 -7
  57. data/sig/generated/wardite/efflorescence/wasi.rbs +0 -13
  58. data/sig/generated/wardite/load.rbs +33 -5
  59. data/sig/generated/wardite/wasi/spinel.rbs +15 -0
  60. data/sig/generated/wardite/wasi.rbs +111 -4
  61. data/sig/generated/wardite.rbs +67 -3
  62. data/sig/io_buffer.rbs +7 -0
  63. data/sig/mir_cache_stdlib.rbs +5 -0
  64. metadata +32 -1
@@ -0,0 +1,749 @@
1
+ # frozen_string_literal: true
2
+ # rbs_inline: enabled
3
+
4
+ require "digest"
5
+ require "fileutils"
6
+ require "securerandom"
7
+
8
+ module Wardite
9
+ module Efflorescence
10
+ # Local, opt-in cache of the verified output of Lowerer. Bump CODE_VERSION
11
+ # when the generated code or its interpretation changes, including opcodes,
12
+ # optimizer/validator fixes, and changes to the metadata used by the VM.
13
+ class MIRCache
14
+ MAGIC = "WARDMIR\0".b
15
+ FORMAT_VERSION = 3
16
+ CODE_VERSION = 1
17
+ DIGEST_SIZE = 32
18
+ LENGTH_SIZE = 8
19
+ INTEGRITY_SIZE = LENGTH_SIZE + 2 * DIGEST_SIZE
20
+ SAMPLE_EDGE = 64 * 1024
21
+ SAMPLE_STEP = 1024 * 1024
22
+ SAMPLE_BLOCK = 4 * 1024
23
+ MAX_BYTES = 256 * 1024 * 1024
24
+ TYPES = %i[i32 i64 f32 f64 exnref].freeze
25
+ TYPE_IDS = TYPES.each_with_index.to_h.freeze
26
+ USES_I64 = 1
27
+ USES_FLOAT = 2
28
+ USES_EH = 4
29
+ USES_STORE = 8
30
+ USES_DYNAMIC_CALLS = 16
31
+ FUNCTION_FLAGS = USES_I64 | USES_FLOAT | USES_EH | USES_STORE | USES_DYNAMIC_CALLS
32
+
33
+ class Invalid < StandardError; end
34
+
35
+ # Identifies the module, the generated code, and the host build.
36
+ attr_reader :key #: String
37
+
38
+ # All records are little-endian. Vectors carry a nonnegative 32-bit element count.
39
+ # A record count is bounded by the bytes still available to decode it.
40
+ class Reader
41
+ attr_reader :offset #: Integer
42
+
43
+ # @rbs bytes: String
44
+ # @rbs offset: Integer
45
+ # @rbs length: Integer?
46
+ def initialize(bytes, offset: 0, length: nil)
47
+ @bytes = bytes
48
+ @offset = offset
49
+ @limit = length ? offset + length : bytes.bytesize
50
+ end
51
+
52
+ # @rbs length: Integer
53
+ # @rbs return: String
54
+ def bytes(length)
55
+ ensure_bytes(length)
56
+ result = @bytes.byteslice(@offset, length) || raise(Invalid)
57
+ @offset += length
58
+ result
59
+ end
60
+
61
+ # @rbs return: Integer
62
+ def integer
63
+ ensure_bytes(4)
64
+ result = @bytes.unpack1("l<", offset: @offset) #: Integer
65
+ @offset += 4
66
+ result
67
+ end
68
+
69
+ # @rbs width: Integer
70
+ # @rbs return: Integer
71
+ def count(width)
72
+ length = integer
73
+ raise Invalid if length < 0
74
+ ensure_bytes(length * width)
75
+ length
76
+ end
77
+
78
+ # @rbs format: String
79
+ # @rbs width: Integer
80
+ # @rbs return: Array[Integer]
81
+ def vector(format, width)
82
+ length = count(width)
83
+ result = @bytes.unpack("#{format}#{length}", offset: @offset) #: Array[Integer]
84
+ @offset += length * width
85
+ result
86
+ end
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
+
117
+ # @rbs return: Array[Symbol]
118
+ def types
119
+ vector("C", 1).map { |id| TYPES[id] || raise(Invalid) }
120
+ end
121
+
122
+ # @rbs return: void
123
+ def finish
124
+ raise Invalid unless @offset == @limit
125
+ end
126
+
127
+ private
128
+
129
+ # @rbs length: Integer
130
+ # @rbs return: void
131
+ def ensure_bytes(length)
132
+ raise Invalid if length > @limit - @offset
133
+ end
134
+ end
135
+
136
+ class Writer
137
+ attr_reader :bytes #: String
138
+
139
+ def initialize
140
+ @bytes = +"".b
141
+ end
142
+
143
+ # @rbs *values: Integer
144
+ # @rbs return: void
145
+ def integers(*values)
146
+ @bytes << values.pack("l<*")
147
+ end
148
+
149
+ # @rbs values: Array[Integer]
150
+ # @rbs format: String
151
+ # @rbs return: void
152
+ def vector(values, format = "l<")
153
+ integers(values.size)
154
+ @bytes << values.pack("#{format}*")
155
+ end
156
+
157
+ # @rbs types: Array[Symbol]
158
+ # @rbs return: void
159
+ def types(types)
160
+ vector(types.map { |type| TYPE_IDS.fetch(type) }, "C")
161
+ end
162
+
163
+ # @rbs function: Function
164
+ # @rbs return: void
165
+ def function(function)
166
+ flags = 0
167
+ flags |= USES_I64 if function.uses_i64
168
+ flags |= USES_FLOAT if function.uses_float
169
+ flags |= USES_EH if function.uses_eh
170
+ flags |= USES_STORE if function.uses_store
171
+ flags |= USES_DYNAMIC_CALLS if function.uses_dynamic_calls
172
+ integers(flags)
173
+ types(function.register_types)
174
+ vector(function.initial_registers, "q<")
175
+ vector(function.constant_registers)
176
+ vector(function.bytecode, "q<")
177
+ call_count = function.call_site_count
178
+ integers(call_count)
179
+ call_count.times do |index|
180
+ site = function.call_site(index)
181
+ integers(site.pool_index)
182
+ vector(site.arguments)
183
+ end
184
+ integers(function.dynamic_sites.size)
185
+ function.dynamic_sites.each do |site|
186
+ integers(site.host_index, site.table_index)
187
+ types(site.parameter_types)
188
+ types(site.result_types)
189
+ vector(site.arguments)
190
+ end
191
+ integers(function.memory_sites.size)
192
+ function.memory_sites.each do |site|
193
+ integers(site.memory_index, site.source_memory_index, site.data_index)
194
+ vector(site.sources)
195
+ end
196
+ integers(function.throw_sites.size)
197
+ function.throw_sites.each do |site|
198
+ integers(site.tag_index)
199
+ vector(site.payload_registers)
200
+ end
201
+ integers(function.flat_handlers.size)
202
+ function.flat_handlers.each do |handler|
203
+ integers(handler.clauses.size)
204
+ handler.clauses.each do |clause|
205
+ integers(clause.tag_index, clause.reference_register, clause.target_pc, clause.handler_depth)
206
+ vector(clause.payload_registers)
207
+ end
208
+ end
209
+ end
210
+ end
211
+
212
+ class Decoder
213
+ include Opcode
214
+
215
+ attr_reader :functions #: Array[Function]
216
+
217
+ # Reuse the semantic register roles for fixed operands. Lowering
218
+ # moves direct call arguments into a side table and leaves optional
219
+ # destinations and return operands to be checked against signatures.
220
+ REGISTER_MASKS = Opcode::NAMES.each_index.map do |opcode|
221
+ next 0 if opcode == CALL || opcode == RETURN
222
+
223
+ instruction = Instruction.new([opcode, 0, 0, 0])
224
+ positions = Opcode.read_positions(instruction)
225
+ positions << 1 if Opcode.destination(instruction) >= 0 && !Opcode.dynamic_call?(opcode)
226
+ positions.reduce(0) { |mask, position| mask | (1 << (position - 1)) }
227
+ end.freeze #: Array[Integer]
228
+
229
+ EXTRA_OPERANDS = Opcode::NAMES.each_index.map do |opcode|
230
+ case opcode
231
+ when BR then :branch
232
+ when BR_IF, BR_IF_ZERO then :conditional
233
+ when CALL then :call
234
+ when CALL_HOST, CALL_INDIRECT then :dynamic_call
235
+ when RETURN then :return
236
+ when EH_ENTER then :handler
237
+ when EH_TRIM then :depth
238
+ when THROW then :throw
239
+ when MEMORY_INIT, MEMORY_COPY, MEMORY_FILL then :bulk
240
+ when MEMORY_SIZE, MEMORY_GROW then :memory
241
+ when GLOBAL_GET, I64_GLOBAL_GET, F32_GLOBAL_GET, F64_GLOBAL_GET then :global_get
242
+ when GLOBAL_SET, I64_GLOBAL_SET, F32_GLOBAL_SET, F64_GLOBAL_SET then :global_set
243
+ when I32_LOAD..I32_STORE16, I64_LOAD..I64_STORE32, F32_LOAD..F64_STORE then :address
244
+ when I32_ADD_IMM..I32_SHR_U_IMM then :immediate
245
+ when I32_XOR_SHR_U_IMM, I32_XOR_SHL_IMM then :shift
246
+ end
247
+ end.freeze #: Array[Symbol?]
248
+
249
+ # @rbs payload: String
250
+ # @rbs instance: Wardite::Instance
251
+ # @rbs entries: Array[FunctionEntry]
252
+ def initialize(payload, instance, entries)
253
+ @payload = payload
254
+ @reader = Reader.new(payload)
255
+ @entries = entries
256
+ @bodies = instance.code_section&.func_codes || []
257
+ @tags = instance.tags
258
+ @functions = []
259
+ @offsets = [] #: Array[Integer]
260
+ @lengths = [] #: Array[Integer]
261
+ @import_count = instance.import_section.imports.size
262
+ @defined_count = entries.size - @import_count
263
+ @data_count = instance.data_section&.segments&.size || 0
264
+ @global_count = instance.global_section&.globals&.size || 0
265
+ @has_memory = (instance.memory_section&.limits&.size || 0) > 0
266
+ @table_type = instance.table_section&.table_types&.[](0) #: Symbol?
267
+ @signatures = {} #: Hash[[Array[Symbol], Array[Symbol]], bool]
268
+ types = instance.type_section
269
+ if types
270
+ types.defined_types.each_with_index do |params, index|
271
+ @signatures[[params, types.defined_results.fetch(index)]] = true
272
+ end
273
+ end
274
+ end
275
+
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
292
+
293
+ index = @import_count + pool_index
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
298
+ end
299
+ raise Invalid unless cursor == @payload.bytesize
300
+ end
301
+
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
317
+ end
318
+
319
+ private
320
+
321
+ # @rbs body: Wardite::CodeSection::CodeBody
322
+ # @rbs function: Function
323
+ # @rbs return: void
324
+ def read_function(body, function)
325
+ flags = @reader.integer
326
+ raise Invalid unless flags.between?(0, FUNCTION_FLAGS)
327
+
328
+ types = @reader.types
329
+ params = function.parameter_types
330
+ first_local = params.size
331
+ function.local_count = body.locals_count.sum
332
+ first_temporary = first_local + function.local_count
333
+ raise Invalid unless first_temporary <= types.size && types.take(first_local) == params
334
+
335
+ local_index = first_local
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 }
339
+ local_index += count
340
+ end
341
+ function.uses_i64 = (flags & USES_I64) != 0
342
+ function.uses_float = (flags & USES_FLOAT) != 0
343
+ function.uses_eh = (flags & USES_EH) != 0
344
+ function.uses_store = (flags & USES_STORE) != 0
345
+ function.uses_dynamic_calls = (flags & USES_DYNAMIC_CALLS) != 0
346
+ raise Invalid if !function.uses_eh && types.include?(:exnref)
347
+
348
+ initial = function.initial_registers
349
+ @reader.read_into(initial, "q<", 8)
350
+ raise Invalid unless initial.size == types.size
351
+ constants = function.constant_registers
352
+ @reader.read_into(constants, "l<", 4)
353
+ previous = first_temporary - 1
354
+ constants.each do |slot|
355
+ raise Invalid unless slot > previous && slot < types.size
356
+ previous = slot
357
+ end
358
+ constant_index = 0
359
+ initial.each_with_index do |bits, slot|
360
+ if slot == constants[constant_index]
361
+ type = types.fetch(slot)
362
+ raise Invalid if type == :exnref || ((type == :i32 || type == :f32) && !bits.between?(0, 0xffffffff))
363
+ constant_index += 1
364
+ else
365
+ raise Invalid unless bits.zero?
366
+ end
367
+ end
368
+ function.register_types.replace(types)
369
+
370
+ code = function.bytecode
371
+ @reader.read_into(code, "q<", 8)
372
+ raise Invalid if code.empty? || code.size % Lowerer::WIDTH != 0
373
+ end
374
+
375
+ # @rbs function: Function
376
+ # @rbs functions: Array[Function]
377
+ # @rbs return: void
378
+ def read_sites(function, functions)
379
+ @reader.count(8).times do
380
+ index = @reader.integer
381
+ raise Invalid unless index.between?(0, @defined_count - 1)
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
388
+ @reader.count(20).times { function.dynamic_sites << read_dynamic_site(function) }
389
+ @reader.count(16).times { function.memory_sites << read_memory_site(function) }
390
+ @reader.count(8).times do
391
+ tag = @reader.integer
392
+ registers = @reader.vector("l<", 4)
393
+ check_arguments(function, registers, tag_types(tag))
394
+ function.throw_sites << ThrowSite.new(tag, registers)
395
+ end
396
+ handler_count = @reader.count(4)
397
+ handler_count.times do
398
+ clauses = Array.new(@reader.count(20)) { read_catch(function, handler_count) }
399
+ function.flat_handlers << HandlerDescriptor.new(clauses)
400
+ end
401
+ end
402
+
403
+ # @rbs function: Function
404
+ # @rbs return: DynamicCallSite
405
+ def read_dynamic_site(function)
406
+ host_index = @reader.integer
407
+ table_index = @reader.integer
408
+ params = @reader.types
409
+ results = @reader.types
410
+ if host_index == -1
411
+ raise Invalid unless table_index == 0 && @table_type == :funcref &&
412
+ @signatures.key?([params, results]) && results.size <= 1 &&
413
+ (params + results).all? { |type| FunctionEntry.numeric_type?(type) }
414
+ else
415
+ raise Invalid unless table_index == -1 && host_index.between?(0, @import_count - 1)
416
+ host = @entries.fetch(host_index)
417
+ raise Invalid unless params == host.parameter_types && results == host.result_types
418
+ end
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
423
+ end
424
+
425
+ # @rbs function: Function
426
+ # @rbs return: MemorySite
427
+ def read_memory_site(function)
428
+ memory = @reader.integer
429
+ source = @reader.integer
430
+ data = @reader.integer
431
+ registers = @reader.vector("l<", 4)
432
+ raise Invalid unless @has_memory && memory == 0 && source == 0 && data.between?(-1, @data_count - 1)
433
+ check_arguments(function, registers, [:i32, :i32, :i32])
434
+ MemorySite.new(registers, memory_index: memory, source_memory_index: source, data_index: data)
435
+ end
436
+
437
+ # @rbs function: Function
438
+ # @rbs handler_count: Integer
439
+ # @rbs return: CatchTarget
440
+ def read_catch(function, handler_count)
441
+ tag = @reader.integer
442
+ reference = @reader.integer
443
+ pc = @reader.integer
444
+ depth = @reader.integer
445
+ registers = @reader.vector("l<", 4)
446
+ check_arguments(function, registers, tag == -1 ? [] : tag_types(tag))
447
+ raise Invalid unless reference == -1 || at(function.register_types, reference) == :exnref
448
+ raise Invalid unless depth.between?(0, handler_count - 1)
449
+ check_target(pc, function.bytecode.size)
450
+ CatchTarget.new(tag, registers, reference, pc, depth)
451
+ end
452
+
453
+ # @rbs function: Function
454
+ # @rbs return: void
455
+ def check_code(function)
456
+ code = function.bytecode
457
+ register_count = function.register_count
458
+ pc = 0
459
+ while pc < code.size
460
+ opcode, a, b, c = code[pc], code[pc + 1], code[pc + 2], code[pc + 3]
461
+ raise Invalid unless opcode.between?(0, REGISTER_MASKS.size - 1) && opcode != PROFILE
462
+ mask = REGISTER_MASKS.fetch(opcode)
463
+ raise Invalid if (mask[0] == 1 && !a.between?(0, register_count - 1)) ||
464
+ (mask[1] == 1 && !b.between?(0, register_count - 1)) ||
465
+ (mask[2] == 1 && !c.between?(0, register_count - 1))
466
+
467
+ case EXTRA_OPERANDS[opcode]
468
+ when :branch then check_target(a, code.size)
469
+ when :conditional then check_target(b, code.size)
470
+ when :call
471
+ raise Invalid unless b.between?(0, function.call_site_count - 1)
472
+ site = function.call_site(b)
473
+ expected = site.arguments.size == 1 ? site.arguments.fetch(0) : -1
474
+ raise Invalid unless c == expected
475
+ check_result(function, a, site.callee.result_types)
476
+ when :dynamic_call
477
+ site = at(function.dynamic_sites, b)
478
+ raise Invalid unless opcode == CALL_HOST ? (site.host_index >= 0 && c == 0) : site.table_index == 0
479
+ check_result(function, a, site.result_types)
480
+ when :return then check_result(function, a, function.result_types)
481
+ when :handler then at(function.flat_handlers, a)
482
+ when :depth then raise Invalid unless a.between?(0, function.flat_handlers.size)
483
+ when :throw then at(function.throw_sites, a)
484
+ when :bulk
485
+ site = at(function.memory_sites, a)
486
+ raise Invalid unless opcode == MEMORY_INIT ? site.data_index >= 0 : site.data_index == -1
487
+ when :global_get then raise Invalid unless b.between?(0, @global_count - 1)
488
+ when :global_set then raise Invalid unless a.between?(0, @global_count - 1)
489
+ when :address then raise Invalid unless @has_memory && c.between?(0, 0xffffffff)
490
+ when :memory then raise Invalid unless @has_memory
491
+ when :immediate then raise Invalid unless c.between?(0, 0xffffffff)
492
+ when :shift then raise Invalid unless c.between?(0, 31)
493
+ end
494
+ pc += Lowerer::WIDTH
495
+ end
496
+ end
497
+
498
+ # @rbs tag: Integer
499
+ # @rbs return: Array[Symbol]
500
+ def tag_types(tag)
501
+ at(@tags, tag).parameter_types
502
+ end
503
+
504
+ # @rbs function: Function
505
+ # @rbs registers: Array[Integer]
506
+ # @rbs types: Array[Symbol]
507
+ # @rbs return: void
508
+ def check_arguments(function, registers, types)
509
+ raise Invalid unless registers.size == types.size
510
+ registers.each_with_index do |slot, index|
511
+ raise Invalid unless at(function.register_types, slot) == types.fetch(index)
512
+ end
513
+ end
514
+
515
+ # @rbs function: Function
516
+ # @rbs slot: Integer
517
+ # @rbs types: Array[Symbol]
518
+ # @rbs return: void
519
+ def check_result(function, slot, types)
520
+ raise Invalid unless types.empty? ? slot == -1 : at(function.register_types, slot) == types.fetch(0)
521
+ end
522
+
523
+ # @rbs target: Integer
524
+ # @rbs limit: Integer
525
+ # @rbs return: void
526
+ def check_target(target, limit)
527
+ raise Invalid unless target.between?(0, limit - 1) && target % Lowerer::WIDTH == 0
528
+ end
529
+
530
+ # @rbs [T] (Array[T] values, Integer index) -> T
531
+ def at(values, index)
532
+ raise Invalid unless index.between?(0, values.size - 1)
533
+ values.fetch(index)
534
+ end
535
+ end
536
+
537
+ # @rbs directory: String
538
+ # @rbs wasm: String
539
+ # @rbs configuration: Configuration
540
+ # @rbs verify: Symbol
541
+ # @rbs eager: bool
542
+ def initialize(directory, wasm, configuration, verify: :checksum, eager: false)
543
+ versions = [FORMAT_VERSION, CODE_VERSION].pack("L<2")
544
+ disabled = configuration.disabled.uniq.sort.join(",")
545
+ key_data = versions + Digest::SHA256.digest(wasm) + disabled
546
+ key_data = "spinel\0".b + key_data if RUBY_ENGINE == "spinel"
547
+ key = Digest::SHA256.digest(key_data)
548
+ @key = key
549
+ @header = MAGIC + versions + key
550
+ @directory = File.expand_path(directory)
551
+ @path = File.join(@directory, "#{key.unpack1("H*")}.mir2")
552
+ @verify = verify
553
+ @eager = eager
554
+ @decoder = nil #: Decoder?
555
+ end
556
+
557
+ # Restore against module declarations so a miss can decode and check the
558
+ # Wasm bodies before Store initialization or any host lookup.
559
+ # @rbs instance: Wardite::Instance
560
+ # @rbs return: Array[Function]?
561
+ def read_functions(instance)
562
+ payload = read_verified_payload
563
+ entries = module_entries(instance)
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
571
+ $stderr.puts "MIR2 cache hit: #{@path}" if ENV["WARDITE_TRACE"]
572
+ decoder.functions
573
+ rescue SystemCallError, IOError, Invalid
574
+ $stderr.puts "MIR2 cache miss: #{@path}" if ENV["WARDITE_TRACE"]
575
+ nil
576
+ end
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
+
598
+ # @rbs instance: Wardite::Instance
599
+ # @rbs ir: IR
600
+ # @rbs return: void
601
+ def write_ir(instance, ir)
602
+ FileUtils.mkdir_p(@directory)
603
+ layout = encode_layout(instance, ir.entries)
604
+ table = Writer.new
605
+ table.integers(ir.functions.size)
606
+ records = Writer.new
607
+ offset = 8 + 8 * ir.functions.size + layout.bytesize
608
+ ir.functions.each do |function|
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
618
+ length = [payload.bytesize].pack("Q<")
619
+ prefix = @header + length + MIRCache.sample_checksum(payload, length) + Digest::SHA256.digest(payload)
620
+ MIRCache.publish(@directory, @path, prefix, payload)
621
+ rescue SystemCallError, IOError
622
+ # Cache I/O is optional once the normal build has succeeded.
623
+ nil
624
+ end
625
+
626
+ private
627
+
628
+ # @rbs instance: Wardite::Instance
629
+ # @rbs return: Array[FunctionEntry]
630
+ def module_entries(instance)
631
+ imports = instance.import_section.imports
632
+ types = instance.type_section
633
+ entries = [] #: Array[FunctionEntry]
634
+ imports.each_with_index do |import, index|
635
+ params = types&.defined_types&.[](import.sig_index)
636
+ results = types&.defined_results&.[](import.sig_index)
637
+ raise Invalid unless params && results
638
+ entries << FunctionEntry.new(:host, params, results, -1, index)
639
+ end
640
+ instance.each_defined_function do |params, results, _body|
641
+ entries << FunctionEntry.new(:defined, params, results, entries.size - imports.size, -1)
642
+ end
643
+ entries
644
+ rescue Wardite::LoadError
645
+ # Keep the usual Wasm validation path and its errors on a miss.
646
+ raise Invalid
647
+ end
648
+
649
+ # @rbs return: String
650
+ def read_verified_payload
651
+ header_size = @header.bytesize
652
+ prefix_size = header_size + INTEGRITY_SIZE
653
+ contents = MIRCache.read_contents(@path, @header, prefix_size)
654
+ length = [contents.bytesize - prefix_size].pack("Q<")
655
+ raise Invalid unless contents.byteslice(header_size, LENGTH_SIZE) == length
656
+
657
+ payload = contents.byteslice(prefix_size..) || raise(Invalid)
658
+ digest_offset = header_size + LENGTH_SIZE
659
+ if @verify == :sha256
660
+ digest_offset += DIGEST_SIZE
661
+ digest = Digest::SHA256.digest(payload)
662
+ else
663
+ digest = MIRCache.sample_checksum(payload, length)
664
+ end
665
+ raise Invalid unless contents.byteslice(digest_offset, DIGEST_SIZE) == digest
666
+ payload
667
+ end
668
+
669
+ # @rbs payload: String
670
+ # @rbs length: String
671
+ # @rbs return: String
672
+ def self.sample_checksum(payload, length)
673
+ size = payload.bytesize
674
+ return Digest::SHA256.digest(length + payload) if size <= 2 * SAMPLE_EDGE
675
+
676
+ sample = length.dup
677
+ sample << (payload.byteslice(0, SAMPLE_EDGE) || raise(Invalid))
678
+ offset = SAMPLE_STEP
679
+ while offset < size
680
+ sample << (payload.byteslice(offset, SAMPLE_BLOCK) || raise(Invalid))
681
+ offset += SAMPLE_STEP
682
+ end
683
+ sample << (payload.byteslice(size - SAMPLE_EDGE, SAMPLE_EDGE) || raise(Invalid))
684
+ Digest::SHA256.digest(sample)
685
+ end
686
+
687
+ # Opening without blocking keeps a FIFO from stalling the start of a run.
688
+ # @rbs path: String
689
+ # @rbs header: String
690
+ # @rbs prefix_size: Integer
691
+ # @rbs return: String
692
+ def self.read_contents(path, header, prefix_size)
693
+ contents = File.open(path, File::RDONLY | File::NONBLOCK) do |file|
694
+ stat = file.stat
695
+ raise Invalid unless stat.file? && stat.size <= MAX_BYTES
696
+ file.binmode
697
+ contents = file.read(stat.size) || raise(Invalid)
698
+ raise Invalid unless file.eof?
699
+ contents
700
+ end
701
+ raise Invalid unless contents.bytesize.between?(prefix_size, MAX_BYTES) && contents.start_with?(header)
702
+ contents
703
+ end
704
+
705
+ # Exclusive creation protects a concurrent writer's temporary file.
706
+ # Close the file before publishing it under the cache key.
707
+ # @rbs directory: String
708
+ # @rbs destination: String
709
+ # @rbs prefix: String
710
+ # @rbs payload: String
711
+ # @rbs return: void
712
+ def self.publish(directory, destination, prefix, payload)
713
+ path = File.join(directory, ".wardite-#{SecureRandom.hex(16)}.tmp")
714
+ file = File.open(path, File::WRONLY | File::CREAT | File::EXCL, 0o600)
715
+ begin
716
+ file.binmode
717
+ file.write(prefix)
718
+ file.write(payload)
719
+ file.close
720
+ File.rename(path, destination)
721
+ ensure
722
+ file.close unless file.closed?
723
+ File.unlink(path) if File.exist?(path)
724
+ end
725
+ end
726
+
727
+ # Include the module's import identities, and every function's signature
728
+ # and index mapping. The live entries and hosts are always linked afresh.
729
+ # @rbs instance: Wardite::Instance
730
+ # @rbs entries: Array[FunctionEntry]
731
+ # @rbs return: String
732
+ def encode_layout(instance, entries)
733
+ writer = Writer.new
734
+ imports = instance.import_section.imports
735
+ writer.integers(imports.size, entries.size)
736
+ imports.each do |import|
737
+ writer.integers(import.module_name.bytesize, import.name.bytesize)
738
+ writer.bytes << import.module_name.b << import.name.b
739
+ end
740
+ entries.each do |entry|
741
+ writer.integers(entry.defined_index, entry.host_index)
742
+ writer.types(entry.parameter_types)
743
+ writer.types(entry.result_types)
744
+ end
745
+ writer.bytes
746
+ end
747
+ end
748
+ end
749
+ end