wardite 0.9.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 (184) hide show
  1. checksums.yaml +4 -4
  2. data/LICENSE +191 -0
  3. data/Makefile +14 -0
  4. data/README.md +107 -2
  5. data/Rakefile +5 -0
  6. data/Steepfile +1 -0
  7. data/assets/wardite.svg +12 -0
  8. data/benchmark/README.md +500 -0
  9. data/benchmark/build_call_profile.rb +42 -0
  10. data/benchmark/call_cost_worker.rb +27 -0
  11. data/benchmark/compare.rb +93 -0
  12. data/benchmark/compare_call_types.rb +212 -0
  13. data/benchmark/compare_dispatch.rb +123 -0
  14. data/benchmark/compare_engines.rb +119 -0
  15. data/benchmark/compare_optimizations.rb +139 -0
  16. data/benchmark/engine_phases.rb +30 -0
  17. data/benchmark/figures/README.md +35 -0
  18. data/benchmark/figures/plot_spinel_comparison.py +137 -0
  19. data/benchmark/figures/spinel_new_vm_candlestick.png +0 -0
  20. data/benchmark/figures/spinel_new_vm_candlestick.svg +7615 -0
  21. data/benchmark/figures/spinel_new_vm_summary.csv +9 -0
  22. data/benchmark/figures/spinel_new_vm_summary.json +82 -0
  23. data/benchmark/float_m5.wat +42 -0
  24. data/benchmark/i32_call_arities.wat +89 -0
  25. data/benchmark/i32_calls.wat +174 -0
  26. data/benchmark/i32_memory.wat +58 -0
  27. data/benchmark/i32_mix.wat +80 -0
  28. data/benchmark/i64_m4.wat +55 -0
  29. data/benchmark/investigate_calls.rb +231 -0
  30. data/benchmark/investigate_generated_guards.rb +218 -0
  31. data/benchmark/m3_call_worker.rb +38 -0
  32. data/benchmark/measure_m1.rb +51 -0
  33. data/benchmark/measure_m2.rb +55 -0
  34. data/benchmark/measure_m3_calls.rb +89 -0
  35. data/benchmark/measure_m4.rb +134 -0
  36. data/benchmark/measure_m5_boundary.rb +41 -0
  37. data/benchmark/measure_mir_cache_verify.rb +58 -0
  38. data/benchmark/measure_ruby_wasm_cache_hit.rb +59 -0
  39. data/benchmark/measure_ruby_wasm_startup.rb +43 -0
  40. data/benchmark/measure_wasi_write.rb +75 -0
  41. data/benchmark/optimization_worker.rb +23 -0
  42. data/benchmark/results/call_arities_exploratory_2026-11-04.json +4320 -0
  43. data/benchmark/results/call_arities_spinel_2026-11-04.json +1200 -0
  44. data/benchmark/results/call_cost_spinel_2026-11-04.json +2392 -0
  45. data/benchmark/results/call_protocol_exploratory_2026-11-04.json +3947 -0
  46. data/benchmark/results/call_protocol_profile_2026-11-04.json +383 -0
  47. data/benchmark/results/call_protocol_ruby_2026-11-04.json +1213 -0
  48. data/benchmark/results/call_protocol_spinel_2026-11-04.json +913 -0
  49. data/benchmark/results/call_types_ruby_2026-11-04.json +1212 -0
  50. data/benchmark/results/call_types_spinel_2026-11-04.json +923 -0
  51. data/benchmark/results/efflorescence-m1-cruby.json +799 -0
  52. data/benchmark/results/efflorescence-m1-spinel.json +799 -0
  53. data/benchmark/results/efflorescence-m2-bulk-loop.json +820 -0
  54. data/benchmark/results/efflorescence-m2-i32-cruby.json +799 -0
  55. data/benchmark/results/efflorescence-m2-i32-spinel.json +799 -0
  56. data/benchmark/results/efflorescence-m2-memory.json +408 -0
  57. data/benchmark/results/efflorescence-mir2-cache-integrity.json +390 -0
  58. data/benchmark/results/efflorescence-unboxed-globals.json +3451 -0
  59. data/benchmark/results/generated_guards_exploratory_2026-11-04.json +1225 -0
  60. data/benchmark/results/generated_guards_profile_2026-11-04.json +592 -0
  61. data/benchmark/results/generated_guards_spinel_2026-11-04.json +1650 -0
  62. data/benchmark/results/generated_guards_validation_2026-11-04.json +256 -0
  63. data/benchmark/results/inlining_engines_2026-11-04.json +241 -0
  64. data/benchmark/results/inlining_ruby_2026-11-04.json +1213 -0
  65. data/benchmark/results/inlining_spinel_2026-11-04.json +893 -0
  66. data/benchmark/results/operand_decode_exploratory_2026-11-04.json +1319 -0
  67. data/benchmark/results/operand_decode_ruby_2026-11-04.json +1213 -0
  68. data/benchmark/results/operand_decode_spinel_2026-11-04.json +924 -0
  69. data/benchmark/results/selective_reset_spinel_2026-11-04.json +454 -0
  70. data/benchmark/results/selective_reset_spinel_2026-11-04_exploratory.json +2679 -0
  71. data/benchmark/results/spinel_fetch_root_patch_2026-11-04.json +4523 -0
  72. data/benchmark/results/while_final_compiler_comparison_2026-11-04.json +324 -0
  73. data/benchmark/results/while_patched_external_2026-11-04.json +220 -0
  74. data/benchmark/results/while_user_unpatched_2026-11-04.json +230 -0
  75. data/benchmark/summarize_call_profile.py +54 -0
  76. data/benchmark/validate_m1_eh.rb +34 -0
  77. data/benchmark/validate_m2.rb +119 -0
  78. data/benchmark/validate_m3.rb +44 -0
  79. data/benchmark/validate_m4.rb +95 -0
  80. data/benchmark/validate_m5.rb +108 -0
  81. data/docs/adr/0001-efflorescence-m1-control-and-eh.md +319 -0
  82. data/docs/adr/0002-efflorescence-m2-memory-and-globals.md +185 -0
  83. data/docs/adr/0003-efflorescence-m3-host-and-indirect-calls.md +228 -0
  84. data/docs/adr/0004-efflorescence-m4-i64.md +202 -0
  85. data/docs/adr/0005-efflorescence-m5-floating-point.md +127 -0
  86. data/docs/adr/0006-efflorescence-m6-coverage-parity.md +101 -0
  87. data/docs/adr/0007-efflorescence-ruby-wasm-phase1.md +75 -0
  88. data/docs/adr/0008-efflorescence-ruby-wasm-phase2.md +75 -0
  89. data/docs/adr/0009-efflorescence-mir2-cache-integrity-modes.md +77 -0
  90. data/docs/adr/0010-efflorescence-mir2-cache-function-restore.md +80 -0
  91. data/docs/adr/0011-efflorescence-unboxed-globals.md +89 -0
  92. data/docs/adr/0012-efflorescence-startup-snapshot.md +173 -0
  93. data/docs/adr/0013-efflorescence-frame-acquisition.md +114 -0
  94. data/docs/efflorescence-call-arities.md +115 -0
  95. data/docs/efflorescence-call-investigation.md +155 -0
  96. data/docs/efflorescence-call-transfer.md +128 -0
  97. data/docs/efflorescence-call-types.md +102 -0
  98. data/docs/efflorescence-coverage-ja.md +351 -0
  99. data/docs/efflorescence-generated-c-guards.md +410 -0
  100. data/docs/efflorescence-inlining.md +165 -0
  101. data/docs/efflorescence-ja.md +155 -0
  102. data/docs/efflorescence-m1.md +160 -0
  103. data/docs/efflorescence-m2.md +233 -0
  104. data/docs/efflorescence-m3.md +131 -0
  105. data/docs/efflorescence-m4.md +88 -0
  106. data/docs/efflorescence-m5.md +82 -0
  107. data/docs/efflorescence-m6.md +95 -0
  108. data/docs/efflorescence-mir2-cache.md +123 -0
  109. data/docs/efflorescence-operand-decoding.md +105 -0
  110. data/docs/efflorescence-phase2-ja.md +225 -0
  111. data/docs/efflorescence-phase2.md +240 -0
  112. data/docs/efflorescence-register-initialization.md +75 -0
  113. data/docs/efflorescence-ruby-wasm-phase1.md +90 -0
  114. data/docs/efflorescence-spinel-linear-memory.md +72 -0
  115. data/docs/efflorescence-startup-snapshot.md +60 -0
  116. data/docs/efflorescence-unboxed-globals.md +61 -0
  117. data/docs/efflorescence.md +144 -0
  118. data/docs/spinel-string-aset-inplace-proposal.md +200 -0
  119. data/lib/wardite/alu_f32.generated.rb +11 -2
  120. data/lib/wardite/alu_f64.generated.rb +11 -2
  121. data/lib/wardite/alu_i32.generated.rb +54 -17
  122. data/lib/wardite/alu_i64.generated.rb +73 -31
  123. data/lib/wardite/cli/cli.rb +112 -29
  124. data/lib/wardite/const.rb +1 -0
  125. data/lib/wardite/efflorescence/float_arithmetic.rb +216 -0
  126. data/lib/wardite/efflorescence/i64_arithmetic.rb +257 -0
  127. data/lib/wardite/efflorescence/inspection.rb +165 -0
  128. data/lib/wardite/efflorescence/ir.rb +1164 -0
  129. data/lib/wardite/efflorescence/mir_cache.rb +657 -0
  130. data/lib/wardite/efflorescence/optimizer.rb +580 -0
  131. data/lib/wardite/efflorescence/register_validation.rb +362 -0
  132. data/lib/wardite/efflorescence/snapshot.rb +229 -0
  133. data/lib/wardite/efflorescence/store_access.rb +366 -0
  134. data/lib/wardite/efflorescence/translator.rb +866 -0
  135. data/lib/wardite/efflorescence/vm.rb +1170 -0
  136. data/lib/wardite/efflorescence/wasi.rb +52 -0
  137. data/lib/wardite/efflorescence.rb +17 -0
  138. data/lib/wardite/errors.rb +20 -0
  139. data/lib/wardite/float_bits.rb +46 -0
  140. data/lib/wardite/instruction.rb +35 -4
  141. data/lib/wardite/leb128.rb +33 -12
  142. data/lib/wardite/load.rb +292 -143
  143. data/lib/wardite/value.rb +169 -175
  144. data/lib/wardite/version.rb +1 -1
  145. data/lib/wardite/wasi/consts.rb +1 -0
  146. data/lib/wardite/wasi/spinel.rb +41 -0
  147. data/lib/wardite/wasi.rb +483 -268
  148. data/lib/wardite/wasm_module.rb +6 -3
  149. data/lib/wardite.rb +360 -98
  150. data/rbs_collection.lock.yaml +36 -96
  151. data/scripts/gen_alu.rb +121 -21
  152. data/scripts/verify_ruby_wasm.rb +70 -0
  153. data/sig/generated/wardite/cli/cli.rbs +23 -6
  154. data/sig/generated/wardite/const.rbs +2 -0
  155. data/sig/generated/wardite/efflorescence/float_arithmetic.rbs +65 -0
  156. data/sig/generated/wardite/efflorescence/i64_arithmetic.rbs +99 -0
  157. data/sig/generated/wardite/efflorescence/inspection.rbs +64 -0
  158. data/sig/generated/wardite/efflorescence/ir.rbs +888 -0
  159. data/sig/generated/wardite/efflorescence/mir_cache.rbs +236 -0
  160. data/sig/generated/wardite/efflorescence/optimizer.rbs +189 -0
  161. data/sig/generated/wardite/efflorescence/register_validation.rbs +104 -0
  162. data/sig/generated/wardite/efflorescence/snapshot.rbs +83 -0
  163. data/sig/generated/wardite/efflorescence/store_access.rbs +145 -0
  164. data/sig/generated/wardite/efflorescence/translator.rbs +218 -0
  165. data/sig/generated/wardite/efflorescence/vm.rbs +240 -0
  166. data/sig/generated/wardite/efflorescence/wasi.rbs +34 -0
  167. data/sig/generated/wardite/errors.rbs +12 -0
  168. data/sig/generated/wardite/float_bits.rbs +30 -0
  169. data/sig/generated/wardite/instruction.rbs +22 -1
  170. data/sig/generated/wardite/leb128.rbs +3 -1
  171. data/sig/generated/wardite/load.rbs +59 -7
  172. data/sig/generated/wardite/value.rbs +70 -11
  173. data/sig/generated/wardite/wasi/consts.rbs +2 -0
  174. data/sig/generated/wardite/wasi/spinel.rbs +15 -0
  175. data/sig/generated/wardite/wasi.rbs +111 -4
  176. data/sig/generated/wardite.rbs +114 -13
  177. data/sig/mir_cache_stdlib.rbs +5 -0
  178. data/sig/vernier.rbs +2 -2
  179. data/spinel/README.md +30 -0
  180. data/spinel/bin/wardite.rb +6 -0
  181. data/spinel/patches/0001-io-buffer-string-view.patch +699 -0
  182. data/spinel/patches/0002-io-buffer-allocation-error.patch +47 -0
  183. data/spinel/spin.toml +7 -0
  184. metadata +154 -3
