-
Notifications
You must be signed in to change notification settings - Fork 2
/
i8080_x86_style.html
3433 lines (3233 loc) · 130 KB
/
i8080_x86_style.html
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
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
687
688
689
690
691
692
693
694
695
696
697
698
699
700
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
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
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
831
832
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
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<html>
<head>
<title>Binary Pattern</title>
<script>
/*
i8275 CRT-Controller: Simply version
00000000:
000000nn:
000001nn:
00001nnn:
0001nnnn:
0010nnnn:
0100nnnn: Lines [1..16]-1
01nnnnnn: Rows [16..64]-1
1000nnnn:
1nnnnnnn: Cols [16..80]-1
1101nnnn:
1110nnnn:
1111nnnn:
40..4F: Set Lines [1..16]
50..7F: Set Rows [16..64]
90..CF: Set Cols [16..80]
*/
Number.prototype.toHex = function(n) {
return (n < 0 ? "0x" : "") + ((((this >> 16) & 0x0000FFFF) | 0x00010000).toString(16) + ((this & 0x0000FFFF) | 0x00010000).toString(16).substr(1)).substr(-Math.abs(n)).toUpperCase();
}
Object.defineProperty(Array.prototype, 'toDump', {
enumerable : false,
value : function(fmt, ptr) {
var width = fmt.split(".").length - 1,
minuses = (fmt.split("-").length - 1) >> 1,
pluses = (fmt.split("+").length - 1) >> 1,
codes = "",
letters = [],
address = ptr.toHex(fmt.split("@").length - 1).split(""),
data;
ptr -= minuses;
while(width --)
data = Number(this[((ptr + width + this.length) % this.length)]),
codes = data.toHex(2) + codes,
letters.unshift(data < 32 || data > 126 ? "·" : "&#" + data + ";");
codes = codes.split("");
return fmt.replace(/[-@.+]/g,
function(letter) {
switch(letter) {
case ".": return letters.shift();
case "@": return address.shift();
default: return codes.shift();
}
}
);
}
}
);
Object.defineProperty(Array.prototype, 'toHex', {
enumerable : false,
value : function(ofs, sep) {
var s = "", t = [], n, tmp;
if(sep && sep.length > 1) {
n = sep.split(/\s+|\|/).length;
ofs -= sep.split(/\|/)[0].split(/\s/).length;
while(n --)
tmp = this[(ofs + n + this.length) % this.length],
s = tmp.toHex(2) + s,
t.unshift("&#" + (tmp >= 32 && tmp < 127 ? tmp : 0xB7) + ";");
return sep.replace(/-|\./g, function(c) {
var tmp;
if(c == "-")
tmp = s.charAt(0),
s = s.substr(1);
else
tmp = t.shift();
return tmp;
}).replace(/\s/g, "\xA0");
}
tmp = [];
this.forEach(function(code) {
tmp.push(Number(code).toHex(2));
});
s = tmp.join("\xA0");
return !ofs || !sep ? s : s.replace(new RegExp("(([0-9A-F]{2}\\s?){" + ofs + "})\\s", "g"), "$1" + sep);
}
});
Object.defineProperty(Array.prototype, 'toText', {
enumerable : false,
value : function() {
var s = "";
this.forEach(function(code) {
s += "&#" + /*String.fromCharCode*/(c >= 32 && c < 127 ? c : 0xB7) + ";";
});
return s;
}
});
String.prototype.x = function(n, j) {var s = this, buf = ""; while(n > 0) { if(n&1) buf+=s; s+=(j?j:"")+s; n >>= 1; } return buf; }
Number.prototype.hi = function(n) {
if(isFinite(n))
return (this & 255) | ((n & 255) << 8);
return (this >> 8) & 255;
}
Number.prototype.lo = function(n) {
if(isFinite(n))
return (this & 0xFF00) | (n & 255);
return this & 255;
}
var CPU =
function(pattern) {
"use strict"
var Register =
function(x) {
return {
id : "",
fx : 0,
hi : (x >> 8) & 255,
lo : x & 255,
start : x & 65535,
get reset() {
this.lo = this.start & 255,
this.hi = this.start >> 8;
return this.lo | (this.hi << 8);
},
get h() {
return this.hi;
},
set h(x) {
this.fx = (x >> 8) & 1;
this.hi = (x &= 255);
this.fx |= (x & 128) | (!x ? 64 : 0);
x ^= x >> 4;
x ^= x << 2;
x ^= x >> 1;
this.fx |= x & 4;
//console.log(this.id + ":" + (this.lo | (this.hi << 8)).toHex(-4));
},
get l() {
return this.lo;
},
set l(x) {
this.fx = (x >> 8) & 1;
this.lo = (x &= 255);
this.fx |= (x & 128) | (!x ? 64 : 0);
x ^= x >> 4;
x ^= x << 2;
x ^= x >> 1;
this.fx |= x & 4;
//console.log(this.id + ":" + (this.lo | (this.hi << 8)).toHex(-4));
},
get x() {
//console.log(this.id + ":" + (this.lo | (this.hi << 8)).toHex(-4));
return this.lo | (this.hi << 8);
},
set x(x) {
this.lo = x & 255, this.hi = (x >> 8) & 255;
//console.log(this.id + ":" + (this.lo | (this.hi << 8)).toHex(-4));
},
get m() {
//console.log(this.id + "[" + (this.lo | (this.hi << 8)).toHex(-4) + "]:" + (ram[this.lo | (this.hi << 8)] & 255).toHex(-2));
return ram[this.lo | (this.hi << 8)] & 255;
},
set m(x) {
ram[this.lo | (this.hi << 8)] = x & 255;
//console.log(this.id + "[" + (this.lo | (this.hi << 8)).toHex(-4) + "]=" + (ram[this.lo | (this.hi << 8)] & 255).toHex(-2));
},
get n() {
var x = this.lo | (this.hi << 8);
this.lo = (this.lo + 1) & 255;
this.hi = !this.lo ? (this.hi + 1) & 255 : this.hi;
return ram[x];
},
set n(x) {
this.hi = !this.lo ? (this.hi - 1) & 255 : this.hi;
this.lo = (this.lo - 1) & 255;
ram[this.lo | (this.hi << 8)] = x & 255;
},
get w() {
var x = this.lo | (this.hi << 8), d;
this.lo = (this.lo + 2) & 255;
this.hi = this.lo < 2 ? (this.hi + 1) & 255 : this.hi;
d = ram[x] + 256 * ram[(x + 1) & 65535];
//console.log("[" + x.toHex(-4) + "]:" + d.toHex(-4));
return d;
},
set w(x) {
this.hi = this.lo < 2 ? (this.hi - 1) & 255 : this.hi;
this.lo = (this.lo - 2) & 255;
ram[this.lo | (this.hi << 8)] = x & 255;
ram[(this.lo + (this.hi << 8) + 1) & 65535] = (x >> 8) & 255;
//console.log("[" + (this.lo | (this.hi << 8)).toHex(-4) + "]=" + x.toHex(-4));
},
}
};
var CPU_ID = "XPU v1.0";
var m = null; // Memory
var r = null; // Registers
var core = {
actions : [], // Instructions set
commands : [], // Assembly commands
is_active : false, // Execution activity
scale : 1, // Instructions per cycle
clock : 512, // Cycles per second
ready : false, // Model status
};
var user = {
actions : null, // Browsing instructions set table
disassemblies : null, // Browsing disassembling list
styles : { // Instruction presentable styles
style : 0, // Unactive instruction presentable style
active : 1, // Active instruction
breaker : 2, // Breaked instruction
crack : 3, // Breaked active instruction
debug : 4, // Debug view selected instruction
enable : 5, // Debug view active instruction
fixed : 6, // Debug view breaked instruction
gap : 7, // Debug view breaked active instruction
zip : [], // Enumerated styles table for disassembler
},
};
var debug = {
active : true, // Active debug / Running
step : false, // Single step debugging
halt : [], // Break-points
text : [], // Text-points
labels : [], // Labels
address : 0,
pointer : 0, // Disassembly start address
lines : 32, // Disassembly rows number
string : "", // Disassembling format
data : [], // Disassembling data representation
flash : 10, // Screen redraws per second
choice : 0xF803, // User line
stamps : [0,0],
hTimer : null,
};
var watch = {
iAdjust : 0,
nAdujst : 1,
sAdjust : "",
dirty : true,
};
var Logging = [];
var $0, $1, $2;
// Отображение таблицы команд
this.showCommands = function(e) {
user.actions = e;
};
// Отображение таблицы команд
this.showListing = function(e) {
user.disassemblies = e;
user.disassemblies.onmousemove = function(e) {
//document.title = t.r;
}
user.disassemblies.onkeyup = function(e) {
function getCharacterOffsetWithin(range, node) {
var treeWalker = document.createTreeWalker(
node,
NodeFilter.SHOW_TEXT,
function(node) {
var nodeRange = document.createRange();
nodeRange.selectNodeContents(node);
return nodeRange.compareBoundaryPoints(Range.END_TO_END, range) < 1 ?
NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT;
},
false
);
var charCount = 0;
while (treeWalker.nextNode()) {
charCount += treeWalker.currentNode.length;
}
if (range.startContainer.nodeType == 3) {
charCount += range.startOffset;
}
return charCount;
}
var el = document.getElementById("test");
var range = window.getSelection().getRangeAt(0);
document.title = getCharacterOffsetWithin(range, this);
}
};
function reset() {
for(var id in r)
r[id].reset;
console.log(CPU_ID + ": Reset...");
}
function step() {
clearTimeout(debug.hTimer);
debug.hTimer = setTimeout(step.bind(this), 1000 / core.clock);
if(!core.ready)
return;
var code = 0|0;
var scale = 0|0;
var $IP = r.pc.x;
this.r = r;
scale = !!core.is_active || debug.is_step ? debug.is_step ? 1 : core.scale : 0;
if((debug.is_step && !!core.is_active && !debug.halt[r.pc.x]))
core.is_active = false,
disassm();
if((!debug.is_step && !!core.is_active && debug.halt[r.pc.x]))
;// disassm();
while(!!debug.is_step || ((!debug.halt[r.pc.x] && !!core.is_active) && (scale -- > 0))) {
code = eval(core.actions[CPU_ID].action);
if(debug.is_step)
debug.is_step = false;
this.step.actions[code].bind(this).call(this);
// eval(core.actions[code].action);
}
if(debug.pointer != r.pc.x)
debug.pointer = r.pc.x,
disassm();
}
function command_set(ic, ib) {
var large = false,
color = "<span class='",
style,
datax = [],
cols = 7,
spaces = "\xA0".x(cols),
dump = [],
head = [],
foot = [],
code,
data = "_".x(4),
action,
command,
operand,
tmp;
for(var id in debug.data)
datax.push(id);
if(!isFinite(ib))
ib = 0;
datax = new RegExp(datax.join("|"));
for(code = 0; code < 256; ++ code) {
action = core.actions[code];
command = action.command + spaces;
operand = action.operand.replace(datax,
function(s) {
return (isFinite(ic) && (code == +ic) ? (data = ib.toHex(s.length)) : debug.data[s]);
}
);
tmp = operand.length - cols;
if(tmp > 0)
command = command.substr(0, cols - tmp) + operand,
operand = operand.substr(-cols);
tmp = (command + spaces).substr(0, cols) + (operand + spaces).substr(0, cols);
style = color + user.styles.zip[isFinite(ic) && (code == +ic) ? 1 : 0].replace(/\?/g, action.color) + "'>";
head.push(style + tmp.substr(0, cols) + "</span>");
foot.push(style + tmp.substr(cols) + "</span>");
if((code & 15) == 15)
dump.push("║" + ("<span" + (code > 15 ? " style=text-decoration:overline>" : ">") + (code >> 4).toHex(1) + "║" + head.join("│") + "</span>║<br />")
+ ("║ ║"+ foot.join("│") + "║").replace(/(IB|XX)/g, "<b style=color:cyan>$1</b>")),
head = [], foot = [];
}
for(code = 0; code < 16; ++ code)
head.push("╔═╗"),
foot.push("═".x(cols - 3) + "╝" + code.toHex(1) + "╚");
/*var sel = window.getSelection().getRangeAt(0); //get cursor position
sel = [[sel.startContainer,sel.startOffset],
[sel.endContainer,sel.endOffset]
]; //save cursor position (start and end);
/*Do whatever, let the user change selected element*/
user.actions.innerHTML = (isFinite(ic) ? ic.toHex(2) + " " + (data + "\xA0\xA0").substr(0, 4) : "_".x(4).substr(0, 5)) + head.join("\xA0".x(cols - 2)) + "<br />" +
"╔═╦" + foot.join("╤") + "╗<br />" +
dump.join(large ? "<br />╟─╫" + "─".x(cols).x(16, "┼") + "╢<br />" : "<br />") +
"<br />╚═╩" + "═".x(cols).x(16, "╧") + "╝";
/*var range = document.createRange(); //Creade range object. This is not IE compatible!
range.setStart(sel[0][0], sel[0][1]); //Load start from our variable
range.setEnd(sel[1][0], sel[1][1]); //Load end too
var s = window.getSelection();
s.removeAllRanges(); //I'm not sure this is necessary
s.addRange(range);//*/
}
function disassm() {
var i, j,
addr = (debug.pointer &= 0xFFFF), // active IP
ip = debug.address & 0xFFFF, lines = debug.lines, next = ip,
jp,
list = [], width,
regs = [],
ips = [],
lid, // label id
ic, ib = 0, ie, asm,
ich, icx,
active = addr.toHex(4) + " " + m[addr].toHex(2),
extend = "",
color,
expression = "",
rem = "", row,
cmm = "",
acc = "???", wait = false;
if(ip > addr)
ip = debug.address = (addr + 0xFFF0) & 0xFFFF;
for(var alias in r) {
regs.push(eval(r[alias].show));
}
lines -= regs.length;
for(i = 0, jp = ip; i < lines - 2 || jp < addr; ++ i) {
ips.push(jp);
ic = m[jp];
width = (core.actions[ic] ? core.actions[ic].width : 1);
jp = (jp + width) & 0xFFFF;
}
if(ips.length > lines - 2)
ip = debug.address = ips.pop();
var _ptr = 0, _bin =0, _cmd = 0, _opr = 0, _rem = 0;
var info = {
"@" : null,
"#" : null,
"$" : null,
"%" : null,
"." : null,
};
var code, data, act, width;
debug.string.replace(/@/g, function() { ++ _ptr; });
debug.string.replace(/#/g, function() { ++ _bin; });
debug.string.replace(/\$/g,function() { ++ _cmd; });
debug.string.replace(/%/g, function() { ++ _opr; });
debug.string.replace(/\./g,function() { ++ _rem; });
while(lines -- > 0) {
///////////////////////////////////////////////////////
info["@"] = ip.toHex(_ptr);
code = m[ip];
data = 0;
info["#"] = "";
act = core.actions[code];
width = act.width;
color = 0;
while(width --) {
color |= (ip + width) == addr ? 1 : 0;
color |= !!debug.halt[ip + width] ? 2 : 0;
color |= debug.choice == (ip + width) ? 4 : 0;
info["#"] = m[ip + width].toHex(2) + info["#"];
if(width)
data = (data << 8) + m[ip + width];
}
info["#"] += ".".x(16);
info["$"] = act.command + " ".x(_cmd);
info["%"] = act.operand.replace(/_+(\d)/g, function(s, n) { return data.toHex(-n * 2); }) + " ".x(_opr);
if(debug.labels[ip])
info["."] = debug.labels[ip] + " ".x(_rem);
else
if(debug.labels[data])
info["."] = debug.labels[data] + " ".x(_rem);
else
info["."] = act.remark + " ".x(_rem);
asm = debug.string.replace(/([@#$%.])/g, function(id) {
var s = info[id].charAt(0);
info[id] = info[id].substr(1);
return s;
});
if(color & 1)
command_set(code, data);
ip += act.width;
asm = "<span class='" + user.styles.zip[color].replace(/\?/g, act.color) + "'>" + asm + "</span>";
if(lines)
list.push(asm);
}
//command_set(ich, icx);
user.disassemblies.innerHTML = list.concat(regs).join("<br />");
watch.dirty = 1;
return;
var inter = active.split("|");
if(watch.active != "P")
watch.address.value = inter.shift().replace(/\s+$/, "");
else
inter.shift();
if(watch.active != "T")
watch.mnemonic.value = inter.shift().replace(/\s+/g, "\t").replace(/\s+(\(.*)?$/, "");
else
inter.shift();
if(watch.active != "R")
watch.remark.value = inter.shift().replace(/\s+$/, "");
if(expression != "")
document.getElementById("Eval").innerText = expression;
watch.dirty = true;
}
function assembly(listing, files) {
var text = listing.split(/\r?\n/),
line, part, regs, args, code, regz, regy, regw,
val_nnIB, val_sxIB, val_s_IB,
arg_nnIB,
instr, ins,
tmp,
dbg = true, // Debug mode
hlt = false, // Halting flag
usr = true, // User mode
arg, val,
rego, cnt,
regas, regaz, regay, regaw, regao,
ip, ipx,
labels = {}, // All labels
label, // Current label
labelz = {},
laps = 8,
lap = laps,
prc = 0,
ign = false,
prcs = text.length * laps,
title = document.title,
bytes,
file = {
name :"",
begin :65535,
end :0,
bin :[]
},
bin = !files ? m : file.bin;
do {
ip = -1; label = [], usr = true; ign = false;
for(line in text) {
++ prc;
if(files && !lap && ip >= 0 && file.begin > ip)
file.begin = ip;
if(ign)
continue;
part = text[line];
part = /([^:;"'`\s]*(?::| ?))?(?:\s)*([^\s;]*)(?:\s*)([^\s,;"'`]*)(?:[,\s]*)?([^\s,;"'`]*)(?:[,\s]*)?(?:(?:("(?:\\.|.)*?")|('(?:\\.|.)*?')|(`(?:\\.|.)*?`)|[^;"'`]*)*)*(\.*)/.exec(part);
if(part[1]) {
part[1] = part[1].replace(/[ :]$/, "");
tmp = part[1].replace(/:/g, "..").match(/(\.*)(.*)/);
label = label.slice(0, tmp[1].length).concat(tmp[2].split("."));
part[1] = label.join(".");
if(debug.labels[part[1]] != ip)
delete debug.labels[debug.labels[part[1].toUpperCase()]];
debug.labels[ip] = part[1],
debug.labels[part[1].toUpperCase()] = ip;
/*labelz = {};
cnt = 1 << 8;
do {
var idn = "";
for(var id in trace.labels)
if((id.length > idn.length) && (id.substr(-1) != " ") && !labelz[id])
idn = id;
else
continue;
//idn = (id.length > idn.length) && (id.substr(-1) != " ") && !labelz[id] ? id : idn;
if(idn != "")
labelz[idn] = trace.labels[idn];
} while((cnt --) && (idn != ""));*/
}
part[3] = part[3].replace(/([0-9][0-9A-F]*)h$/gi, "0x$1");
part[4] = part[4].replace(/([0-9][0-9A-F]*)h$/gi, "0x$1");
instr = part[2].toUpperCase();
if(instr.substr(-1) == "?" || instr.substr(-1) == "!") {
if((dbg || (instr.substr(-1) == "!")) && !lap)
debug.halt[ip] = true;
instr = instr.substr(0, instr.length - 1);
}
regs = [part[2], part[3]].join(" ").toUpperCase();
if(part[4])
regs += "," + part[4].toUpperCase();
/*if((regs = preset.alias[regs]) || (regs = preset.alias[instr])) {
regs = regs.split(" ");
for(var i in regs) {
if(typeof(regs[i]) == "string")
ram[ip ++] = parseInt(regs[i], 16);
}
continue;
}*/
part[3] = part[3].replace(/^(\.+)/, function(str, data) {
var data = data.length;
return label.slice(0, data).join(".") + ".";
});
part[4] = part[4].replace(/^(\.+)/, function(str, data) {
var data = data.length;
return label.slice(0, data).join(".") + ".";
});
regs = part[3].toUpperCase();
if(part[4])
regs += "," + part[4].toUpperCase();
args = [];
try{
regs = regs.replace(/(\.*)([A-Z_a-z][A-Z_a-z.0-9]*)/g, function(str, nest, tag) {
var tmp = debug.labels[label.slice(0, nest.length).concat(tag.split(".")).join(".").toUpperCase()];
//console.log(ip.Hex(4) + " " +str + "::" + nest + ":" + tag + "=" + tmp);
if(isFinite(tmp))
return Number(tmp).toHex(-4);
return nest + tag;
});
/*for(var i in labelz) {
regs = regs.replace(new RegExp("("+i.replace(/(\.)/g, "\\.")+")", "gi"), function(str, data) {
return "0x" + Number(labelz[i]).Hex(4);
});
}*/
}catch(e){}
rego = regs; ipx = false;
regs = regs.replace(/\$([+-](0x[0-9A-F]+|[0-9]+))/g, function(str, data) {
ipx = true;
data = (ip + parseInt(data) - 1) & 0xFFFF;
args.push(data);
return "0x" + data.toHex(4);
});
regs = regs.replace(/(0x[0-9A-F]+|[0-9]+)(\*|\/)(0x[0-9A-F]+|[0-9]+)+/g, function(str, x, op, y) {
return (op == "*" ? parseInt(x) * parseInt(y) : op == "/" && !!parseInt(y) ? parseInt(x) / parseInt(y) : 0x8000).toHex(-4);
});
regs = regs.replace(/(0x[0-9A-F]+|[0-9]+)([+-])(0x[0-9A-F]+|[0-9]+)+/g, function(str, x, op, y) {
return (op == "+" ? parseInt(x) + parseInt(y) : parseInt(x) - parseInt(y)).toHex(-4);
});
regs = regs.replace(/([-+](0x[0-9A-F]+|[0-9]+))/g, function(str, data) {
return "+" + (parseInt(data) + 256).toHex(-2);
});
ins = core.commands[instr];
code = -1;
bytes = 0;
if(ins && (regs in ins))
code = ins[regs];
else {
arg_nnIB = regs.replace(/(0x[0-9A-F]+)|([0-9]+)/gi, function(data) { // nnIB
var bin0 = parseInt(data);
var tag00= regs.replace(/(0x[0-9A-F]+)|([0-9]+)/gi, "_2");
var tag01= regs.replace(/(0x[0-9A-F]+)|([0-9]+)/gi, "_1");
var tag0 = regs.replace(/\+(0x[0-9A-F]+|[0-9]+)/, "+IB");
var bin1 = parseInt(data);
var tag1 = bin1.hi().toHex(2) + "IB";
var bin2 = parseInt(data) + (ipx ? -ip- 3 : -ip - 2);
var tag2 = "$+IB";
var bin3 = parseInt(data) + (ipx ? -ip- 4 : -ip - 3);
var bin3a = bin3 + (bin3 < -128 ? +(bin3 & 0x80) * 2 : bin3 >= 128 ? +(bin3 & 0x80) * 2 : 0);
var tag3 = "$+" + ((bin3a >> 8) & 7) + "IB";
if(ins) {
if((tag0 in ins) || (tag00 in ins) || (tag01 in ins))
return tag01 in ins ? (args.unshift(bin0), bytes = 1, "_1") : (args.unshift(bin0.lo(), bin0.hi()), bytes = 2, "_2");
if(tag1 in ins)
return args.push(bin1) ? tag1 : tag1;
if(bin2 >= -128 && bin2 < 128 && (tag2 in ins))
return args.push(bin2.lo()) ? tag2 : tag2;
if(((bin3 >= -1024 && bin3 < -128) || (bin3 >= 128 && bin3 <= 895)) && (tag3 in ins))
return args.push(bin3.lo()) ? tag3 : tag3;
if("IB" in ins)
return args.push(bin1) ? "IB" : "IB";
if(part[4] && (regs.split(",")[0] + ",IB") in ins)
return (code = ins[part[3] + ",IB"]) && args.push(bin1) ? "" : "";
if("" in ins)
return "";
}
args.push(bin1);
return "";
});
if(ins && (arg_nnIB in ins))
code = ins[arg_nnIB];
else
if(part[4] && ins && ([part[4].toUpperCase(), part[3].toUpperCase()].join(",") in ins))
code = ins[[part[4].toUpperCase(), part[3].toUpperCase()].join(",")];
else
if(part[4] && ins && (part[3].toUpperCase() in ins) && (part[4].toUpperCase() in ins))
code = ins[part[3].toUpperCase()] | (ins[part[4].toUpperCase()] << 16);
else
if(ins && (part[3].toUpperCase() in ins))
code = ins[part[3].toUpperCase()];
else
if(part[4] && ins && (regs.toUpperCase() in ins))
code = ins[regs.toUpperCase()];
else
if(ins && ((arg_nnIB = arg_nnIB.replace(/(\[[A-Z]{2})(\])/ig, "$1+IB$2")) in ins))
code = ins[arg_nnIB], args.unshift(0);
}
switch(instr) {
case ".END": ign = true; continue;
case "USER": usr = !!parseInt(regs); continue;
case "FILE": file.name = regs; continue;
case "DEBUG":dbg = !!parseInt(regs); continue;
case ".ORG": ip = args.shift(); continue;
case ".EQU": debug.labels[part[1].toUpperCase()] = args.shift(); continue;
case "BRK": if(files && dbg && !lap) debug.halt[ip] = !!parseInt(regs); continue;
case ".DB":
case ".TEXT":
if(part[5]) {
args = part[5].replace(/Ё/ig, "Е").replace(/[абвгдеёжзийклмнопрстуфхцчшщъыьэюя]/ig, function(str, ascii) {
var koi7ru = "ЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ",
data = koi7ru.indexOf(ascii);
if(data < 0)
return ascii;
return String.fromCharCode(ascii + 0x60);
}).split("");
args.shift(); args.pop();
while(args.length) {
tmp = args.shift();
code = tmp.charCodeAt(0);
if(tmp == "\\")
switch(tmp = args.shift()) {
case '0': code = 0x00; break;
case 't': code = 0x09; break;
case 'n': code = 0x0A; break;
case 'h': code = 0x0C; break;
case 'r': code = 0x0D; break;
case 'e': code = 0x1B; break;
case '_': code = 0x1F; break;
case '<': code = 0x08; break;
case '>': code = 0x18; break;
case '^': code = 0x19; break;
case 'v': code = 0x1A; break;
default: code = tmp.charCodeAt(0);
}
debug.text[ip] = true,
bin[ip ++] = code;
}
} else
while(args.length)
debug.text[ip] = true,
bin[ip ++] = args.shift();
continue;
case ".DW":
while(args.length)
tmp = args.shift(),
debug.text[ip] = true,
bin[ip ++] = tmp.lo(),
debug.text[ip] = true,
bin[ip ++] = tmp.hi();
continue;
}
hlt = !lap;
if(code >= 0) {
do {
if(!files)
debug.halt[ip] &= hlt;
debug.text[ip] = false,
bin[ip ++] = code & 0xFF;
while(bytes -- && args.length > 0)
debug.text[ip] = false,
debug.halt[ip] = false,
bin[ip ++] = args.shift();
} while((code & 0x8000) && (code >>= 16));
}
if(files && !lap && ip >= 0 && file.end < end)
file.end = ip;
}
} while(lap --);
document.title = title;
//disassm();
if(files)
return file;
}
// Initializing start / Начало инициализации
function create(pattern) {
var res, tmp, id;
var $D, commands, operands, actions, descriptions, width;
// Styling collection / Коллекция стилей
var stylex = /^\.([a-z]+)\t+(.+?)\t+/gm;
// Registers collection / Коллекция регистров
var regs = [],
regex = /^([a-z]+)(?:\:)(0x[0-9A-F]+|0[0-7]+|\d+)\t(.*)\t(.*)/gm;
// Operands collection / Коллекция набора операндов
var opers = [],
operex = /^([^\s-]{2,14})\t(.*)$/gm,
operexp = [],
operact = [],
operem = [];
// Decoder bits collection / Коллекция битов дешифратора
var pins = [],
pinex = /^([A-Z_?]+|[0-7_?]+)\?$/gm,
pinexp = [],
pinenum = [],
pinenus = [];
// Instructions set model / Коллекция командной модели
var models = [],
modelex = /^([0X1_]+)([A-Z_?])\t([^:\t]+)\t*([^:\t]*?)\t*:(.*?)(?:\t+(.*))?$/gm;
// Destroy the existing model / Уничтожаем существующую модель
core.ready = false;
delete core.actions;
delete core.commands;
delete debug.labels;
delete debug.data;
core.actions = {},
core.commands = {},
debug.labels = [],
debug.data = [],
r = {},
core.is_active = false;
// Let's parse the presentable pattern / Начинаем разбирать представленный шаблом
if(!(res = pattern.match(regex))) {
console.log(CPU_ID + ": Registers declaration needed...");
alert("Where the registers?");
throw 1;
}
// Build-up the registers / Создаём набор регистров
console.groupCollapsed(CPU_ID + ": Registers set");
res.forEach
(function(str) {
str.replace(regex,
function(str, id, data, name, present) {
if(id != "assm")
r[id] = new Register(parseInt(data)),
r[id].id = name;
tmp = [];
present.replace(/\`(.+?)\`|([^`]+?)/g,
function(str, action, text) {
if(text)
tmp.push('"' + text + '"');
else
tmp.push("(" + action + ")");
});
if(id == "assm")
debug.lines = parseInt(data),
debug.string = present;
else
r[id].show = tmp.join("+");//new Function("", "return " + tmp.join("+"));
});
console.log(str);
});
console.groupEnd();
if(!(res = pattern.match(pinex))) {
console.log(CPU_ID + ": Binaries declaration needed...");
alert("Where the pins?");
throw 2;
}
console.groupCollapsed(CPU_ID + ": Decoder bus naming");
pinex = [];
// Build-up the decoder / Разбираем битовые поля инструкций
res.forEach
(function(str) {
str.replace(/_|\?$/g, "").split("").reverse()
.forEach
(function(id, x, whole) {
if(isFinite(id))
pinenum.push("((x >> " + (whole.length - x - 1) + ") & 1) << " + id),
pinenus.push("x.substr(" + (-x - 1) + ", 1)");
else
if(id != "?")
(((pinexp[id]) || (pinexp[id] = [])) && pinexp[id]).push("(((x >> " + x + ") & 1) << " + pinexp[id].length + ")");
});
// Functional evaluating / Объявляем функциональное считывание
console.log(str);
});
console.groupEnd();
for(id in pinexp)
pinex.push("\\$" + id + "(\\[.*?\\])?"),
pins["$" + id] = new Function("x", "return " + pinexp[id].join(" | "));
if(pinenum.length)
pinenum = new Function("x", "return (" + pinenum.join(") + (") + ")"),
pinenus = new Function("x", "return " + pinenus.join(" + "));
else
pinenum = new Function("x", "return x"),
pinenus = new Function("x", "return x");
// Decoder bits collection / Собираем имена полей в выражение
pinex = new RegExp("(" + pinex.join("|") + ")", "g");
if(!(res = pattern.match(operex))) {
console.log(CPU_ID + ": Operands declaration needed...");
alert("Where the operands?");
throw 3;
}
console.groupCollapsed(CPU_ID + ": Operands set");
// Parse the operands / Разбираемся с операндами
res.forEach
(function(str) {
var str = str.split(/\t+/);
var val = str[1].split("/");
str[0].split("/")
.forEach
(function(id) {
console.log(id + '\t' + val[0]);
operexp.push(id);
opers[id] = val[0];
operact[id] = str[2];
operem[id] = str[3] || val[0];
if(val[1])
val.shift();
if(id.match(/^_+\d$/) && str[3])
debug.data[str[1]] = str[3];
});
console.log(str);
});
console.groupEnd();
// Collect the operands names into expression / Собираем имена операндов в выражение
//operex = new RegExp("(" + operexp.join("|")./*replace(/_+\d\||\|_+\d/g, "").*/replace(/(\$|\.)/g, "\\$1") + ")", "g");
operexp = new RegExp("(" + operexp.join("|").replace(/(\$|\.)/g, "\\$1") + ")", "g");
// Instructions presentable styles collection / Коллекция стилей презентабельности инструкций
for(id = 0; id < 8; ++ id)
user.styles.zip[id] = "";
if(!!(res = pattern.match(stylex))) {
console.groupCollapsed(CPU_ID + ": Instructions styling...");
res.forEach
(function(str) {
str.replace(stylex,
function(str, id, style) {
console.log("Bad style index " + id + " " + style);
if((id in user.styles) && isFinite(id = user.styles[id])) {
id = +id;
tmp = id < 3 ? 1 << id : 4;
while(id < 8)
user.styles.zip[id] = style,
id += tmp;
}
});
});
console.groupEnd();
} else
console.log(CPU_ID + ": Styling declaration advisable...");
// Build-up the fully command model / Разбираемся и строим полную командную модель
if(!(res = pattern.match(modelex))) {
console.log(CPU_ID + ": Common model declaration needed...");
alert("Where the model???");
throw 4;
}
this.r = r;
this.m = m;
if(step.actions)
delete step.actions;
this.step = step;
step.actions = [];
//this.step.r = r;
step();
console.groupCollapsed(CPU_ID + ": Building model");
res.forEach
(function(desc) {
console.groupCollapsed(desc);
desc.replace(modelex,
function(str, mask, group, command, operand, action, description) {
tmp = pinenus(mask.replace(/_/g, ""));
var
base = parseInt(tmp.replace(/X/g, "0"), 2), // 0XX1X0X1XX -> 0001000100
over = parseInt(tmp.replace(/X/g, "1"), 2), // 0XX1X0X1XX -> 0111101111
last = parseInt(tmp.replace(/./g, "1"), 2), // 0XX1X0X1XX -> 1111111111
mix = base ^ over ^ last; // 1001010100
// Running for whole combinates of undefined bits / Пробегаем по всем комбинациям неопределённых битов
for(var i = base; i <= over; i = (((i | mix) + 1) & ~mix) | base) {
$D = (i & -256) | pinenum(i);
if(core.actions[$D])
continue;
if(width = operand.match(/_(\d)/))
width = +width[1];
else
width = 0;
// Enumeration correct the pattern fields / Корректируем объявления шаблона с подстановкой конкретных числовых величин
commands = command .replace(pinex ,function($id) {return pins[$id]($D); });
operands = operand .replace(pinex ,function($id) {return pins[$id]($D); });
actions = action .replace(pinex ,function($id) {return pins[$id]($D); });
descriptions = description .replace(pinex ,function($id) {return pins[$id]($D); });
// Second lap correction / Проходимся второй раз с подстановкой перечисленных имён шаблона конкретными ссылками
commands = commands .replace(operexp,function($id) {return opers[$id.replace(/\[.*?\]/, "")]; });
operands = operands .replace(operexp,function($id) {return opers[$id.replace(/\[.*?\]/, "")]; });
actions = actions .replace(operexp,function($id) {return operact[$id.replace(/\[.*?\]/, "")]; });
descriptions = descriptions .replace(operexp,function($id) {return operem[$id.replace(/\[.*?\]/, "")]; });
Logging.push($D.toHex(2) + "#" + group + "|" + commands + "\t" + operands + "\t{" + actions + "}" + descriptions);
// Emulator step-in expression / Ищем ходовую строчку эмулятора
if(group == "?") {
if((command + " " + operand) == CPU_ID)
$D = CPU_ID;
else {
console.groupEnd(); console.groupEnd();
console.log(CPU_ID + ": Model version is incorrect...");
alert("Incorrect version...");
throw 5;
}
}
// Building the functional matrix for emulator and disassembler / Строим функциональную матрицу системы команд для эмуляции и дизассемблера
core.actions[$D] = {
color : group, // Instructions group colour / Цвет группы, к которой относится операция
width : width + 1, // Width of instruction / Ширина инструкции
command : commands, // Instruction mnemonic / Название команды
operand : operands, // Operands of instruction / Операнды команды
action : actions, // Emulation expression / Функциональное описание действия команды
remark : descriptions, // Description / Краткое описание инструкции
};
step.actions[$D] = new Function("", "with(this){return " + actions + "}");
if(group == "?")
break;
if(!core.commands[commands])
core.commands[commands] = [];
// Building the callback matrix for assembly / Строим обратную матрицу для ассемблера
operands.replace(/_+/g, "_").split("/")
.forEach(function(operands) {
if(!(operand in core.commands[commands]))
core.commands[commands][operands] = $D;
});
tmp = last + 1;
console.log(mask.replace(/[0X1]/g, function() {
return (tmp >>= 1) & $D ? "1" : "0";
}) + "\t" + width + ":" + commands + "\t" + operands + "\t:" + actions + "\t/*" + descriptions + "*/");
};
});
console.groupEnd();
});
console.groupEnd();
console.log(CPU_ID + ": Model is builded and ready...");
core.ready = true;
this.r = r;
clearTimeout(debug.hTimer);
debug.hTimer = setTimeout(step.bind(this), 1000 / core.clock);
}
return {
core : core,
assembly : assembly,
disassm : disassm,
reset : reset,
step : step,
debug : debug,
watch : watch,
create : create,
r : r,
// get r() {
// return r;
// },
set command_set(e) {