wardite 1.0.0 → 1.1.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 (60) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +33 -7
  3. data/Steepfile +1 -0
  4. data/assets/wardite.svg +12 -0
  5. data/benchmark/measure_mir_cache_verify.rb +58 -0
  6. data/benchmark/measure_ruby_wasm_cache_hit.rb +59 -0
  7. data/benchmark/measure_ruby_wasm_startup.rb +43 -0
  8. data/benchmark/results/efflorescence-mir2-cache-integrity.json +390 -0
  9. data/benchmark/results/efflorescence-unboxed-globals.json +3451 -0
  10. data/docs/adr/0007-efflorescence-ruby-wasm-phase1.md +75 -0
  11. data/docs/adr/0008-efflorescence-ruby-wasm-phase2.md +75 -0
  12. data/docs/adr/0009-efflorescence-mir2-cache-integrity-modes.md +77 -0
  13. data/docs/adr/0010-efflorescence-mir2-cache-function-restore.md +80 -0
  14. data/docs/adr/0011-efflorescence-unboxed-globals.md +89 -0
  15. data/docs/adr/0012-efflorescence-startup-snapshot.md +173 -0
  16. data/docs/adr/0013-efflorescence-frame-acquisition.md +114 -0
  17. data/docs/efflorescence-generated-c-guards.md +5 -0
  18. data/docs/efflorescence-mir2-cache.md +123 -0
  19. data/docs/efflorescence-ruby-wasm-phase1.md +90 -0
  20. data/docs/efflorescence-spinel-linear-memory.md +72 -0
  21. data/docs/efflorescence-startup-snapshot.md +60 -0
  22. data/docs/efflorescence-unboxed-globals.md +61 -0
  23. data/lib/wardite/alu_f32.generated.rb +10 -2
  24. data/lib/wardite/alu_f64.generated.rb +10 -2
  25. data/lib/wardite/alu_i32.generated.rb +40 -8
  26. data/lib/wardite/alu_i64.generated.rb +55 -11
  27. data/lib/wardite/cli/cli.rb +56 -6
  28. data/lib/wardite/efflorescence/ir.rb +14 -1
  29. data/lib/wardite/efflorescence/mir_cache.rb +657 -0
  30. data/lib/wardite/efflorescence/register_validation.rb +128 -56
  31. data/lib/wardite/efflorescence/snapshot.rb +229 -0
  32. data/lib/wardite/efflorescence/store_access.rb +103 -8
  33. data/lib/wardite/efflorescence/translator.rb +10 -3
  34. data/lib/wardite/efflorescence/vm.rb +202 -38
  35. data/lib/wardite/efflorescence/wasi.rb +0 -56
  36. data/lib/wardite/efflorescence.rb +6 -0
  37. data/lib/wardite/load.rb +108 -24
  38. data/lib/wardite/version.rb +1 -1
  39. data/lib/wardite/wasi/spinel.rb +41 -0
  40. data/lib/wardite/wasi.rb +483 -268
  41. data/lib/wardite.rb +218 -70
  42. data/scripts/gen_alu.rb +55 -11
  43. data/scripts/verify_ruby_wasm.rb +70 -0
  44. data/sig/generated/wardite/cli/cli.rbs +15 -0
  45. data/sig/generated/wardite/efflorescence/ir.rbs +7 -0
  46. data/sig/generated/wardite/efflorescence/mir_cache.rbs +236 -0
  47. data/sig/generated/wardite/efflorescence/register_validation.rbs +31 -3
  48. data/sig/generated/wardite/efflorescence/snapshot.rbs +83 -0
  49. data/sig/generated/wardite/efflorescence/store_access.rbs +13 -2
  50. data/sig/generated/wardite/efflorescence/translator.rbs +5 -1
  51. data/sig/generated/wardite/efflorescence/vm.rbs +68 -7
  52. data/sig/generated/wardite/efflorescence/wasi.rbs +0 -13
  53. data/sig/generated/wardite/load.rbs +32 -5
  54. data/sig/generated/wardite/wasi/spinel.rbs +15 -0
  55. data/sig/generated/wardite/wasi.rbs +111 -4
  56. data/sig/generated/wardite.rbs +67 -3
  57. data/sig/mir_cache_stdlib.rbs +5 -0
  58. data/spinel/patches/0001-io-buffer-string-view.patch +699 -0
  59. data/spinel/patches/0002-io-buffer-allocation-error.patch +47 -0
  60. metadata +29 -1
