Class: Wardite::Runtime

Inherits:
Object
  • Object
show all
Includes:
ValueHelper
Defined in:
lib/wardite.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from ValueHelper

#F32, #F64, #I32, #I64

Constructor Details

#initialize(inst) ⇒ Runtime

Returns a new instance of Runtime.



252
253
254
255
256
257
258
# File 'lib/wardite.rb', line 252

def initialize(inst)
  @stack = []
  @call_stack = []
  @instance = inst

  invoke_start_section
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args) ⇒ Object



822
823
824
825
826
827
828
# File 'lib/wardite.rb', line 822

def method_missing(name, *args)
  if callable? name
    call(name, args)
  else
    super
  end
end

Instance Attribute Details

#call_stackObject

: Array



247
248
249
# File 'lib/wardite.rb', line 247

def call_stack
  @call_stack
end

#instanceObject (readonly)

: Instance



249
250
251
# File 'lib/wardite.rb', line 249

def instance
  @instance
end

#stackObject

TODO: add types of class that the stack accomodates



245
246
247
# File 'lib/wardite.rb', line 245

def stack
  @stack
end

Instance Method Details

#_start(*args) ⇒ Object



838
839
840
# File 'lib/wardite.rb', line 838

def _start(*args)
  call(:_start, args)
end

#call(name, args) ⇒ Object



277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
# File 'lib/wardite.rb', line 277

def call(name, args)
  if !callable?(name)
    raise ::NoMethodError, "function #{name} not found"
  end
  kind, fn = @instance.exports.mappings[name.to_s]
  if kind != 0
    raise ::NoMethodError, "#{name} is not a function"
  end
  if !fn.is_a?(WasmFunction) && !fn.is_a?(ExternalFunction)
    raise ::NoMethodError, "#{name} is not a function"
  end
  if fn.callsig.size != args.size
    raise ArgumentError, "unmatch arg size"
  end
  args.each_with_index do |arg, idx|
    case fn.callsig[idx]
    when :i32
      raise "type mismatch: i32(#{arg})" unless arg.is_a?(Integer)
      stack.push I32(arg)
    else
      raise "TODO: add me"
    end
  end

  case fn
  when WasmFunction
    r = invoke_internal(fn)
    r
  when ExternalFunction
    invoke_external(fn)
  else
    raise GenericError, "registered pointer is not to a function"
  end
end

#call_by_index(idx) ⇒ Object



314
315
316
317
318
319
320
321
322
323
324
325
# File 'lib/wardite.rb', line 314

def call_by_index(idx)
  fn = @instance.store.funcs[idx]

  case fn
  when WasmFunction
    invoke_internal(fn)
  when ExternalFunction
    invoke_external(fn)
  else
    raise GenericError, "registered pointer is not to a function"
  end
end

#callable?(name) ⇒ Boolean

Returns:

  • (Boolean)


270
271
272
# File 'lib/wardite.rb', line 270

def callable?(name)
  !! @instance.exports[name.to_s]
end

#do_branch(labels, stack, level) ⇒ Object



767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
# File 'lib/wardite.rb', line 767

def do_branch(labels, stack, level)
  idx = labels.size - 1 - level
  label = labels[idx]
  pc = if label.kind == :loop
    # keep the top of labels for loop again...
    while labels.size > idx + 1
      labels.pop
    end
    stack_unwind(label.sp, 0)
    label.start || raise(EvalError, "loop withour start")
  else
    while labels.size > idx
      labels.pop
    end
    stack_unwind(label.sp, label.arity)
    label.pc
  end

  pc
end

#drained_stack(finish) ⇒ Object



810
811
812
813
814
815
816
817
# File 'lib/wardite.rb', line 810

def drained_stack(finish)
  drained = stack[0...finish]
  if ! drained
    $stderr.puts "warning: state of stack: #{stack.inspect}"
    raise EvalError, "stack too short"
  end
  return drained
end

#eval_insn(frame, insn) ⇒ Object



439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
# File 'lib/wardite.rb', line 439

