Module: Wardite::BinaryLoader

Extended by:
Leb128Helper, ValueHelper
Defined in:
lib/wardite/load.rb

Class Method Summary collapse

Methods included from Leb128Helper

fetch_sleb128, fetch_uleb128

Methods included from ValueHelper

F32, F64, I32, I64

Class Method Details

.assert_read(sbuf, n) ⇒ Object



872
873
874
875
876
877
878
879
880
881
# File 'lib/wardite/load.rb', line 872

def self.assert_read(sbuf, n)
  ret = sbuf.read n
  if !ret
    raise LoadError, "too short section size"
  end
  if ret.size != n
    raise LoadError, "too short section size"
  end
  ret
end

.code_body(buf) ⇒ Object



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
# File 'lib/wardite/load.rb', line 617

def self.code_body(buf)
  dest = [] #: Array[Op]
  while c = buf.read(1)
    namespace, code = resolve_code(c, buf)
    operand_types = Op.operand_of(code)
    operand = [] #: Array[operandItem]
    operand_types.each do |typ|
      case typ
      when :u8
        ope = buf.read 1
        if ! ope
          raise LoadError, "buffer too short"
        end
        operand << ope.ord
      when :u32
        operand << fetch_uleb128(buf)
      when :u32_vec
        len = fetch_uleb128(buf)
        vec = [] #: Array[Integer]
        len.times do
          vec << fetch_uleb128(buf)
        end
        operand << vec
      when :i32
        operand << fetch_sleb128(buf)
      when :i64
        operand << fetch_sleb128(buf, max_level: 16)
      when :f32
        data = buf.read 4
        if !data || data.size != 4
          raise LoadError, "buffer too short"
        end
        v = data.unpack("e")[0]
        raise "String#unpack is broken" if !v.is_a?(Float)
        operand << v
      when :f64
        data = buf.read 8
        if !data || data.size != 8
          raise LoadError, "buffer too short"
        end
        v = data.unpack("E")[0]
        raise "String#unpack is broken" if !v.is_a?(Float)
        operand << v
      when :u8_block
        block_ope = buf.read 1
        if ! block_ope
          raise LoadError, "buffer too short for if"
        end
        if block_ope.ord == 0x40
          operand << Block.void
        else
          operand << Block.new([block_ope.ord])
        end
      else
        $stderr.puts "warning: unknown type #{typ.inspect}. defaulting to u32"
        operand << fetch_uleb128(buf)
      end         
    end

    dest << Op.new(namespace, code, operand)
  end

  dest
rescue => e
  require "pp"
  $stderr.puts "parsed:::"
  $stderr.puts "#{dest.pretty_inspect}"
  $stderr.puts "code = #{code}"
  raise e
end

.code_sectionObject



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
# File 'lib/wardite/load.rb', line 575

def self.code_section
  dest = CodeSection.new
  size = fetch_uleb128(@buf)
  dest.size = size
  sbuf = StringIO.new(@buf.read(size) || raise("buffer too short"))

  len = fetch_uleb128(sbuf)
  len.times do |i|
    ilen = fetch_uleb128(sbuf)
    code = assert_read(sbuf, ilen)
    last_code = code[-1]
    if ! last_code
      raise "[BUG] empty code fetched" # guard for steep check
    end
    if last_code.ord != 0x0b
      $stderr.puts "warning: instruction not ended with inst end(0x0b): 0x0#{last_code.ord}" 
    end
    cbuf = StringIO.new(code)
    locals_count = [] #: Array[Integer]
    locals_type = [] #: Array[Symbol]
    locals_len = fetch_uleb128(cbuf)
    locals_len.times do
      type_count = fetch_uleb128(cbuf)
      locals_count << type_count
      value_type = assert_read(cbuf, 1)&.ord
      locals_type << Op.i2type(value_type || -1)
    end
    body = code_body(cbuf)
    revisitor = Revisitor.new(body)
    revisitor.revisit!
    
    dest.func_codes << CodeSection::CodeBody.new do |b|
      b.locals_count = locals_count
      b.locals_type = locals_type
      b.body = revisitor.ops
    end
  end
  dest
end

.data_count_sectionObject



748
749
750
751
752
753
754
755
# File 'lib/wardite/load.rb', line 748

def self.data_count_section
  size = fetch_uleb128(@buf)
  sbuf = StringIO.new(@buf.read(size) || raise("buffer too short"))
  count = fetch_uleb128(sbuf)
  dest = DataCountSection.new(count)
  dest.size = size
  dest
end

