-
Notifications
You must be signed in to change notification settings - Fork 0
/
RiscvEmulator.js
599 lines (565 loc) · 15.7 KB
/
RiscvEmulator.js
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
// BigUint64Array and BigInt polyfill.
//
// Mac/iOS doesn't seem to support BigUint64Array used in JS-WASM bridge
// generated by wasm-bindgen for transferring u64 type data and also BigInt
// yet. Perhaps it may be impossible to perfectly simulate BingUint64Array
// and BigInt so this polyfill is just for transferring the data properly
// without error via the JS-WASM bridge. It doesn't be expected to use for
// other purposes. And wasm-bindgen update can break this polyfill.
if (!('BigUint64Array' in window)) {
// Represents Uint64 as strings
const uint32Strings = (num) => {
return ('00000000' + num.toString(16)).slice(-8);
};
const composeUint64HexStrings = (uint32Low, uint32High) => {
const lowStr = uint32Strings(uint32Low);
const highStr = uint32Strings(uint32High);
return highStr + lowStr;
};
const lowerUint32 = uint64HexStr => {
return Number('0x' + uint64HexStr.slice(-8));
};
const higherUint32 = uint64HexStr => {
return Number('0x' + uint64HexStr.slice(0, 8));
};
const convertToUint64HexStrings = str => {
if (isNaN(Number(str))) {
throw new Error('Invalid format. ' + str);
}
// Assuming non-hex representation is in Number.MAX_SAFE_INTEGER
if (str.slice(0, 2).toLowerCase() !== '0x') {
str = '0x' + Number(str).toString(16);
}
return ('0000000000000000' + str.slice(2)).slice(-16);
};
// Assuming BigInt also isn't supported if BigUint64Array isn't supported
window.BigInt = str => {
return convertToUint64HexStrings(str);
};
window.BigUint64Array = new Proxy(Float64Array, {
construct(target, args) {
let obj;
const isArgumentArray = args.length === 1 && Array.isArray(args[0]);
if (isArgumentArray) {
const array = args[0];
obj = new Float64Array(array.length);
} else {
switch (args.length) {
case 0:
obj = new Float64Array();
break;
case 1:
obj = new Float64Array(args[0]);
break;
case 2:
obj = new Float64Array(args[0], args[1]);
break;
default:
obj = new Float64Array(args[0], args[1], args[2]);
break;
}
}
const p = new Proxy(obj, {
get(target, prop) {
const num = Number(prop);
if (Number.isInteger(num)) {
if (num >= target.length) {
return undefined;
}
const view = new Uint32Array(target.buffer);
const low = view[num * 2];
const high = view[num * 2 + 1];
return composeUint64HexStrings(low, high);
} else if (prop === 'set') {
return (array, offset = 0) => {
for (let i = 0; i < array.length; i++) {
p[offset + i] = array[i];
}
};
} else {
return target[prop];
}
},
set(target, prop, value) {
const num = Number(prop);
if (Number.isInteger(num)) {
const view = new Uint32Array(target.buffer);
const low = lowerUint32(value);
const high = higherUint32(value);
view[num * 2] = low;
view[num * 2 + 1] = high;
} else {
target[prop] = value;
}
return true;
}
});
if (isArgumentArray) {
const array = args[0];
for (let i = 0; i < array.length; i++) {
p[i] = array[i];
}
}
return p;
}
});
}
const charTable = {};
const u8_to_char = u8 => {
if (charTable[u8] === undefined) {
charTable[u8] = String.fromCharCode(u8);
}
return charTable[u8];
};
const u8s_to_strings = u8s => {
let s = '';
for (const u8 of u8s) {
s += u8_to_char(u8);
}
return s;
};
export default class RiscvEmulator {
constructor(riscv, terminal, options = {}) {
this.riscv = riscv;
this.terminal = terminal;
this.debugModeEnabled = options.debugModeEnabled !== undefined ? options.debugModeEnabled : false;
this.runCyclesNum = options.runCyclesNum !== undefined ? options.runCyclesNum : 0x10000;
this.inDebugMode = false;
this.inputs = [];
this.breakpoints = [];
this.lastCommandStrings = '';
this._setupInputEventHandlers();
}
_setupInputEventHandlers() {
this.terminal.onKey(event => {
if (this.inDebugMode) {
this._handleKeyInputInDebugMode(event.key, event.domEvent.keyCode);
} else {
this._handleKeyInput(event.key, event.domEvent.keyCode);
}
});
// I don't know why but terminal.onKey doesn't catch
// space key so handling in document keydown event listener.
document.addEventListener('keydown', event => {
if (event.keyCode === 32) {
if (this.inDebugMode) {
this._handleKeyInputInDebugMode(' ', 32);
} else {
this._handleKeyInput(' ', 32);
}
}
event.preventDefault();
});
}
_handleKeyInput(key, keyCode) {
if (this.debugModeEnabled && key.charCodeAt(0) === 1) { // Ctrl-A
this.inDebugMode = true;
return;
}
const inputs = this.inputs;
// xterm.js doesn't handle function keys so
// handling by myself here
switch (keyCode) {
case 32: // Space
inputs.push(32);
break;
case 33: // Page up
inputs.push(27, 91, 53, 126);
break;
case 34: // Page down
inputs.push(27, 91, 54, 126);
break;
case 35: // End
inputs.push(27, 91, 52, 126);
break;
case 36: // Home
inputs.push(27, 91, 49, 126);
break;
case 37: // Arrow Left
inputs.push(27, 91, 68);
break;
case 38: // Arrow Up
inputs.push(27, 91, 65);
break;
case 39: // Arrow Right
inputs.push(27, 91, 67);
break;
case 40: // Arrow Down
inputs.push(27, 91, 66);
break;
case 45: // Insert
inputs.push(27, 91, 50, 126);
break;
case 46: // Delete
inputs.push(127);
break;
case 112: // F1
inputs.push(27, 79, 80);
break;
case 113: // F2
inputs.push(27, 79, 81);
break;
case 114: // F3
inputs.push(27, 79, 82);
break;
case 115: // F4
inputs.push(27, 79, 83);
break;
case 116: // F5
inputs.push(27, 91, 49, 53, 126);
break;
case 117: // F6
inputs.push(27, 91, 49, 55, 126);
break;
case 118: // F7
inputs.push(27, 91, 49, 6, 126);
break;
case 119: // F8
inputs.push(27, 91, 49, 57, 126);
break;
case 120: // F9
inputs.push(27, 91, 50, 48, 126);
break;
case 121: // F10
inputs.push(27, 91, 50, 49, 126);
break;
case 122: // F11
inputs.push(27, 91, 50, 50, 126);
break;
case 123: // F12
inputs.push(27, 91, 50, 51, 126);
break;
default:
inputs.push(key.charCodeAt(0));
break;
}
}
async _handleKeyInputInDebugMode(key, keyCode) {
switch(keyCode) {
case 8: // backspace
// Do not delete the prompt
if (this.terminal._core.buffer.x > 2) {
this.terminal.write('\b \b');
}
break;
case 13: // new line
const lines = this.terminal._core.buffer.lines;
// Is there easier way to get last line?
const y = this.terminal._core.buffer.y < this.terminal.rows - 1
? this.terminal._core.buffer.y : lines.length - 1;
const line = lines.get(y);
const length = line.getTrimmedLength();
let commandStrings = '';
for (let i = 2; i < length; i++) {
commandStrings += line.getString(i);
}
if (commandStrings.trim() === '') {
commandStrings = this.lastCommandStrings;
}
const command = this._parseCommand(commandStrings);
this.lastCommandStrings = commandStrings;
this.terminal.writeln('');
if (!await this._runCommand(command)) {
this.terminal.writeln('Unknown command.');
}
if (this.inDebugMode) {
this.prompt();
}
break;
default:
this.terminal.write(key);
break;
}
}
_parseCommand(s) {
return s.trim().split(/\s+/);
}
async _runCommand(command) {
if (command.length === 0) {
return false;
}
switch(command[0].toLowerCase()) {
case '':
// Do nothing
return command.length === 1;
break;
// UGH...
case 'b':
case 'br':
case 'bre':
case 'brea':
case 'break':
case 'breakp':
case 'breakpo':
case 'breakpoi':
case 'breakpoin':
case 'breakpoint':
if (command.length === 1) {
this.displayBreakpoints();
return true;
} else if (command.length === 2) {
this.setBreakpoint(command[1]);
return true;
} else {
return false;
}
break;
case 'c':
case 'co':
case 'con':
case 'cont':
case 'conti':
case 'contin':
case 'continu':
case 'continue':
if (command.length === 1) {
await this.continue();
return true;
} else {
return false;
}
break;
case 'd':
case 'de':
case 'del':
case 'dele':
case 'delet':
case 'delete':
if (command.length === 2) {
this.deleteBreakpoint(command[1]);
return true;
} else {
return false;
}
break;
case 'h':
case 'he':
case 'hel':
case 'help':
if (command.length === 1) {
this.displayDebugCommands();
return true;
} else {
return false;
}
break;
case 'm':
case 'me':
case 'mem':
if (command.length === 2) {
this.displayMemoryContent(command[1]);
return true;
} else {
return false;
}
break;
case 'p':
case 'pc':
if (command.length === 1) {
this.displayPCContent();
return true;
} else {
return false;
}
break;
case 'r':
case 're':
case 'reg':
if (command.length === 2) {
this.displayRegisterContent(command[1]);
return true;
} else {
return false;
}
break;
case 's':
case 'st':
case 'ste':
case 'step':
switch (command.length) {
case 1:
this.step(1);
return true;
case 2:
this.step(command[1]);
return true;
default:
return false;
}
break;
default:
return false;
}
}
displayDebugCommands() {
this.terminal.writeln('Commands:');
this.terminal.writeln(' breakpoint: Show breakpoint set list.');
this.terminal.writeln(' breakpoint <virtual_address|symbol>: Set breakpoint.');
this.terminal.writeln(' delete <virtual_address>: Delete breakpoint.');
this.terminal.writeln(' continue: Continue the main program. Ctrl-A enters debug mode again.');
this.terminal.writeln(' help: Show this message');
this.terminal.writeln(' mem <virtual_address>: Show eight-byte content of memory');
this.terminal.writeln(' pc: Show PC content');
this.terminal.writeln(' reg <register_num>: Show register content');
this.terminal.writeln(' step [num]: Run [num](one if omitted) step(s) execution');
this.terminal.writeln('');
}
step(numOrNumStr) {
const num = parseInt(numOrNumStr);
if (isNaN(num)) {
this.terminal.writeln('Invalid num.');
return false;
}
this.riscv.run_cycles(num);
this.flush();
this.riscv.disassemble_next_instruction();
this.flush();
this.terminal.writeln('');
}
run() {
const runCycles = () => {
setTimeout(runCycles, 0);
this.riscv.run_cycles(this.runCyclesNum);
this.flush();
while (this.inputs.length > 0) {
this.riscv.put_input(this.inputs.shift());
}
};
this.inDebugMode = false;
this.lastCommandStrings = '';
runCycles();
}
async continue() {
this.inDebugMode = false;
return new Promise(resolve => {
const runCycles = async () => {
if (this.inDebugMode) {
this.step(0);
return resolve();
}
setTimeout(runCycles, 0);
if (this.breakpoints.length === 0) {
// If no breakpoint set, we don't need to take care breakpoints
// so calling run_cycles() which should be faster than
// run_until_breakpoints()
this.riscv.run_cycles(this.runCyclesNum);
} else {
if (this.riscv.run_until_breakpoints(new BigUint64Array(this.breakpoints), this.runCyclesNum)) {
this.inDebugMode = true;
}
}
this.flush();
while (this.inputs.length > 0) {
this.riscv.put_input(this.inputs.shift());
}
};
runCycles();
});
}
displayMemoryContent(vAddressStr) {
let vAddress;
try {
vAddress = BigInt(vAddressStr);
} catch (e) {
this.terminal.writeln('Invalid virtual address.');
return;
}
const error = new Uint8Array([0]);
const data = this.riscv.load_doubleword(vAddress, error);
switch (error[0]) {
case 0:
this.terminal.writeln('0x' + data.toString(16));
break;
case 1:
this.terminal.writeln('Page fault.');
break;
case 2:
this.terminal.writeln('Invalid address.');
break;
default:
this.terminal.writeln('Unknown error code.');
break;
}
}
displayRegisterContent(regNumStr) {
const regNum = parseInt(regNumStr);
if (isNaN(regNum)) {
this.terminal.writeln('Invalid register number.');
return;
}
if (regNum < 0 || regNum > 31) {
this.terminal.writeln('Register number should be 0-31.');
return;
}
this.terminal.writeln('0x' + this.riscv.read_register(regNum).toString(16));
}
displayPCContent() {
this.terminal.writeln('0x' + this.riscv.read_pc().toString(16));
}
setBreakpoint(arg) {
let vAddress;
if (!isNaN(parseInt(arg))) {
try {
vAddress = BigInt(arg);
} catch (e) {
this.terminal.writeln('Invalid virtual address.');
return;
}
} else {
const error = new Uint8Array([0]);
vAddress = this.riscv.get_address_of_symbol(arg, error);
if (error[0]) {
this.terminal.writeln('Symbol is not found.');
return;
}
}
if (this.breakpoints.includes(vAddress)) {
this.terminal.writeln('Already set.');
return;
}
this.breakpoints.push(vAddress);
this.terminal.writeln('Breakpoint is set at 0x' + vAddress.toString(16));
}
deleteBreakpoint(vAddressStr) {
let vAddress;
try {
vAddress = BigInt(vAddressStr);
} catch (e) {
this.terminal.writeln('Invalid virtual address.');
return;
}
if (!this.breakpoints.includes(vAddress)) {
this.terminal.writeln('Not found.');
return;
}
this.breakpoints.splice(this.breakpoints.indexOf(vAddress), 1);
}
displayBreakpoints() {
for (const b of this.breakpoints) {
this.terminal.writeln('0x' + b.toString(16));
}
}
flush() {
const outputBytes = [];
while (true) {
const data = this.riscv.get_output();
if (data !== 0) {
outputBytes.push(data);
} else {
break;
}
}
if (outputBytes.length > 0) {
this.terminal.write(u8s_to_strings(outputBytes));
}
}
startDebugMode() {
this.inDebugMode = true;
this.displayDebugCommands()
this.step(0);
this.prompt();
}
prompt() {
this.terminal.write('% ');
}
}