def eval_insn(frame, insn)
  namespace, code, operand, else_pos, end_pos = *insn
  case namespace
  when :convert
    return Evaluator.convert_eval_insn(self, frame, code, operand)
  when :i32
    return Evaluator.i32_eval_insn(self, frame, code, operand)
  when :i64
    return Evaluator.i64_eval_insn(self, frame, code, operand)
  when :f32
    return Evaluator.f32_eval_insn(self, frame, code, operand)
  when :f64
    return Evaluator.f64_eval_insn(self, frame, code, operand)
  end

  # unmached namespace...
  case code
  when :unreachable
    raise Unreachable, "unreachable op"
  when :nop
    return

  when :br
    level = operand[0]
    raise EvalError, "br op without level" if !level.is_a?(Integer)
    pc = do_branch(frame.labels, stack, level)
    frame.pc = pc

  when :br_if
    level = operand[0]
    raise EvalError, "br op without level" if !level.is_a?(Integer)
    cond = stack.pop 
    raise EvalError, "cond not found" if !cond.is_a?(I32)
    if cond.value.zero?
      return
    end
    pc = do_branch(frame.labels, stack, level)
    frame.pc = pc

  when :br_table
    level_vec = operand[0]
    raise EvalError, "no level vector" if !level_vec.is_a?(Array)
    default = operand[1]
    raise EvalError, "no default specified" if !default.is_a?(Integer)
    idx = stack.pop 
    raise EvalError, "idx not found" if !idx.is_a?(I32)
    level = if idx.value_s < 0 || idx.value_s >= level_vec.size
      default
    else
      level_vec[idx.value_s]
    end
    pc = do_branch(frame.labels, stack, level)
    frame.pc = pc

  when :block
    block = operand[0]
    raise EvalError, "block op without block" if !block.is_a?(Block)
    next_pc = end_pos || -1
    label = Label.new(:block, next_pc, stack.size, block.result_size)
    frame.labels.push(label)

  when :loop
    block = operand[0]
    raise EvalError, "loop op without block" if !block.is_a?(Block)
    start = frame.pc
    next_pc = end_pos || -1
    label = Label.new(:loop, next_pc, stack.size, block.result_size, start)
    frame.labels.push(label)

  when :if
    block = operand[0]
    raise EvalError, "if op without block" if !block.is_a?(Block)
    cond = stack.pop
    raise EvalError, "cond not found" if !cond.is_a?(I32)
    next_pc = end_pos || -1

    if cond.value.zero?
      frame.pc = else_pos || -1
    end

    if frame.pc == next_pc
      # This means if block has no else instr.
      return
    end

    label = Label.new(:if, next_pc, stack.size, block.result_size)
    frame.labels.push(label)

  when :else
    if old_label = frame.labels.pop
      frame.pc = old_label.pc
      stack_unwind(old_label.sp, old_label.arity)
    else
      raise EvalError, "else should be in if block"
    end

  when :call
    idx = operand[0]
    raise EvalError, "[BUG] local operand not found" if !idx.is_a?(Integer)
    fn = self.instance.store.funcs[idx]
    case fn
    when WasmFunction
      push_frame(fn)
    when ExternalFunction
      ret = invoke_external(fn)
      self.stack.push ret if ret
    else
      raise GenericError, "got a non-function pointer"
    end

  when :call_indirect
    table = self.instance.store.tables[0]
    raise EvalError, "table required but not found" if !table
    type_idx = operand[0]
    raise EvalError, "[BUG] index operand invalid" if !type_idx.is_a?(Integer)
    nullbyte = operand[1]
    raise EvalError, "[BUG] invalid bytearray of call_indirect" if nullbyte != 0x0
    table_idx = stack.pop
    raise EvalError, "[BUG] index stack invalid" if !table_idx.is_a?(I32)
    fntype = self.instance.types[type_idx]
    if !fntype
      raise EvalError, "undefined type index: idx=#{type_idx}"          
    end
    refs = self.instance.store.tables[0]&.refs
    if !refs
       raise EvalError, "uninitialized element idx:#{table_idx}"
    end

    fn = refs[table_idx.value]
    case fn
    when WasmFunction
      if table.type != :funcref
        raise EvalError, "invalid type of elem; expected: #{table.type}"
      end
      fn = fn.clone(override_type: fntype)
      push_frame(fn)
    when ExternalFunction
      if table.type != :externref
        raise EvalError, "invalid type of elem; expected: #{table.type}"
      end
      fn = fn.clone(override_type: fntype)
      ret = invoke_external(fn)
      self.stack.push ret if ret
    when nil
      raise EvalError, "uninitialized element idx:#{table_idx.value}"
    else
      raise EvalError, "[BUG] unknwon function type #{fn}"
    end

  when :return
    old_frame = call_stack.pop
    if !old_frame
      raise EvalError, "maybe empty call stack"
    end

    stack_unwind(old_frame.sp, old_frame.arity)

  when :end
    if old_label = frame.labels.pop
      frame.pc = old_label.pc
      stack_unwind(old_label.sp, old_label.arity)
    else
      old_frame = call_stack.pop
      if !old_frame
        raise EvalError, "maybe empty call stack"
      end
      stack_unwind(old_frame.sp, old_frame.arity)
    end

  when :drop
    stack.pop

  when :select
    cond, right, left = stack.pop, stack.pop, stack.pop
    if !cond.is_a?(I32)
      raise EvalError, "invalid stack for select"
    end
    if !right || !left
      raise EvalError, "stack too short"
    end
    stack.push(cond.value != 0 ? left : right)

  when :local_get
    idx = operand[0]
    if !idx.is_a?(Integer)
      raise EvalError, "[BUG] invalid type of operand"
    end
    local = frame.locals[idx]
    if !local
      # require "irb"; binding.irb
      raise EvalError, "local not found, idx = #{idx}"
    end
    stack.push(local)

  when :local_set
    idx = operand[0]
    if !idx.is_a?(Integer)
      raise EvalError, "[BUG] invalid type of operand"
    end
    value = stack.pop
    if !value
      raise EvalError, "value should be pushed"
    end
    frame.locals[idx] = value

  when :local_tee
    idx = operand[0]
    if !idx.is_a?(Integer)
      raise EvalError, "[BUG] invalid type of operand"
    end
    value = stack.pop
    if !value
      raise EvalError, "value should be pushed"
    end
    frame.locals[idx] = value
    stack.push value

  when :global_get
    idx = operand[0]
    if !idx.is_a?(Integer)
      raise EvalError, "[BUG] invalid type of operand"
    end
    global = instance.store.globals[idx]
    if !global
      raise EvalError, "global not found"
    end
    stack.push(global.value)

  when :global_set
    idx = operand[0]
    if !idx.is_a?(Integer)
      raise EvalError, "[BUG] invalid type of operand"
    end
    current_global = instance.store.globals[idx]
    if !current_global
      raise EvalError, "global index not valid"
    end
    if !current_global.mutable?
      raise EvalError, "global not mutable"
    end
    value = stack.pop
    if !value
      raise EvalError, "value should be pushed"
    end
    current_global.value = value
    instance.store.globals[idx] = current_global

  when :memory_size
    memory = instance.store.memories[0] || raise("[BUG] no memory")
    stack.push(I32(memory.current))

  when :memory_grow
    delta = stack.pop
    if !delta.is_a?(I32)
      raise EvalError, "maybe stack too short"
    end
    memory = instance.store.memories[0] || raise("[BUG] no memory")
    stack.push(I32(memory.grow(delta.value)))

  when :memory_init
    idx = operand[0]
    if !idx.is_a?(Integer)
      raise EvalError, "[BUG] invalid type of operand"
    end
    if operand[1] != 0x0
      $stderr.puts "warning: :memory_init is not ending with 0x00"
    end
    data_sec = instance.data_section
    if !data_sec
      raise EvalError, "data segment out of range"
    end
    data_seg = data_sec.segments[idx]
    if !data_seg
      raise EvalError, "data segment out of range"
    end

    memory = instance.store.memories[0] || raise("[BUG] no memory")
    length, src_offset, dest_offset = stack.pop, stack.pop, stack.pop
    if !length.is_a?(I32) || !src_offset.is_a?(I32) || !dest_offset.is_a?(I32)
      raise EvalError, "invalid stack values"
    end
    source = data_seg.data[src_offset.value...(src_offset.value+length.value)]
    raise EvalError, "invalid source range" if !source
    memory.data[dest_offset.value...(dest_offset.value+length.value)] = source

  when :memory_copy
    if operand[0] != 0x0 || operand[1] != 0x0
      $stderr.puts "warning: :memory_copy is not ending with 0x00"
    end
    length, src_offset, dest_offset = stack.pop, stack.pop, stack.pop
    if !length.is_a?(I32) || !src_offset.is_a?(I32) || !dest_offset.is_a?(I32)
      raise EvalError, "invalid stack values"
    end
    memory = instance.store.memories[0] || raise("[BUG] no memory")
    source = memory.data[src_offset.value...(src_offset.value+length.value)]
    raise EvalError, "invalid source range" if !source
    memory.data[dest_offset.value...(dest_offset.value+length.value)] = source

  when :memory_fill
    if operand[0] != 0x0
      $stderr.puts "warning: :memory_fill is not ending with 0x00"
    end
    length, byte, dest_offset = stack.pop, stack.pop, stack.pop
    if !length.is_a?(I32) || !byte.is_a?(I32) || !dest_offset.is_a?(I32)
      raise EvalError, "invalid stack values"
    end
    memory = instance.store.memories[0] || raise("[BUG] no memory")
    source = byte.value.chr * length.value
    memory.data[dest_offset.value...(dest_offset.value+length.value)] = source

  else
    raise "TODO! unsupported #{insn.inspect}"
  end