.data_sectionObject



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
# File 'lib/wardite/load.rb', line 701

def self.data_section
  dest = DataSection.new
  size = fetch_uleb128(@buf)
  dest.size = size
  sbuf = StringIO.new(@buf.read(size) || raise("buffer too short"))

  len = fetch_uleb128(sbuf)
  len.times do |i|
    data_type = fetch_uleb128(sbuf)
    case data_type
    when 0x0
      # active
      code = fetch_insn_while_end(sbuf)
      ops = code_body(StringIO.new(code))
      offset = decode_expr(ops)
      len = fetch_uleb128(sbuf)
      data = sbuf.read len
      if !data
        raise LoadError, "buffer too short"
      end
      segment = DataSection::Segment.new do |seg|
        seg.mode = :active
        seg.mem_index = 0 # memory index
        seg.offset = offset
        seg.data = data
      end
      dest.segments << segment
    when 0x1
      # passive
      dsize = fetch_uleb128(sbuf)
      data = sbuf.read dsize
      if !data
        raise LoadError, "data too short"
      end
      segment = DataSection::Segment.new do |seg|
        seg.mode = :passive
        seg.mem_index = 0 # unused
        seg.offset = 0 # unused
        seg.data = data
      end
      dest.segments << segment
    end
  end
  dest
end

.decode_expr(ops) ⇒ Object



776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
# File 'lib/wardite/load.rb', line 776

def self.decode_expr(ops)
  # sees first opcode
  op = ops.first
  if !op
    raise LoadError, "empty opcodes"
  end
  case op.code
  when :i32_const
    arg = op.operand[0]
    if !arg.is_a?(Integer)
      raise "Invalid definition of operand"
    end
    return arg
  else
    raise "Unimplemented offset op: #{op.code.inspect}"
  end
end

.decode_global_expr(ops) ⇒ Object



796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
# File 'lib/wardite/load.rb', line 796

def self.decode_global_expr(ops)
  # sees first opcode
  op = ops.first
  if !op
    raise LoadError, "empty opcodes"
  end
  case op.code
  when :i32_const
    arg = op.operand[0]
    if !arg.is_a?(Integer)
      raise "Invalid definition of operand"
    end
    return I32(arg)
  when :i64_const
    arg = op.operand[0]
    if !arg.is_a?(Integer)
      raise "Invalid definition of operand"
    end
    return I64(arg)
  when :f32_const
    arg = op.operand[0]
    if !arg.is_a?(Float)
      raise "Invalid definition of operand"
    end
    return F32(arg)
  when :f64_const
    arg = op.operand[0]
    if !arg.is_a?(Float)
      raise "Invalid definition of operand"
    end
    return F64(arg)
  else
    raise "Unimplemented offset op: #{op.code.inspect}"
  end
end

.elem_sectionObject



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
# File 'lib/wardite/load.rb', line 472

def self.elem_section
  dest = ElemSection.new
  size = fetch_uleb128(@buf)
  dest.size = size
  sbuf = StringIO.new(@buf.read(size) || raise("buffer too short"))

  len = fetch_uleb128(sbuf)
  len.times do |i|
    etype = fetch_uleb128(sbuf)
    case etype
    when 0x0 # expr, vec(funcidx)
      dest.table_indices << 0 # default and fixed to table[0]

      code = fetch_insn_while_end(sbuf)
      ops = code_body(StringIO.new(code))
      offset = decode_expr(ops)
      dest.table_offsets << offset

      elms = [] #: Array[Integer]
      elen = fetch_uleb128(sbuf)
      elen.times do |i|
        index = fetch_uleb128(sbuf)
        elms << index
      end
      dest.element_indices << elms
    else
      raise NotImplementedError, "element section type #{etype} is a TODO!"
    end
  end
  dest
end

.export_sectionObject



833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
# File 'lib/wardite/load.rb', line 833

def self.export_section
  dest = ExportSection.new
  size = fetch_uleb128(@buf)
  dest.size = size
  sbuf = StringIO.new(@buf.read(size) || raise("buffer too short"))

  len = fetch_uleb128(sbuf)
  len.times do |i|
    nlen = fetch_uleb128(sbuf)
    name = assert_read(sbuf, nlen)
    kind_ = assert_read(sbuf, 1)
    kind = kind_[0]&.ord
    if !kind
      raise "[BUG] empty unpacked string" # guard rbs
    end

    index = fetch_uleb128(sbuf)
    dest.add_desc do |desc|
      desc.name = name
      desc.kind = kind
      desc.index = index
    end
  end

  dest