@@ -0,0 +1,362 @@
1
+ # frozen_string_literal: true
2
+ # rbs_inline: enabled
3
+
4
+ module Wardite
5
+ module Efflorescence
6
+ # Verify definite assignment once, after optimization and before execution.
7
+ # This makes stale temporary slots harmless when a frame is reused. Keep
8
+ # states per basic block, rather than per instruction, to bound their size.
9
+ class RegisterValidation
10
+ # Keep each word within Spinel's fixed-width Integer.
11
+ WORD_SHIFT = 5
12
+ WORD_BITS = 1 << WORD_SHIFT
13
+ WORD_MASK = WORD_BITS - 1
14
+
15
+ class Block
16
+ attr_reader :first #: Integer
17
+ attr_reader :limit #: Integer
18
+ attr_reader :defined #: Array[Integer]
19
+ attr_reader :successors #: Array[Integer]
20
+ attr_accessor :pending #: bool
21
+
22
+ # @rbs first: Integer
23
+ # @rbs limit: Integer
24
+ def initialize(first, limit)
25
+ @first = first
26
+ @limit = limit
27
+ @defined = [] #: Array[Integer]
28
+ @successors = [] #: Array[Integer]
29
+ @reached = false
30
+ @pending = false
31
+ end
32
+
33
+ # Incoming facts only lose definitions after the first reachable edge.
34
+ # Return true when a changed block needs to enter the worklist.
35
+ # @rbs incoming: Array[Integer]
36
+ # @rbs return: bool
37
+ def merge(incoming)
38
+ changed = false
39
+ unless @reached
40
+ @defined = incoming.dup
41
+ @reached = true
42
+ changed = true
43
+ else
44
+ index = 0
45
+ while index < @defined.size
46
+ previous = @defined.fetch(index)
47
+ intersection = previous & incoming.fetch(index)
48
+ if intersection != previous
49
+ @defined[index] = intersection
50
+ changed = true
51
+ end
52
+ index += 1
53
+ end
54
+ end
55
+ return false unless changed && !@pending
56
+
57
+ @pending = true
58
+ true
59
+ end
60
+ end
61
+
62
+ # @rbs function: Wardite::Efflorescence::Function
63
+ # @rbs return: void
64
+ # @rbs ir: Wardite::Efflorescence::IR?
65
+ # @rbs tags: Array[Wardite::Efflorescence::Tag]?
66
+ def validate(function, ir = nil, tags: nil)
67
+ instructions = function.instructions
68
+ raise TranslationError, "Efflorescence: empty MIR function" if instructions.empty?
69
+ validate_types(function, ir, tags)
70
+ analysis = Analysis.new(function)
71
+ flow = analysis.flow
72
+ register_count = function.register_count
73
+ blocks = [] #: Array[Wardite::Efflorescence::RegisterValidation::Block]
74
+ block_for_pc = [] #: Array[Integer]
75
+ first = 0
76
+ instructions.size.times do |pc|
77
+ if pc > 0 && analysis.leaders[pc] == 1
78
+ blocks << Block.new(first, pc)
79
+ first = pc
80
+ end
81
+ block_for_pc << blocks.size
82
+ end
83
+ blocks << Block.new(first, instructions.size)
84
+ order = reverse_postorder(blocks, block_for_pc, flow)
85
+
86
+ word_count = (register_count + WORD_MASK) >> WORD_SHIFT
87
+ constants = Array.new(word_count, 0)
88
+ defined = Array.new(word_count, 0)
89
+ (function.parameter_count + function.local_count).times { |register| mark(defined, register) }
90
+ function.constant_registers.each do |register|
91
+ mark(constants, register)
92
+ mark(defined, register)
93
+ end
94
+ blocks.fetch(0).merge(defined)
95
+ pending = 1
96
+ while pending > 0
97
+ order.each do |block_index|
98
+ break if pending == 0
99
+ block = blocks.fetch(block_index)
100
+ next unless block.pending
101
+
102
+ block.pending = false
103
+ pending -= 1
104
+ defined = block.defined.dup
105
+ pc = block.first
106
+ while pc < block.limit
107
+ instruction = instructions.fetch(pc)
108
+ function.reads(instruction).each do |register|
109
+ unless register >= 0 && register < register_count && marked?(defined, register)
110
+ raise TranslationError, "Efflorescence: function #{function.index}, MIR PC #{pc}: r#{register} read before definition"
111
+ end
112
+ end
113
+ # A CALL result exists only on its normal successor.
114
+ flow.exceptional.fetch(pc).each do |clause|
115
+ edge_defined = defined.dup
116
+ clause.destinations.each { |register| mark(edge_defined, register) }
117
+ target = block_for_pc.fetch(clause.target_pc)
118
+ pending += 1 if blocks.fetch(target).merge(edge_defined)
119
+ end
120
+ destination = Opcode.destination(instruction)
121
+ if destination >= 0
122
+ if destination >= register_count || marked?(constants, destination)
123
+ raise TranslationError, "Efflorescence: function #{function.index}, MIR PC #{pc}: invalid register destination r#{destination}"
124
+ end
125
+ mark(defined, destination)
126
+ end
127
+ pc += 1
128
+ end
129
+ flow.normal.fetch(block.limit - 1).each do |target_pc|
130
+ target = block_for_pc.fetch(target_pc)
131
+ pending += 1 if blocks.fetch(target).merge(defined)
132
+ end
133
+ end
134
+ end
135
+ end
136
+ private
137
+
138
+ # Visit predecessors before joins where possible, then revisit changed
139
+ # states across backedges until the worklist is empty.
140
+ # @rbs blocks: Array[Wardite::Efflorescence::RegisterValidation::Block]
141
+ # @rbs block_for_pc: Array[Integer]
142
+ # @rbs flow: Wardite::Efflorescence::FlowGraph
143
+ # @rbs return: Array[Integer]
144
+ def reverse_postorder(blocks, block_for_pc, flow)
145
+ blocks.each do |block|
146
+ flow.normal.fetch(block.limit - 1).each { |pc| block.successors << block_for_pc.fetch(pc) }
147
+ (block.first...block.limit).each do |pc|
148
+ flow.exceptional.fetch(pc).each { |clause| block.successors << block_for_pc.fetch(clause.target_pc) }
149
+ end
150
+ end
151
+
152
+ seen = Array.new(blocks.size, false)
153
+ next_edge = Array.new(blocks.size, 0)
154
+ seen[0] = true
155
+ stack = [0]
156
+ postorder = [] #: Array[Integer]
157
+ until stack.empty?
158
+ index = stack.fetch(stack.size - 1)
159
+ successors = blocks.fetch(index).successors
160
+ edge = next_edge.fetch(index)
161
+ if edge == successors.size
162
+ postorder << index
163
+ stack.pop
164
+ else
165
+ target = successors.fetch(edge)
166
+ next_edge[index] = edge + 1
167
+ unless seen.fetch(target)
168
+ seen[target] = true
169
+ stack << target
170
+ end
171
+ end
172
+ end
173
+ postorder.reverse
174
+ end
175
+
176
+ # @rbs words: Array[Integer]
177
+ # @rbs register: Integer
178
+ # @rbs return: void
179
+ def mark(words, register)
180
+ index = register >> WORD_SHIFT
181
+ words[index] = words.fetch(index) | (1 << (register & WORD_MASK))
182
+ end
183
+
184
+ # @rbs words: Array[Integer]
185
+ # @rbs register: Integer
186
+ # @rbs return: bool
187
+ def marked?(words, register)
188
+ word = words.fetch(register >> WORD_SHIFT)
189
+ (word & (1 << (register & WORD_MASK))) != 0
190
+ end
191
+
192
+ # Validate all registers, including unreachable instructions and table-only
193
+ # operands. Numeric registers are checked before flat execution.
194
+ # @rbs function: Wardite::Efflorescence::Function
195
+ # @rbs return: void
196
+ # @rbs ir: Wardite::Efflorescence::IR?
197
+ # @rbs tags: Array[Wardite::Efflorescence::Tag]?
198
+ def validate_types(function, ir, tags)
199
+ function.instructions.each do |instruction|
200
+ opcode = instruction[0]
201
+ if Opcode.memory_site?(opcode)
202
+ index = instruction[1]
203
+ unless index >= 0 && index < function.memory_sites.size
204
+ raise TranslationError, "invalid MIR memory site index"
205
+ end
206
+ site = function.memory_site(index)
207
+ unless site.sources.size == 3 && site.memory_index == 0 && site.source_memory_index == 0 &&
208
+ (opcode != Opcode::MEMORY_INIT || site.data_index >= 0)
209
+ raise TranslationError, "invalid MIR memory site operands"
210
+ end
211
+ end
212
+ if Opcode.dynamic_call?(opcode)
213
+ site = function.dynamic_site(instruction[2])
214
+ destination = instruction[1]
215
+ if opcode == Opcode::CALL_HOST
216
+ unless site.host_index >= 0 && site.table_index == -1 && instruction[3] == 0
217
+ raise TranslationError, "invalid MIR host call operands"
218
+ end
219
+ elsif site.host_index != -1 || site.table_index != 0
220
+ raise TranslationError, "invalid MIR indirect call operands"
221
+ end
222
+ unless site.arguments.size == site.parameter_types.size &&
223
+ site.parameter_types.all? { |type| FunctionEntry.numeric_type?(type) } &&
224
+ (site.result_types.empty? ? destination == -1 : site.result_types.size == 1 &&
225
+ FunctionEntry.numeric_type?(site.result_types.fetch(0)) && destination >= 0)
226
+ raise TranslationError, "invalid MIR dynamic call signature"
227
+ end
228
+ if ir && opcode == Opcode::CALL_HOST
229
+ host = ir.hosts[site.host_index]
230
+ unless host && host.entry.parameter_types == site.parameter_types && host.entry.result_types == site.result_types
231
+ raise TranslationError, "MIR host call signature mismatch"
232
+ end
233
+ end
234
+ check_register(function, instruction[3], :i32) if opcode == Opcode::CALL_INDIRECT
235
+ site.arguments.each_with_index { |register, i| check_register(function, register, site.parameter_types.fetch(i)) }
236
+ check_result(function, destination, site.result_types)
237
+ next
238
+ end
239
+ reads = function.reads(instruction)
240
+ destination = Opcode.destination(instruction)
241
+ if opcode > Opcode::CALL_INDIRECT
242
+ validate_extended_instruction(function, instruction, reads, destination)
243
+ next
244
+ end
245
+ case opcode
246
+ when Opcode::THROW
247
+ site = function.throw_sites.fetch(instruction[1])
248
+ types = payload_types(tags, site.tag_index, reads.size)
249
+ reads.each_with_index { |register, i| check_register(function, register, types.fetch(i)) }
250
+ when Opcode::COPY
251
+ type = function.register_types[destination] if destination >= 0
252
+ unless type && FunctionEntry.numeric_type?(type)
253
+ raise TranslationError, "invalid MIR numeric copy destination r#{destination}"
254
+ end
255
+ check_register(function, instruction[2], type)
256
+ when Opcode::RETURN
257
+ check_result(function, instruction[1], function.result_types)
258
+ when Opcode::CALL
259
+ if ir
260
+ entry = ir.entry_at(instruction[2])
261
+ unless entry.kind == :defined && reads.size == entry.parameter_types.size
262
+ raise TranslationError, "invalid MIR direct call signature"
263
+ end
264
+ reads.each_with_index { |register, i| check_register(function, register, entry.parameter_types.fetch(i)) }
265
+ check_result(function, destination, entry.result_types)
266
+ else
267
+ reads.each { |register| check_register(function, register, :i32) }
268
+ check_register(function, destination, :i32) if destination >= 0
269
+ end
270
+ else
271
+ expected = opcode == Opcode::COPY_REF || opcode == Opcode::THROW_REF ? :exnref : :i32
272
+ reads.each { |register| check_register(function, register, expected) }
273
+ check_register(function, destination, expected) if destination >= 0
274
+ end
275
+ end
276
+ function.handlers.each do |handler|
277
+ handler.clauses.each do |clause|
278
+ types = payload_types(tags, clause.tag_index, clause.payload_registers.size)
279
+ clause.payload_registers.each_with_index do |register, i|
280
+ check_destination(function, register, types.fetch(i))
281
+ end
282
+ check_destination(function, clause.reference_register, :exnref) if clause.reference_register >= 0
283
+ end
284
+ end
285
+ end
286
+
287
+ # @rbs function: Wardite::Efflorescence::Function
288
+ # @rbs instruction: Wardite::Efflorescence::Instruction
289
+ # @rbs reads: Array[Integer]
290
+ # @rbs destination: Integer
291
+ # @rbs return: void
292
+ def validate_extended_instruction(function, instruction, reads, destination)
293
+ opcode = instruction[0]
294
+ types = Opcode.extended_alu_types(opcode)
295
+ if types
296
+ check_register(function, destination, types.fetch(0))
297
+ reads.each_with_index { |register, i| check_register(function, register, types.fetch(i + 1)) }
298
+ elsif (type = Opcode::EXTENDED_LOAD_TYPES[opcode])
299
+ check_register(function, destination, type)
300
+ check_register(function, instruction[2], :i32)
301
+ elsif (type = Opcode::EXTENDED_STORE_TYPES[opcode])
302
+ check_register(function, instruction[1], type)
303
+ check_register(function, instruction[2], :i32)
304
+ elsif (type = Opcode::EXTENDED_GLOBAL_GET_TYPES[opcode])
305
+ check_register(function, destination, type)
306
+ elsif (type = Opcode::EXTENDED_GLOBAL_SET_TYPES[opcode])
307
+ check_register(function, instruction[2], type)
308
+ else
309
+ raise TranslationError, "unknown extended MIR opcode #{opcode}"
310
+ end
311
+ end
312
+
313
+ # @rbs tags: Array[Wardite::Efflorescence::Tag]?
314
+ # @rbs index: Integer
315
+ # @rbs size: Integer
316
+ # @rbs return: Array[Symbol]
317
+ def payload_types(tags, index, size)
318
+ return Array.new(size, :i32) unless tags
319
+
320
+ tag = tags[index] if index >= 0
321
+ types = tag ? tag.parameter_types : [] #: Array[Symbol]
322
+ if (index >= 0 && !tag) || size != types.size
323
+ raise TranslationError, "invalid MIR exception payload"
324
+ end
325
+ types
326
+ end
327
+
328
+ # @rbs function: Wardite::Efflorescence::Function
329
+ # @rbs register: Integer
330
+ # @rbs types: Array[Symbol]
331
+ # @rbs return: void
332
+ def check_result(function, register, types)
333
+ if types.empty?
334
+ raise TranslationError, "invalid MIR void result" unless register == -1
335
+ else
336
+ check_register(function, register, types.fetch(0))
337
+ end
338
+ end
339
+
340
+ # @rbs function: Wardite::Efflorescence::Function
341
+ # @rbs register: Integer
342
+ # @rbs type: Symbol
343
+ # @rbs return: void
344
+ def check_register(function, register, type)
345
+ unless register >= 0 && function.register_types[register] == type
346
+ raise TranslationError, "invalid MIR register type/index r#{register}"
347
+ end
348
+ end
349
+
350
+ # @rbs function: Wardite::Efflorescence::Function
351
+ # @rbs register: Integer
352
+ # @rbs type: Symbol
353
+ # @rbs return: void
354
+ def check_destination(function, register, type)
355
+ unless register >= 0 && function.register_types[register] == type && !function.constant_registers.include?(register)
356
+ raise TranslationError, "invalid catch destination r#{register}"
357
+ end
358
+ end
359
+
360
+ end
361
+ end
362
+ end
@@ -0,0 +1,229 @@
1
+ # frozen_string_literal: true
2
+ # rbs_inline: enabled
3
+
4
+ require "digest"
5
+ require "fileutils"
6
+ require "wardite/efflorescence/mir_cache" unless RUBY_ENGINE == "spinel"
7
+
8
+ module Wardite
9
+ module Efflorescence
10
+ class SavedFrame
11
+ attr_reader :pool_index #: Integer
12
+ attr_reader :pc #: Integer
13
+ attr_reader :return_register #: Integer
14
+ attr_reader :registers #: Array[Integer]
15
+ attr_reader :handlers #: Array[Integer]
16
+
17
+ # @rbs pool_index: Integer
18
+ # @rbs pc: Integer
19
+ # @rbs return_register: Integer
20
+ # @rbs registers: Array[Integer]
21
+ # @rbs handlers: Array[Integer]
22
+ def initialize(pool_index, pc, return_register, registers, handlers)
23
+ @pool_index = pool_index
24
+ @pc = pc
25
+ @return_register = return_register
26
+ @registers = registers
27
+ @handlers = handlers
28
+ end
29
+ end
30
+
31
+ # Startup snapshot of a WASI command (ADR 0012). The state is saved just
32
+ # before the first WASI call whose result is not fixed by the key, and a
33
+ # later run with the same key resumes from there.
34
+ class Snapshot
35
+ MAGIC = "WARDSNP\0".b
36
+ FORMAT_VERSION = 1
37
+ PAGE_SIZE = 65536
38
+ ZERO_PAGE = ("\0" * PAGE_SIZE).b
39
+ # Their results depend only on values in the key, or are frozen into the
40
+ # snapshot (clocks and random bytes). fd_filestat_get is allowed for
41
+ # stdio only: CRuby probes fds 0-2 before anything else.
42
+ ALLOWED = %i[args_sizes_get args_get environ_sizes_get environ_get fd_prestat_get
43
+ fd_prestat_dir_name fd_fdstat_get clock_res_get clock_time_get random_get].freeze
44
+
45
+ attr_reader :path #: String
46
+
47
+ # @rbs directory: String
48
+ # @rbs instance: Wardite::Instance
49
+ # @rbs mir_cache: Wardite::Efflorescence::MIRCache
50
+ def initialize(directory, instance, mir_cache)
51
+ wasi = instance.wasi || raise(Wardite::ArgumentError, "snapshot requires WASI")
52
+ @wasi = wasi
53
+ @fds = wasi.fd_table.keys.sort
54
+ @fd_count = wasi.fd_count
55
+ pages = instance.store.memories.map { |memory| memory.current }
56
+ key_data = [FORMAT_VERSION, pages.size, *pages].pack("L<*") + mir_cache.key + wasi.snapshot_identity
57
+ key = Digest::SHA256.digest(key_data)
58
+ @header = MAGIC + [FORMAT_VERSION].pack("L<") + key
59
+ @directory = File.expand_path(directory)
60
+ @path = File.join(@directory, "#{key.unpack1("H*")}.snap")
61
+ end
62
+
63
+ # Does this host call end the deterministic prefix of the run?
64
+ # @rbs host: Wardite::Efflorescence::HostFunction
65
+ # @rbs registers: Array[Integer]
66
+ # @rbs sources: Array[Integer]
67
+ # @rbs return: bool
68
+ def checkpoint?(host, registers, sources)
69
+ external = host.external
70
+ return true unless @wasi.equal?(external.target_module)
71
+ name = external.name
72
+ return registers[sources.fetch(0)] > 2 if name == :fd_filestat_get
73
+ !ALLOWED.include?(name)
74
+ end
75
+
76
+ # Saving is best effort: any refusal or I/O error leaves the run as is.
77
+ # @rbs instance: Wardite::Instance
78
+ # @rbs frames: Array[Wardite::Efflorescence::Frame]
79
+ # @rbs return: void
80
+ def save(instance, frames)
81
+ started = Time.now.to_f
82
+ return trace("skipped (open descriptors changed)") unless @wasi.fd_table.keys.sort == @fds && @wasi.fd_count == @fd_count
83
+ store = instance.store
84
+ return trace("skipped (multiple memories)") if store.memories.size > 1
85
+ writer = MIRCache::Writer.new
86
+ writer.integers(@fd_count)
87
+ access = StoreAccess.new(store)
88
+ globals = [] #: Array[Integer]
89
+ store.globals.each_with_index do |global, index|
90
+ globals << case global.type
91
+ when :i64 then access.global_get_i64(index)
92
+ when :f32, :f64 then access.global_get_float(index, global.type)
93
+ else access.global_get(index)
94
+ end
95
+ end
96
+ writer.vector(globals, "q<")
97
+ writer.integers(frames.size)
98
+ frames.each do |frame|
99
+ return trace("skipped (pending exception reference)") unless frame.exception_registers.compact.empty?
100
+ writer.integers(frame.pool_index, frame.pc, frame.return_register)
101
+ writer.vector(frame.registers, "q<")
102
+ writer.vector(frame.handlers)
103
+ end
104
+ memory = store.memories[0]
105
+ pages = memory ? memory.current : 0
106
+ used = [] #: Array[Integer]
107
+ if memory
108
+ pages.times { |page| used << page unless memory.read_bytes(page * PAGE_SIZE, PAGE_SIZE) == ZERO_PAGE }
109
+ end
110
+ writer.integers(pages)
111
+ writer.vector(used)
112
+ payload = writer.bytes
113
+ if memory
114
+ return trace("skipped (too large)") if payload.bytesize + used.size * PAGE_SIZE > MIRCache::MAX_BYTES
115
+ used.each { |page| payload << memory.read_bytes(page * PAGE_SIZE, PAGE_SIZE) }
116
+ end
117
+ FileUtils.mkdir_p(@directory)
118
+ MIRCache.publish(@directory, @path, @header + Digest::SHA256.digest(payload), payload)
119
+ trace("saved", started)
120
+ rescue SystemCallError, IOError
121
+ trace("skipped (write failed)")
122
+ end
123
+
124
+ # Validate everything before touching the Store, so a rejected file
125
+ # leaves a fresh instance for the normal start.
126
+ # @rbs vm: Wardite::Efflorescence::VM
127
+ # @rbs return: Array[Wardite::Efflorescence::SavedFrame]?
128
+ def restore(vm)
129
+ started = Time.now.to_f
130
+ instance = vm.instance
131
+ store = instance.store
132
+ header_size = @header.bytesize
133
+ prefix_size = header_size + MIRCache::DIGEST_SIZE
134
+ contents = MIRCache.read_contents(@path, @header, prefix_size)
135
+ payload = contents.byteslice(prefix_size..) || raise(MIRCache::Invalid)
136
+ raise MIRCache::Invalid unless contents.byteslice(header_size, MIRCache::DIGEST_SIZE) == Digest::SHA256.digest(payload)
137
+ reader = MIRCache::Reader.new(payload)
138
+ raise MIRCache::Invalid unless reader.integer == @wasi.fd_count && store.memories.size <= 1
139
+ globals = reader.vector("q<", 8)
140
+ raise MIRCache::Invalid unless globals.size == store.globals.size
141
+ functions = vm.ir.functions
142
+ frames = [] #: Array[SavedFrame]
143
+ reader.count(12).times do
144
+ pool_index = reader.integer
145
+ pc = reader.integer
146
+ return_register = reader.integer
147
+ registers = reader.vector("q<", 8)
148
+ handlers = reader.vector("l<", 4)
149
+ frames << SavedFrame.new(pool_index, pc, return_register, registers, handlers)
150
+ end
151
+ raise MIRCache::Invalid if frames.empty?
152
+ frames.each_with_index { |frame, index| check_frame(functions, frames, index) }
153
+ memory = store.memories[0]
154
+ pages = reader.integer
155
+ used = reader.vector("l<", 4)
156
+ current = memory ? memory.current : 0
157
+ raise MIRCache::Invalid unless (memory || pages == 0) && pages >= current
158
+ raise MIRCache::Invalid unless used.all? { |page| page >= 0 && page < pages }
159
+ contents = reader.bytes(used.size * PAGE_SIZE)
160
+ reader.finish
161
+
162
+ if memory
163
+ raise MIRCache::Invalid if pages > current && memory.grow(pages - current) < 0
164
+ used_pages = Array.new(pages, false)
165
+ used.each_with_index do |page, i|
166
+ used_pages[page] = true
167
+ memory.write_bytes(page * PAGE_SIZE, contents.byteslice(i * PAGE_SIZE, PAGE_SIZE) || raise(MIRCache::Invalid))
168
+ end
169
+ used_pages.each_with_index { |nonzero, page| memory.write_bytes(page * PAGE_SIZE, ZERO_PAGE) unless nonzero }
170
+ end
171
+ access = StoreAccess.new(store)
172
+ store.globals.each_with_index do |global, index|
173
+ value = globals.fetch(index)
174
+ case global.type
175
+ when :i64 then access.global_set_i64(index, value)
176
+ when :f32, :f64 then access.global_set_float(index, global.type, value)
177
+ else access.global_set(index, value)
178
+ end
179
+ end
180
+ trace("restored", started)
181
+ frames
182
+ rescue SystemCallError, IOError, MIRCache::Invalid
183
+ trace("miss")
184
+ nil
185
+ end
186
+
187
+ private
188
+
189
+ # The top frame resumes at its host call. Callers resume after the call
190
+ # that created the frame above them, which writes its return register.
191
+ # @rbs functions: Array[Wardite::Efflorescence::Function]
192
+ # @rbs frames: Array[Wardite::Efflorescence::SavedFrame]
193
+ # @rbs index: Integer
194
+ # @rbs return: void
195
+ def check_frame(functions, frames, index)
196
+ frame = frames.fetch(index)
197
+ function = functions[frame.pool_index] || raise(MIRCache::Invalid)
198
+ code = function.bytecode
199
+ pc = frame.pc
200
+ raise MIRCache::Invalid unless pc >= 0 && pc < code.size && pc % Lowerer::WIDTH == 0
201
+ raise MIRCache::Invalid unless frame.registers.size == function.initial_registers.size
202
+ raise MIRCache::Invalid unless frame.handlers.all? { |id| id >= 0 && id < function.flat_handlers.size }
203
+ if index == frames.size - 1
204
+ opcode = code.fetch(pc)
205
+ raise MIRCache::Invalid unless opcode == Opcode::CALL_HOST || opcode == Opcode::CALL_INDIRECT
206
+ else
207
+ raise MIRCache::Invalid unless pc >= Lowerer::WIDTH
208
+ opcode = code.fetch(pc - Lowerer::WIDTH)
209
+ raise MIRCache::Invalid unless opcode == Opcode::CALL || opcode == Opcode::CALL_INDIRECT
210
+ end
211
+ destination = frame.return_register
212
+ if index == 0
213
+ raise MIRCache::Invalid unless destination == -1
214
+ else
215
+ raise MIRCache::Invalid unless destination >= -1 && destination < frames.fetch(index - 1).registers.size
216
+ end
217
+ end
218
+
219
+ # @rbs message: String
220
+ # @rbs started: Float
221
+ # @rbs return: void
222
+ def trace(message, started = 0.0)
223
+ return unless ENV["WARDITE_TRACE"]
224
+ elapsed = started > 0 ? " (#{(Time.now.to_f - started).round(3)}s)" : ""
225
+ $stderr.puts "snapshot #{message}: #{@path}#{elapsed}"
226
+ end
227
+ end
228
+ end
229
+ end