rescue => e
  if ENV["DEBUG"]
    require "pp"
    $stderr.puts "instance:::\n#{self.instance.pretty_inspect}"
    $stderr.puts "frame:::\n#{frame.pretty_inspect}"
    $stderr.puts "stack:::\n#{stack.pretty_inspect}"
  end
  raise e
end

#execute!Object



421
422
423
424
425
426
427
428
429
430
431
432
433
434
# File 'lib/wardite.rb', line 421

def execute!
  loop do
    cur_frame = self.call_stack.last #: Frame
    if !cur_frame
      break
    end
    cur_frame.pc += 1
    insn = cur_frame.body[cur_frame.pc]
    if !insn
      break
    end
    eval_insn(cur_frame, insn)
  end
end

#invoke_external(external_function) ⇒ Object



379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
# File 'lib/wardite.rb', line 379

def invoke_external(external_function)
  start = Time.now.to_f
  $stderr.puts "[trace] call external function: #{external_function.name}" if ENV["WARDITE_TRACE"]
  local_start = stack.size - external_function.callsig.size
  args = stack[local_start..]
  if !args
    raise LoadError, "stack too short"
  end
  self.stack = drained_stack(local_start)

  proc = external_function.callable
  val = proc[self.instance.store, args]
  if !val
    return
  end

  case val
  when I32, I64, F32, F64
    return val
  when Integer
    case external_function.retsig[0]
    when :i32
      return I32(val)
    when :i64
      return I64(val)
    end
  when Float
    case external_function.retsig[0]
    when :f32
      return F32(val)
    when :f64
      return F64(val)
    end
  end

  raise "invalid type of value returned in proc. val: #{val.inspect}"