end

.fetch_insn_while_end(sbuf) ⇒ Object



759
760
761
762
763
764
765
766
767
768
769
770
771
772
# File 'lib/wardite/load.rb', line 759

def self.fetch_insn_while_end(sbuf)
  code = String.new("")
  loop {
    c = sbuf.read 1
    if !c
      break
    end
    code << c
    if c == "\u000b" # :end
      break
    end
  }
  code
end

.function_sectionObject



536
537
538
539
540
541
542
543
544
545
546
547
548
# File 'lib/wardite/load.rb', line 536

def self.function_section
  dest = FunctionSection.new
  size = fetch_uleb128(@buf)
  dest.size = size
  sbuf = StringIO.new(@buf.read(size) || raise("buffer too short"))

  len = fetch_uleb128(sbuf)
  len.times do |i|
    index = fetch_uleb128(sbuf)
    dest.func_indices << index
  end
  dest
end

.global_sectionObject



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
# File 'lib/wardite/load.rb', line 505

def self.global_section
  dest = GlobalSection.new
  size = fetch_uleb128(@buf)
  dest.size = size
  sbuf = StringIO.new(@buf.read(size) || raise("buffer too short"))

  len = fetch_uleb128(sbuf)
  len.times do |i|
    typeb = fetch_uleb128(sbuf)
    gtype = Op.i2type(typeb)
    mut = sbuf.read 1
    if !mut
      raise LoadError, "global section too short"
    end
    
    code = fetch_insn_while_end(sbuf)
    ops = code_body(StringIO.new(code))
    value = decode_global_expr(ops)

    global = GlobalSection::Global.new do |g|
      g.type = gtype
      g.mutable = (mut.ord == 0x01)
      g.shared = false # always
      g.value = value
    end
    dest.globals << global
  end
  dest
end

.import_sectionObject



406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
# File 'lib/wardite/load.rb', line 406

def self.import_section
  dest = ImportSection.new
  size = fetch_uleb128(@buf)
  dest.size = size
  sbuf = StringIO.new(@buf.read(size) || raise("buffer too short"))

  len = fetch_uleb128(sbuf)
  len.times do |i|
    mlen = fetch_uleb128(sbuf)
    module_name = assert_read(sbuf, mlen)
    nlen = fetch_uleb128(sbuf)
    name = assert_read(sbuf, nlen)
    kind_ = assert_read(sbuf, 1)
    kind = kind_[0]&.ord
    if !kind
      raise "[BUG] empty unpacked string" # guard rbs
    end

    index = fetch_uleb128(sbuf)
    dest.add_desc do |desc|
      desc.module_name = module_name
      desc.name = name
      desc.kind = kind
      desc.sig_index = index
    end
  end

  dest
end

.load_from_buffer(buf, import_object: {}, enable_wasi: true) ⇒ Object



256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
# File 'lib/wardite/load.rb', line 256

def self.load_from_buffer(buf, import_object: {}, enable_wasi: true)
  @buf = buf

  version = preamble
  sections_ = sections

  wasi_env = nil
  if enable_wasi
    require "wardite/wasi"
    wasi_env = Wardite::WasiSnapshotPreview1.new       
    import_object[:wasi_snapshot_preview1] = wasi_env
  end

  return Instance.new(import_object) do |i|
    i.version = version
    i.sections = sections_
    if enable_wasi
      i.wasi = wasi_env
    end
  end
end

.memory_sectionObject



437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
# File 'lib/wardite/load.rb', line 437

def self.memory_section
  dest = MemorySection.new
  size = fetch_uleb128(@buf)
  dest.size = size
  sbuf = StringIO.new(@buf.read(size) || raise("buffer too short"))

  len = fetch_uleb128(sbuf)
  if len != 1
    raise LoadError, "memory section has invalid size: #{len}"
  end
  len.times do |i|
    flags = fetch_uleb128(sbuf)
    min = fetch_uleb128(sbuf)

    max = nil
    if flags != 0
      max = fetch_uleb128(sbuf)
    end
    dest.limits << [min, max]
  end
  dest
end

.preambleObject



279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
# File 'lib/wardite/load.rb', line 279

def self.preamble
  asm = @buf.read 4
  if !asm
    raise LoadError, "buffer too short"
  end
  if asm != "\u0000asm"
    raise LoadError, "invalid preamble"
  end

  vstr = @buf.read(4)
  if !vstr
    raise LoadError, "buffer too short"
  end
  version = vstr.to_enum(:chars)
    .with_index
    .inject(0) {|dest, (c, i)| dest | (c.ord << i*8) }
  if version != 1
    raise LoadError, "unsupported version: #{version}"
  end
  version