@@ -0,0 +1,657 @@
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 = 2
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
+ # @rbs bytes: String
42
+ def initialize(bytes)
43
+ @bytes = bytes
44
+ @offset = 0
45
+ end
46
+
47
+ # @rbs length: Integer
48
+ # @rbs return: String
49
+ def bytes(length)
50
+ ensure_bytes(length)
51
+ result = @bytes.byteslice(@offset, length) || raise(Invalid)
52
+ @offset += length
53
+ result
54
+ end
55
+
56
+ # @rbs return: Integer
57
+ def integer
58
+ ensure_bytes(4)
59
+ result = @bytes.unpack1("l<", offset: @offset) #: Integer
60
+ @offset += 4
61
+ result
62
+ end
63
+
64
+ # @rbs width: Integer
65
+ # @rbs return: Integer
66
+ def count(width)
67
+ length = integer
68
+ raise Invalid if length < 0
69
+ ensure_bytes(length * width)
70
+ length
71
+ end
72
+
73
+ # @rbs format: String
74
+ # @rbs width: Integer
75
+ # @rbs return: Array[Integer]
76
+ def vector(format, width)
77
+ length = count(width)
78
+ result = @bytes.unpack("#{format}#{length}", offset: @offset) #: Array[Integer]
79
+ @offset += length * width
80
+ result
81
+ end
82
+
83
+ # @rbs return: Array[Symbol]
84
+ def types
85
+ vector("C", 1).map { |id| TYPES[id] || raise(Invalid) }
86
+ end
87
+
88
+ # @rbs return: void
89
+ def finish
90
+ raise Invalid unless @offset == @bytes.bytesize
91
+ end
92
+
93
+ private
94
+
95
+ # @rbs length: Integer
96
+ # @rbs return: void
97
+ def ensure_bytes(length)
98
+ raise Invalid if length > @bytes.bytesize - @offset
99
+ end
100
+ end
101
+
102
+ class Writer
103
+ attr_reader :bytes #: String
104
+
105
+ def initialize
106
+ @bytes = +"".b
107
+ end
108
+
109
+ # @rbs *values: Integer
110
+ # @rbs return: void
111
+ def integers(*values)
112
+ @bytes << values.pack("l<*")
113
+ end
114
+
115
+ # @rbs values: Array[Integer]
116
+ # @rbs format: String
117
+ # @rbs return: void
118
+ def vector(values, format = "l<")
119
+ integers(values.size)
120
+ @bytes << values.pack("#{format}*")
121
+ end
122
+
123
+ # @rbs types: Array[Symbol]
124
+ # @rbs return: void
125
+ def types(types)
126
+ vector(types.map { |type| TYPE_IDS.fetch(type) }, "C")
127
+ end
128
+
129
+ # @rbs function: Function
130
+ # @rbs return: void
131
+ def function(function)
132
+ flags = 0
133
+ flags |= USES_I64 if function.uses_i64
134
+ flags |= USES_FLOAT if function.uses_float
135
+ flags |= USES_EH if function.uses_eh
136
+ flags |= USES_STORE if function.uses_store
137
+ flags |= USES_DYNAMIC_CALLS if function.uses_dynamic_calls
138
+ integers(flags)
139
+ types(function.register_types)
140
+ vector(function.initial_registers, "q<")
141
+ vector(function.constant_registers)
142
+ vector(function.bytecode, "q<")
143
+ call_count = function.call_site_count
144
+ integers(call_count)
145
+ call_count.times do |index|
146
+ site = function.call_site(index)
147
+ integers(site.pool_index)
148
+ vector(site.arguments)
149
+ end
150
+ integers(function.dynamic_sites.size)
151
+ function.dynamic_sites.each do |site|
152
+ integers(site.host_index, site.table_index)
153
+ types(site.parameter_types)
154
+ types(site.result_types)
155
+ vector(site.arguments)
156
+ end
157
+ integers(function.memory_sites.size)
158
+ function.memory_sites.each do |site|
159
+ integers(site.memory_index, site.source_memory_index, site.data_index)
160
+ vector(site.sources)
161
+ end
162
+ integers(function.throw_sites.size)
163
+ function.throw_sites.each do |site|
164
+ integers(site.tag_index)
165
+ vector(site.payload_registers)
166
+ end
167
+ integers(function.flat_handlers.size)
168
+ function.flat_handlers.each do |handler|
169
+ integers(handler.clauses.size)
170
+ handler.clauses.each do |clause|
171
+ integers(clause.tag_index, clause.reference_register, clause.target_pc, clause.handler_depth)
172
+ vector(clause.payload_registers)
173
+ end
174
+ end
175
+ end
176
+ end
177
+
178
+ class Decoder
179
+ include Opcode
180
+
181
+ # Reuse the semantic register roles for fixed operands. Lowering
182
+ # moves direct call arguments into a side table and leaves optional
183
+ # destinations and return operands to be checked against signatures.
184
+ REGISTER_MASKS = Opcode::NAMES.each_index.map do |opcode|
185
+ next 0 if opcode == CALL || opcode == RETURN
186
+
187
+ instruction = Instruction.new([opcode, 0, 0, 0])
188
+ positions = Opcode.read_positions(instruction)
189
+ positions << 1 if Opcode.destination(instruction) >= 0 && !Opcode.dynamic_call?(opcode)
190
+ positions.reduce(0) { |mask, position| mask | (1 << (position - 1)) }
191
+ end.freeze #: Array[Integer]
192
+
193
+ EXTRA_OPERANDS = Opcode::NAMES.each_index.map do |opcode|
194
+ case opcode
195
+ when BR then :branch
196
+ when BR_IF, BR_IF_ZERO then :conditional
197
+ when CALL then :call
198
+ when CALL_HOST, CALL_INDIRECT then :dynamic_call
199
+ when RETURN then :return
200
+ when EH_ENTER then :handler
201
+ when EH_TRIM then :depth
202
+ when THROW then :throw
203
+ when MEMORY_INIT, MEMORY_COPY, MEMORY_FILL then :bulk
204
+ when MEMORY_SIZE, MEMORY_GROW then :memory
205
+ when GLOBAL_GET, I64_GLOBAL_GET, F32_GLOBAL_GET, F64_GLOBAL_GET then :global_get
206
+ when GLOBAL_SET, I64_GLOBAL_SET, F32_GLOBAL_SET, F64_GLOBAL_SET then :global_set
207
+ when I32_LOAD..I32_STORE16, I64_LOAD..I64_STORE32, F32_LOAD..F64_STORE then :address
208
+ when I32_ADD_IMM..I32_SHR_U_IMM then :immediate
209
+ when I32_XOR_SHR_U_IMM, I32_XOR_SHL_IMM then :shift
210
+ end
211
+ end.freeze #: Array[Symbol?]
212
+
213
+ # @rbs reader: Reader
214
+ # @rbs instance: Wardite::Instance
215
+ # @rbs entries: Array[FunctionEntry]
216
+ def initialize(reader, instance, entries)
217
+ @reader = reader
218
+ @instance = instance
219
+ @entries = entries
220
+ @import_count = instance.import_section.imports.size
221
+ @defined_count = entries.size - @import_count
222
+ @data_count = instance.data_section&.segments&.size || 0
223
+ @global_count = instance.global_section&.globals&.size || 0
224
+ @has_memory = (instance.memory_section&.limits&.size || 0) > 0
225
+ @table_type = instance.table_section&.table_types&.[](0) #: Symbol?
226
+ @signatures = {} #: Hash[[Array[Symbol], Array[Symbol]], bool]
227
+ types = instance.type_section
228
+ if types
229
+ types.defined_types.each_with_index do |params, index|
230
+ @signatures[[params, types.defined_results.fetch(index)]] = true
231
+ end
232
+ end
233
+ end
234
+
235
+ # @rbs return: Array[Function]
236
+ def decode
237
+ raise Invalid unless @reader.count(4) == @defined_count
238
+
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
+ index = @import_count + pool_index
244
+ function = read_function(body, @entries.fetch(index), index)
245
+ functions << function
246
+ call_records << read_sites(function)
247
+ end
248
+ @reader.finish
249
+
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
260
+ end
261
+
262
+ private
263
+
264
+ # @rbs body: Wardite::CodeSection::CodeBody
265
+ # @rbs entry: FunctionEntry
266
+ # @rbs index: Integer
267
+ # @rbs return: Function
268
+ def read_function(body, entry, index)
269
+ flags = @reader.integer
270
+ raise Invalid unless flags.between?(0, FUNCTION_FLAGS)
271
+
272
+ types = @reader.types
273
+ params = entry.parameter_types
274
+ first_local = params.size
275
+ first_temporary = first_local + body.locals_count.sum
276
+ raise Invalid unless first_temporary <= types.size && types.take(first_local) == params
277
+
278
+ 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 }
281
+ local_index += count
282
+ 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
+ function.uses_i64 = (flags & USES_I64) != 0
286
+ function.uses_float = (flags & USES_FLOAT) != 0
287
+ function.uses_eh = (flags & USES_EH) != 0
288
+ function.uses_store = (flags & USES_STORE) != 0
289
+ function.uses_dynamic_calls = (flags & USES_DYNAMIC_CALLS) != 0
290
+ raise Invalid if !function.uses_eh && types.include?(:exnref)
291
+
292
+ initial = @reader.vector("q<", 8)
293
+ raise Invalid unless initial.size == types.size
294
+ constants = @reader.vector("l<", 4)
295
+ previous = first_temporary - 1
296
+ constants.each do |slot|
297
+ raise Invalid unless slot > previous && slot < types.size
298
+ previous = slot
299
+ end
300
+ constant_index = 0
301
+ initial.each_with_index do |bits, slot|
302
+ if slot == constants[constant_index]
303
+ type = types.fetch(slot)
304
+ raise Invalid if type == :exnref || ((type == :i32 || type == :f32) && !bits.between?(0, 0xffffffff))
305
+ constant_index += 1
306
+ else
307
+ raise Invalid unless bits.zero?
308
+ end
309
+ end
310
+ function.register_types.replace(types)
311
+ function.initial_registers.replace(initial)
312
+ function.constant_registers.replace(constants)
313
+
314
+ code = @reader.vector("q<", 8)
315
+ 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
+ end
320
+
321
+ # @rbs function: Function
322
+ # @rbs return: Array[[Integer, Array[Integer]]]
323
+ def read_sites(function)
324
+ calls = Array.new(@reader.count(8)) do
325
+ index = @reader.integer
326
+ raise Invalid unless index.between?(0, @defined_count - 1)
327
+ [index, @reader.vector("l<", 4)]
328
+ end #: Array[[Integer, Array[Integer]]]
329
+ @reader.count(20).times { function.dynamic_sites << read_dynamic_site(function) }
330
+ @reader.count(16).times { function.memory_sites << read_memory_site(function) }
331
+ @reader.count(8).times do
332
+ tag = @reader.integer
333
+ registers = @reader.vector("l<", 4)
334
+ check_arguments(function, registers, tag_types(tag))
335
+ function.throw_sites << ThrowSite.new(tag, registers)
336
+ end
337
+ handler_count = @reader.count(4)
338
+ handler_count.times do
339
+ clauses = Array.new(@reader.count(20)) { read_catch(function, handler_count) }
340
+ function.flat_handlers << HandlerDescriptor.new(clauses)
341
+ end
342
+ calls
343
+ end
344
+
345
+ # @rbs function: Function
346
+ # @rbs return: DynamicCallSite
347
+ def read_dynamic_site(function)
348
+ host_index = @reader.integer
349
+ table_index = @reader.integer
350
+ params = @reader.types
351
+ results = @reader.types
352
+ arguments = @reader.vector("l<", 4)
353
+ if host_index == -1
354
+ raise Invalid unless table_index == 0 && @table_type == :funcref &&
355
+ @signatures.key?([params, results]) && results.size <= 1 &&
356
+ (params + results).all? { |type| FunctionEntry.numeric_type?(type) }
357
+ else
358
+ raise Invalid unless table_index == -1 && host_index.between?(0, @import_count - 1)
359
+ host = @entries.fetch(host_index)
360
+ raise Invalid unless params == host.parameter_types && results == host.result_types
361
+ end
362
+ check_arguments(function, arguments, params)
363
+ DynamicCallSite.new(host_index, arguments, params, results, table_index: table_index)
364
+ end
365
+
366
+ # @rbs function: Function
367
+ # @rbs return: MemorySite
368
+ def read_memory_site(function)
369
+ memory = @reader.integer
370
+ source = @reader.integer
371
+ data = @reader.integer
372
+ registers = @reader.vector("l<", 4)
373
+ raise Invalid unless @has_memory && memory == 0 && source == 0 && data.between?(-1, @data_count - 1)
374
+ check_arguments(function, registers, [:i32, :i32, :i32])
375
+ MemorySite.new(registers, memory_index: memory, source_memory_index: source, data_index: data)
376
+ end
377
+
378
+ # @rbs function: Function
379
+ # @rbs handler_count: Integer
380
+ # @rbs return: CatchTarget
381
+ def read_catch(function, handler_count)
382
+ tag = @reader.integer
383
+ reference = @reader.integer
384
+ pc = @reader.integer
385
+ depth = @reader.integer
386
+ registers = @reader.vector("l<", 4)
387
+ check_arguments(function, registers, tag == -1 ? [] : tag_types(tag))
388
+ raise Invalid unless reference == -1 || at(function.register_types, reference) == :exnref
389
+ raise Invalid unless depth.between?(0, handler_count - 1)
390
+ check_target(pc, function.bytecode.size)
391
+ CatchTarget.new(tag, registers, reference, pc, depth)
392
+ end
393
+
394
+ # @rbs function: Function
395
+ # @rbs return: void
396
+ def check_code(function)
397
+ code = function.bytecode
398
+ register_count = function.register_count
399
+ pc = 0
400
+ while pc < code.size
401
+ opcode, a, b, c = code[pc], code[pc + 1], code[pc + 2], code[pc + 3]
402
+ raise Invalid unless opcode.between?(0, REGISTER_MASKS.size - 1) && opcode != PROFILE
403
+ mask = REGISTER_MASKS.fetch(opcode)
404
+ raise Invalid if (mask[0] == 1 && !a.between?(0, register_count - 1)) ||
405
+ (mask[1] == 1 && !b.between?(0, register_count - 1)) ||
406
+ (mask[2] == 1 && !c.between?(0, register_count - 1))
407
+
408
+ case EXTRA_OPERANDS[opcode]
409
+ when :branch then check_target(a, code.size)
410
+ when :conditional then check_target(b, code.size)
411
+ when :call
412
+ raise Invalid unless b.between?(0, function.call_site_count - 1)
413
+ site = function.call_site(b)
414
+ expected = site.arguments.size == 1 ? site.arguments.fetch(0) : -1
415
+ raise Invalid unless c == expected
416
+ check_result(function, a, site.callee.result_types)
417
+ when :dynamic_call
418
+ site = at(function.dynamic_sites, b)
419
+ raise Invalid unless opcode == CALL_HOST ? (site.host_index >= 0 && c == 0) : site.table_index == 0
420
+ check_result(function, a, site.result_types)
421
+ when :return then check_result(function, a, function.result_types)
422
+ when :handler then at(function.flat_handlers, a)
423
+ when :depth then raise Invalid unless a.between?(0, function.flat_handlers.size)
424
+ when :throw then at(function.throw_sites, a)
425
+ when :bulk
426
+ site = at(function.memory_sites, a)
427
+ raise Invalid unless opcode == MEMORY_INIT ? site.data_index >= 0 : site.data_index == -1
428
+ when :global_get then raise Invalid unless b.between?(0, @global_count - 1)
429
+ when :global_set then raise Invalid unless a.between?(0, @global_count - 1)
430
+ when :address then raise Invalid unless @has_memory && c.between?(0, 0xffffffff)
431
+ when :memory then raise Invalid unless @has_memory
432
+ when :immediate then raise Invalid unless c.between?(0, 0xffffffff)
433
+ when :shift then raise Invalid unless c.between?(0, 31)
434
+ end
435
+ pc += Lowerer::WIDTH
436
+ end
437
+ end
438
+
439
+ # @rbs tag: Integer
440
+ # @rbs return: Array[Symbol]
441
+ def tag_types(tag)
442
+ at(@instance.tags, tag).parameter_types
443
+ end
444
+
445
+ # @rbs function: Function
446
+ # @rbs registers: Array[Integer]
447
+ # @rbs types: Array[Symbol]
448
+ # @rbs return: void
449
+ def check_arguments(function, registers, types)
450
+ raise Invalid unless registers.size == types.size
451
+ registers.each_with_index do |slot, index|
452
+ raise Invalid unless at(function.register_types, slot) == types.fetch(index)
453
+ end
454
+ end
455
+
456
+ # @rbs function: Function
457
+ # @rbs slot: Integer
458
+ # @rbs types: Array[Symbol]
459
+ # @rbs return: void
460
+ def check_result(function, slot, types)
461
+ raise Invalid unless types.empty? ? slot == -1 : at(function.register_types, slot) == types.fetch(0)
462
+ end
463
+
464
+ # @rbs target: Integer
465
+ # @rbs limit: Integer
466
+ # @rbs return: void
467
+ def check_target(target, limit)
468
+ raise Invalid unless target.between?(0, limit - 1) && target % Lowerer::WIDTH == 0
469
+ end
470
+
471
+ # @rbs [T] (Array[T] values, Integer index) -> T
472
+ def at(values, index)
473
+ raise Invalid unless index.between?(0, values.size - 1)
474
+ values.fetch(index)
475
+ end
476
+ end
477
+
478
+ # @rbs directory: String
479
+ # @rbs wasm: String
480
+ # @rbs configuration: Configuration
481
+ # @rbs verify: Symbol
482
+ def initialize(directory, wasm, configuration, verify: :checksum)
483
+ versions = [FORMAT_VERSION, CODE_VERSION].pack("L<2")
484
+ disabled = configuration.disabled.uniq.sort.join(",")
485
+ key_data = versions + Digest::SHA256.digest(wasm) + disabled
486
+ key_data = "spinel\0".b + key_data if RUBY_ENGINE == "spinel"
487
+ key = Digest::SHA256.digest(key_data)
488
+ @key = key
489
+ @header = MAGIC + versions + key
490
+ @directory = File.expand_path(directory)
491
+ @path = File.join(@directory, "#{key.unpack1("H*")}.mir2")
492
+ @verify = verify
493
+ end
494
+
495
+ # Restore against module declarations so a miss can decode and check the
496
+ # Wasm bodies before Store initialization or any host lookup.
497
+ # @rbs instance: Wardite::Instance
498
+ # @rbs return: Array[Function]?
499
+ def read(instance)
500
+ reader = Reader.new(read_verified_payload)
501
+ 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
504
+ $stderr.puts "MIR2 cache hit: #{@path}" if ENV["WARDITE_TRACE"]
505
+ functions
506
+ rescue SystemCallError, IOError, Invalid
507
+ $stderr.puts "MIR2 cache miss: #{@path}" if ENV["WARDITE_TRACE"]
508
+ nil
509
+ end
510
+
511
+ # @rbs instance: Wardite::Instance
512
+ # @rbs ir: IR
513
+ # @rbs return: void
514
+ def write(instance, ir)
515
+ FileUtils.mkdir_p(@directory)
516
+ writer = Writer.new
517
+ layout = encode_layout(instance, ir.entries)
518
+ writer.integers(layout.bytesize)
519
+ writer.bytes << layout
520
+ writer.integers(ir.functions.size)
521
+ 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
526
+ length = [payload.bytesize].pack("Q<")
527
+ prefix = @header + length + MIRCache.sample_checksum(payload, length) + Digest::SHA256.digest(payload)
528
+ MIRCache.publish(@directory, @path, prefix, payload)
529
+ rescue SystemCallError, IOError
530
+ # Cache I/O is optional once the normal build has succeeded.
531
+ nil
532
+ end
533
+
534
+ private
535
+
536
+ # @rbs instance: Wardite::Instance
537
+ # @rbs return: Array[FunctionEntry]
538
+ def module_entries(instance)
539
+ imports = instance.import_section.imports
540
+ types = instance.type_section
541
+ entries = [] #: Array[FunctionEntry]
542
+ imports.each_with_index do |import, index|
543
+ params = types&.defined_types&.[](import.sig_index)
544
+ results = types&.defined_results&.[](import.sig_index)
545
+ raise Invalid unless params && results
546
+ entries << FunctionEntry.new(:host, params, results, -1, index)
547
+ end
548
+ instance.each_defined_function do |params, results, _body|
549
+ entries << FunctionEntry.new(:defined, params, results, entries.size - imports.size, -1)
550
+ end
551
+ entries
552
+ rescue Wardite::LoadError
553
+ # Keep the usual Wasm validation path and its errors on a miss.
554
+ raise Invalid
555
+ end
556
+
557
+ # @rbs return: String
558
+ def read_verified_payload
559
+ header_size = @header.bytesize
560
+ prefix_size = header_size + INTEGRITY_SIZE
561
+ contents = MIRCache.read_contents(@path, @header, prefix_size)
562
+ length = [contents.bytesize - prefix_size].pack("Q<")
563
+ raise Invalid unless contents.byteslice(header_size, LENGTH_SIZE) == length
564
+
565
+ payload = contents.byteslice(prefix_size..) || raise(Invalid)
566
+ digest_offset = header_size + LENGTH_SIZE
567
+ if @verify == :sha256
568
+ digest_offset += DIGEST_SIZE
569
+ digest = Digest::SHA256.digest(payload)
570
+ else
571
+ digest = MIRCache.sample_checksum(payload, length)
572
+ end
573
+ raise Invalid unless contents.byteslice(digest_offset, DIGEST_SIZE) == digest
574
+ payload
575
+ end
576
+
577
+ # @rbs payload: String
578
+ # @rbs length: String
579
+ # @rbs return: String
580
+ def self.sample_checksum(payload, length)
581
+ size = payload.bytesize
582
+ return Digest::SHA256.digest(length + payload) if size <= 2 * SAMPLE_EDGE
583
+
584
+ sample = length.dup
585
+ sample << (payload.byteslice(0, SAMPLE_EDGE) || raise(Invalid))
586
+ offset = SAMPLE_STEP
587
+ while offset < size
588
+ sample << (payload.byteslice(offset, SAMPLE_BLOCK) || raise(Invalid))
589
+ offset += SAMPLE_STEP
590
+ end
591
+ sample << (payload.byteslice(size - SAMPLE_EDGE, SAMPLE_EDGE) || raise(Invalid))
592
+ Digest::SHA256.digest(sample)
593
+ end
594
+
595
+ # Opening without blocking keeps a FIFO from stalling the start of a run.
596
+ # @rbs path: String
597
+ # @rbs header: String
598
+ # @rbs prefix_size: Integer
599
+ # @rbs return: String
600
+ def self.read_contents(path, header, prefix_size)
601
+ contents = File.open(path, File::RDONLY | File::NONBLOCK) do |file|
602
+ stat = file.stat
603
+ raise Invalid unless stat.file? && stat.size <= MAX_BYTES
604
+ file.binmode
605
+ contents = file.read(stat.size) || raise(Invalid)
606
+ raise Invalid unless file.eof?
607
+ contents
608
+ end
609
+ raise Invalid unless contents.bytesize.between?(prefix_size, MAX_BYTES) && contents.start_with?(header)
610
+ contents
611
+ end
612
+
613
+ # Exclusive creation protects a concurrent writer's temporary file.
614
+ # Close the file before publishing it under the cache key.
615
+ # @rbs directory: String
616
+ # @rbs destination: String
617
+ # @rbs prefix: String
618
+ # @rbs payload: String
619
+ # @rbs return: void
620
+ def self.publish(directory, destination, prefix, payload)
621
+ path = File.join(directory, ".wardite-#{SecureRandom.hex(16)}.tmp")
622
+ file = File.open(path, File::WRONLY | File::CREAT | File::EXCL, 0o600)
623
+ begin
624
+ file.binmode
625
+ file.write(prefix)
626
+ file.write(payload)
627
+ file.close
628
+ File.rename(path, destination)
629
+ ensure
630
+ file.close unless file.closed?
631
+ File.unlink(path) if File.exist?(path)
632
+ end
633
+ end
634
+
635
+ # Include the module's import identities, and every function's signature
636
+ # and index mapping. The live entries and hosts are always linked afresh.
637
+ # @rbs instance: Wardite::Instance
638
+ # @rbs entries: Array[FunctionEntry]
639
+ # @rbs return: String
640
+ def encode_layout(instance, entries)
641
+ writer = Writer.new
642
+ imports = instance.import_section.imports
643
+ writer.integers(imports.size, entries.size)
644
+ imports.each do |import|
645
+ writer.integers(import.module_name.bytesize, import.name.bytesize)
646
+ writer.bytes << import.module_name.b << import.name.b
647
+ end
648
+ entries.each do |entry|
649
+ writer.integers(entry.defined_index, entry.host_index)
650
+ writer.types(entry.parameter_types)
651
+ writer.types(entry.result_types)
652
+ end
653
+ writer.bytes
654
+ end
655
+ end
656
+ end
657
+ end