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



668
669
670
671
672
673
674
675
676
677
# File 'lib/wardite/load.rb', line 668

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



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

def self.code_body(buf)
  dest = []
  while c = buf.read(1)
    namespace, code = Op.to_sym(c)
    operand_types = Op.operand_of(code)
    operand = [] #: Array[Integer|Float|Block]
    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 :i32
        operand << fetch_sleb128(buf)
      when :i64
        operand << fetch_sleb128(buf)
      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_if_block # :if specific
        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
end

.code_sectionObject



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

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 = []
    locals_type = []
    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)
    dest.func_codes << CodeSection::CodeBody.new do |b|
      b.locals_count = locals_count
      b.locals_type = locals_type
      b.body = body
    end
  end
  dest
end

.data_sectionObject



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

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|
    mem_index = fetch_uleb128(sbuf)
    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.flags = mem_index
      seg.offset = offset
      seg.data = data
    end
    dest.segments << segment
  end
  dest
end

.decode_expr(ops) ⇒ Object



583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
# File 'lib/wardite/load.rb', line 583

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



603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
# File 'lib/wardite/load.rb', line 603

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)
  # TODO: floats
  else
    raise "Unimplemented offset op: #{op.code.inspect}"
  end
end

.export_sectionObject



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

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.func_index = index
    end
  end

  dest
end

.fetch_insn_while_end(sbuf) ⇒ Object



566
567
568
569
570
571
572
573
574
575
576
577
578
579
# File 'lib/wardite/load.rb', line 566

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



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

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



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

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



336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
# File 'lib/wardite/load.rb', line 336

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



193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
# File 'lib/wardite/load.rb', line 193

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

  version = preamble
  sections_ = sections

  if enable_wasi
    wasi_env = Wardite::WasiSnapshotPreview1.new       
    import_object[:wasi_snapshot_preview1] = wasi_env.to_module
  end

  return Instance.new(import_object) do |i|
    i.version = version
    i.sections = sections_
  end
end

.memory_sectionObject



367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
# File 'lib/wardite/load.rb', line 367

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



211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
# File 'lib/wardite/load.rb', line 211

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

.sectionsObject



234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
# File 'lib/wardite/load.rb', line 234

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
        unimplemented_skip_section(code)
      when Wardite::SectionMemory
        memory_section
      when Wardite::SectionGlobal
        global_section
      when Wardite::SectionExport
        export_section
      when Wardite::SectionStart
        unimplemented_skip_section(code)
      when Wardite::SectionElement
        unimplemented_skip_section(code)
      when Wardite::SectionCode
        code_section
      when Wardite::SectionData
        data_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

.type_sectionObject



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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
# File 'lib/wardite/load.rb', line 281

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 = []
    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 = []
    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



658
659
660
661
662
663
# File 'lib/wardite/load.rb', line 658

def self.unimplemented_skip_section(code)
  $stderr.puts "warning: unimplemented section: 0x0#{code}"
  size = @buf.read(1)&.ord
  @buf.read(size)
  nil
end