end

.resolve_code(c, buf) ⇒ Object



691
692
693
694
695
696
697
698
# File 'lib/wardite/load.rb', line 691

def self.resolve_code(c, buf)
  namespace, code = Op.to_sym(c)
  if namespace == :fc
    lower = fetch_uleb128(buf)
    return Op.resolve_fc_sym(lower) #: [Symbol, Symbol]
  end
  return [namespace, code] #: [Symbol, Symbol]
end

.sectionsObject



302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
# File 'lib/wardite/load.rb', line 302

def self.sections
  sections = [] #: Array[Section]

  loop do
    byte = @buf.read(1)
    if !byte
      break
    end
    code = byte.ord

    section = case code
      when Wardite::SectionType
        type_section
      when Wardite::SectionImport
        import_section
      when Wardite::SectionFunction
        function_section
      when Wardite::SectionTable
        table_section
      when Wardite::SectionMemory
        memory_section
      when Wardite::SectionGlobal
        global_section
      when Wardite::SectionExport
        export_section
      when Wardite::SectionStart
        start_section
      when Wardite::SectionElement
        elem_section
      when Wardite::SectionCode
        code_section
      when Wardite::SectionData
        data_section
      when Wardite::Const::SectionDataCount
        data_count_section
      when Wardite::SectionCustom
        unimplemented_skip_section(code)
      else
        raise LoadError, "unknown code: #{code}(\"#{code.to_s 16}\")"
      end

    if section
      sections << section
    end
  end
  sections
end

.start_sectionObject



461
462
463
464
465
466
467
468
469
# File 'lib/wardite/load.rb', line 461

def self.start_section
  dest = StartSection.new
  size = fetch_uleb128(@buf)
  dest.size = size
  # StartSection won't use size
  func_index = fetch_uleb128(@buf)
  dest.func_index = func_index
  dest
end

.table_sectionObject



551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
# File 'lib/wardite/load.rb', line 551

def self.table_section
  dest = TableSection.new
  size = fetch_uleb128(@buf)
  dest.size = size
  sbuf = StringIO.new(@buf.read(size) || raise("buffer too short"))

  len = fetch_uleb128(sbuf)
  len.times do |i|
    code = fetch_uleb128(sbuf)
    type = Op.i2type(code)
    dest.table_types << type

    flags = fetch_uleb128(sbuf)
    min = fetch_uleb128(sbuf)
    max = nil
    if flags != 0
      max = fetch_uleb128(sbuf)
    end
    dest.table_limits << [min, max]
  end
  dest
end

.type_sectionObject



351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
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
# File 'lib/wardite/load.rb', line 351

def self.type_section
  dest = TypeSection.new

  size = fetch_uleb128(@buf)
  dest.size = size
  sbuf = StringIO.new(@buf.read(size) || raise("buffer too short"))

  len = fetch_uleb128(sbuf)
  len.times do |i|
    fncode = assert_read(sbuf, 1)
    if fncode != "\x60"
      raise LoadError, "not a function definition"
    end

    arglen = fetch_uleb128(sbuf)
    arg = [] #: Array[Symbol]
    arglen.times do
      case ty = assert_read(sbuf, 1)&.ord
      when 0x7f
        arg << :i32
      when 0x7e
        arg << :i64
      when 0x7d
        arg << :f32
      when 0x7c
        arg << :f64
      else
        raise NotImplementedError, "unsupported for now: #{ty.inspect}"
      end
    end
    dest.defined_types << arg

    retlen = fetch_uleb128(sbuf)
    ret = [] #: Array[Symbol]
    retlen.times do
      case ty = assert_read(sbuf, 1)&.ord
      when 0x7f
        ret << :i32
      when 0x7e
        ret << :i64
      when 0x7d
        ret << :f32
      when 0x7c
        ret << :f64
      else
        raise NotImplementedError, "unsupported for now: #{ty.inspect}"
      end
    end
    dest.defined_results << ret
  end

  dest
end

.unimplemented_skip_section(code) ⇒ Object



862
863
864
865
866
867
# File 'lib/wardite/load.rb', line 862

def self.unimplemented_skip_section(code)
  $stderr.puts "warning: unimplemented section: 0x0#{code}" if ENV['WARN_UNIMPLEMENTED_SECTION']
  size = fetch_uleb128(@buf)
  @buf.read(size)
  nil
end