Module: Wardite::BinaryLoader

Extended by:
Leb128Helper, ValueHelper
Defined in:
lib/wardite.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



604
605
606
607
608
609
610
611
612
613
# File 'lib/wardite.rb', line 604

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



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

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



400
401
402
403
404
405
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
435
# File 'lib/wardite.rb', line 400

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



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

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



546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
# File 'lib/wardite.rb', line 546

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

.export_sectionObject



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

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



529
530
531
532
533
534
535
536
537
538
539
540
541
542
# File 'lib/wardite.rb', line 529

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



385
386
387
388
389
390
391
392
393
394
395
396
397
# File 'lib/wardite.rb', line 385

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

.import_sectionObject



330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
# File 'lib/wardite.rb', line 330

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



187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
# File 'lib/wardite.rb', line 187

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



361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
# File 'lib/wardite.rb', line 361

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



205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
# File 'lib/wardite.rb', line 205

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



228
229
230
231
232
233
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
# File 'lib/wardite.rb', line 228

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
        unimplemented_skip_section(code)
      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



275
276
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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
# File 'lib/wardite.rb', line 275

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



594
595
596
597
598
599
# File 'lib/wardite.rb', line 594

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