ensure
  $GLOBAL_EXTERNAL_TIMES += 1
  $GLOBAL_EXTERNAL_ELAP += (Time.now.to_f - start)
end

#invoke_internal(wasm_function) ⇒ Object



346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
# File 'lib/wardite.rb', line 346

def invoke_internal(wasm_function)
  arity = wasm_function.retsig.size
  push_frame(wasm_function)
  execute!

  if arity > 0
    if arity > 1
      raise ::NotImplementedError, "return artiy >= 2 not yet supported ;;"
    end
    if self.stack.empty?
      raise "[BUG] stack empry"
    end
    v = self.stack.pop
    return v
  end

  return nil
end

#invoke_start_sectionObject



261
262
263
264
265
266
# File 'lib/wardite.rb', line 261

def invoke_start_section
  start_section = instance.start_section
  if start_section
    call_by_index(start_section.func_index)
  end
end

#push_frame(wasm_function) ⇒ Object



329
330
331
332
333
334
335
336
337
338
339
340
341
342
# File 'lib/wardite.rb', line 329

def push_frame(wasm_function)
  local_start = stack.size - wasm_function.callsig.size
  locals = stack[local_start..]
  if !locals
    raise LoadError, "stack too short"
  end
  self.stack = drained_stack(local_start)
  locals.concat(wasm_function.default_locals)

  arity = wasm_function.retsig.size
  frame = Frame.new(-1, stack.size, wasm_function.body, arity, locals)
  frame.findex = wasm_function.findex
  self.call_stack.push(frame)
end

#respond_to?(name) ⇒ Boolean

Returns:

  • (Boolean)


832
833
834
# File 'lib/wardite.rb', line 832

def respond_to? name
  callable?(name) || super
end

#stack_unwind(sp, arity) ⇒ Object

unwind the stack and put return value if exists



792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
# File 'lib/wardite.rb', line 792

def stack_unwind(sp, arity)
  if arity > 0
    if arity > 1
      raise ::NotImplementedError, "return artiy >= 2 not yet supported ;;"
    end
    value = stack.pop
    if !value
      raise EvalError, "cannot obtain return value"
    end
    self.stack = drained_stack(sp)
    stack.push value
  else
    self.stack = drained_stack(sp)
  end
end