-
Notifications
You must be signed in to change notification settings - Fork 1
/
rcl_vm.rb
619 lines (513 loc) · 11.4 KB
/
rcl_vm.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
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
273
274
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
328
329
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
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
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
436
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
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
require "pp"
require "json"
require_relative "common"
module TermColor
RESET = "\e[m"
RED = "\e[0;31m"
BLUE = "\e[0;34m"
end
class MemRef
attr_reader :base, :disp, :index
def initialize(base, disp, index)
@base = base
@disp = disp
@index = index
end
end
class Insn
attr_reader :opcode, :operands
def initialize(opcode, operands)
@opcode = opcode
@operands = operands
@_dump_str = [@opcode, *@operands].inspect
end
def dump
@_dump_str
end
end
class Memory
attr_accessor :code
attr_reader :data, :vram
CODE_DUMP_WIDTH = 10
def initialize(data_size)
@code = []
@data = Array.new(data_size, 0)
@vram = Array.new(50, 0)
end
def label?(insn)
insn.opcode == :_cmt && insn.operands[0].start_with?("label:")
end
def dump_code(pc)
work_insns = []
@code.each_with_index do |insn, i|
work_insns << { addr: i, insn: insn }
end
work_insns
.select do |work_insn|
pc - CODE_DUMP_WIDTH <= work_insn[:addr] &&
work_insn[:addr] <= pc + CODE_DUMP_WIDTH
end
.map do |work_insn|
head =
if work_insn[:addr] == pc
"pc =>"
else
" "
end
opcode = work_insn[:insn].opcode
color =
case opcode
when "exit", "call", "ret", "jump", "jump_eq", "jump_g"
TermColor::RED
when "_cmt", "_debug"
TermColor::BLUE
else
""
end
indent =
if label?(work_insn[:insn])
""
else
" "
end
format(
"%s %02d #{color}%s%s#{TermColor::RESET}",
head,
work_insn[:addr],
indent,
work_insn[:insn].dump
)
end
.join("\n")
end
def _chr(n)
if n.nil?
return "! nil"
end
unless n.is_a?(Integer)
return "! non-integer"
end
if n < 32
if n == 12
"LF"
else
"ctrl"
end
elsif 32 <= n && n < 128
"'#{n.chr}'"
else
""
end
end
def dump_data(sp, bp)
lines = []
@data.each_with_index do |x, i|
addr = i
next if addr < sp - 12
next if addr > sp + 8
head =
case addr
when sp
if sp == bp
"sp bp => "
else
"sp => "
end
when bp
" bp => "
else
" "
end
begin
lines << head + format("%04d % 4d %s", addr, x, _chr(x))
rescue => e
lines << [e.message, { x: x }].inspect
end
end
lines.join("\n")
end
def format_cols(cols)
cols.map {|col| col == 1 ? "@" : "." }.join("")
end
def dump_vram
rows = @vram.each_slice(5).to_a
main = rows[0..4]
buf = rows[5..9]
(0..4)
.map do |li| # line index
format_cols(main[li]) + " " + format_cols(buf[li])
end
.join("\n")
end
end
class Vm
FLAG_TRUE = 1
FLAG_FALSE = 0
EOF = -1
def initialize(mem, data_size, debug, verbose, skip)
@debug = debug
@verbose =
if @debug
true
else
verbose
end
@skip = skip
@pc = 0 # program counter
# registers
@reg_a = 0
@reg_b = 0
@zf = FLAG_FALSE # zero flag
@sf = FLAG_FALSE # sign flag
@mem = mem
@sp = data_size - 1 # stack pointer
@bp = data_size - 1 # base pointer
@step = 0
@output = ""
end
def set_sp(addr)
if addr < 0
dump_at_exit()
raise "Stack overflow"
end
@sp = addr
end
def to_operand(el)
case el
when String
if %w[reg_a reg_b sp bp].include?(el)
el.to_sym
elsif el.start_with?("mem:")
_, base_str, disp_str, index_str = el.split(":")
base = to_operand(base_str)
disp = to_operand(disp_str).to_i
index = to_operand(index_str).to_i
MemRef.new(base, disp, index)
elsif /^-?\d+$/.match?(el)
el.to_i
else
el
end
else
el
end
end
def load_program_file(path)
insns = File.open(path).each_line.map { |line| JSON.parse(line) }
load_program(insns)
end
def load_program(insns)
@mem.code = insns
.map do |insn|
opcode, *operands = insn
operands = operands.map { |it| to_operand(it) }
Insn.new(opcode.to_sym, operands)
end
end
def execute
insn = @mem.code[@pc]
opcode = insn.opcode
case opcode
when :exit then return insn.operands[0]
when :cp then cp() ; @pc += 1
when :lea then lea() ; @pc += 1
when :add_ab then add_ab() ; @pc += 1
when :mult_ab then mult_ab() ; @pc += 1
when :add_sp then add_sp() ; @pc += 1
when :sub_sp then sub_sp() ; @pc += 1
when :compare then compare() ; @pc += 1
when :jump then jump()
when :jump_eq then jump_eq()
when :jump_g then jump_g()
when :call then call()
when :ret then ret()
when :push then push() ; @pc += 1
when :pop then pop() ; @pc += 1
when :read then read() ; @pc += 1
when :write then write() ; @pc += 1
when :set_vram then set_vram() ; @pc += 1
when :get_vram then get_vram() ; @pc += 1
when :_cmt then @pc += 1
when :_debug then _debug() ; @pc += 1
else
raise "Unknown opcode (#{opcode})"
end
nil
end
def start
dump() # 初期状態
if @debug
$stderr.puts "Press enter key to start"
$stdin.gets
end
loop do
@step += 1
exit_status = execute()
if exit_status
dump()
$stderr.puts "exit" if @verbose
return exit_status
end
dump() if @step % @skip == 0
$stdin.gets if @debug
end
end
def dump_reg
[
"reg_a(#{ @reg_a.inspect })",
"reg_b(#{ @reg_b.inspect })"
].join(" ")
end
def dump
return unless @verbose
$stderr.puts <<~DUMP
================================
#{ @step }: #{ dump_reg() } zf(#{ @zf }) sf(#{ @sf })
---- memory (code) ----
#{ @mem.dump_code(@pc) }
---- memory (data) ----
#{ @mem.dump_data(@sp, @bp) }
---- memory (vram) ----
#{ @mem.dump_vram() }
---- output ----
#{ @output.inspect }
DUMP
end
def dump_for_test
puts "reg_a (#{@reg_a})"
puts "reg_b (#{@reg_b})"
puts "pc (#{@pc})"
puts "bp (#{@bp})"
puts "sp (#{@sp})"
puts "zf (#{@zf})"
puts "sf (#{@sf})"
end
def get_value(operand)
case operand
when Integer then operand
when Symbol
case operand
when :reg_a then @reg_a
when :reg_b then @reg_b
when :sp then @sp
when :bp then @bp
else
raise panic("operand", operand)
end
when MemRef
@mem.data[calc_indirect_addr(operand)]
else
raise panic("operand", operand)
end
end
def set_value(dest, val)
case dest
when Symbol
case dest
when :reg_a then @reg_a = val
when :reg_b then @reg_b = val
when :sp then @sp = val
when :bp then @bp = val
else
raise panic("dest", dest)
end
when MemRef
@mem.data[calc_indirect_addr(dest)] = val
else
raise panic("dest", dest)
end
end
def calc_indirect_addr(memref)
base = get_value(memref.base)
disp = memref.disp
index = memref.index
base + disp + index
end
def dump_at_exit
lines = []
@mem.data.each_with_index do |n, i|
line = format("%04d (% 4d) (0x% 4x)", i, n, n)
if 32 <= n && n <= 126
line += " (#{ n.chr })"
end
lines << line
end
File.open("tmp/dump.txt", "wb") { |f|
f.puts lines.join("\n")
}
end
# --------------------------------
def fetch_operand(i)
@mem.code[@pc].operands[i]
end
def add_ab
@reg_a = @reg_a + @reg_b
end
def mult_ab
@reg_a = @reg_a * @reg_b
end
def cp
arg_src = fetch_operand(0)
arg_dest = fetch_operand(1)
src_val = get_value(arg_src)
set_value(arg_dest, src_val)
end
# load effective address
def lea
dest = fetch_operand(0)
src = fetch_operand(1)
addr =
case src
when MemRef
calc_indirect_addr(src)
else
raise panic("src", src)
end
set_value(dest, addr)
end
def add_sp
set_sp(@sp + fetch_operand(0))
end
def sub_sp
set_sp(@sp - fetch_operand(0))
end
def compare
result = @reg_b - @reg_a
@zf = (result == 0) ? FLAG_TRUE : FLAG_FALSE
@sf = (0 <= result) ? FLAG_TRUE : FLAG_FALSE
end
def jump
jump_dest = fetch_operand(0)
@pc = jump_dest
end
def jump_eq
if @zf == FLAG_TRUE
jump_dest = fetch_operand(0)
@pc = jump_dest
else
@pc += 1
end
end
def jump_g
if @zf == FLAG_FALSE && @sf == FLAG_TRUE
jump_dest = fetch_operand(0)
@pc = jump_dest
else
@pc += 1
end
end
def call
set_sp(@sp - 1) # スタックポインタを1減らす
@mem.data[@sp] = @pc + 1 # 戻り先を記憶
next_addr = fetch_operand(0) # ジャンプ先
@pc = next_addr
end
def ret
ret_addr = @mem.data[@sp] # 戻り先アドレスを取得
@pc = ret_addr # 戻る
set_sp(@sp + 1) # スタックポインタを戻す
end
def push
arg = fetch_operand(0)
val_to_push = get_value(arg)
set_sp(@sp - 1)
@mem.data[@sp] = val_to_push
end
def pop
arg = fetch_operand(0)
val = @mem.data[@sp]
set_value(arg, val)
set_sp(@sp + 1)
end
def read
raise "stdin is not available" if $stdin_.nil?
arg = fetch_operand(0)
c = $stdin_.getc
n = c.nil? ? EOF : c.ord
set_value(arg, n)
end
def write
arg_val = fetch_operand(0)
arg_fd = fetch_operand(1)
n = get_value(arg_val)
c = n.chr
fd = get_value(arg_fd)
case fd
when 1
$stdout.write c
when 2
$stderr.write c
else
raise "invalid fd (#{fd})"
end
@output += c
if 80 < @output.size
@output = @output[1..-1]
end
end
def set_vram
arg_vram = fetch_operand(0) # dest (vram)
arg_val = fetch_operand(1) # src
src_val = get_value(arg_val)
case arg_vram
when Integer
@mem.vram[arg_vram] = src_val
when MemRef
vram_addr = @mem.data[calc_indirect_addr(arg_vram)]
@mem.vram[vram_addr] = src_val
else
raise panic("arg_vram", arg_vram)
end
end
def get_vram
arg_vram = fetch_operand(0) # src (vram)
arg_dest = fetch_operand(1) # dest
vram_addr = get_value(arg_vram)
val = @mem.vram[vram_addr]
set_value(arg_dest, val)
end
def _debug
@debug = true
end
end
def env_to_bool(key, default = false)
if ENV.key?(key)
case ENV[key]
when "0" then false
when "1" then true
else default
end
else
false
end
end
def env_to_int(key, default = 1)
if ENV.key?(key)
ENV[key].to_i
else
default
end
end
$stdin_ = nil
if $PROGRAM_NAME == __FILE__
exe_file = ARGV[0]
stdin_file = ENV.fetch("STDIN", File.join(__dir__, "tmp/stdin"))
if File.exist?(stdin_file)
$stdin_ = File.open(stdin_file, "rb")
end
data_size = 2_000_000
mem = Memory.new(data_size)
vm = Vm.new(
mem,
data_size,
env_to_bool("DEBUG"),
env_to_bool("VERBOSE"),
env_to_int("SKIP", 1)
)
vm.load_program_file(exe_file)
exit_status = vm.start
if ENV["DUMP_FOR_TEST"] == "1"
vm.dump_for_test
end
exit exit_status
end