This repository has been archived by the owner on Oct 15, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 46
/
x86.js
951 lines (780 loc) · 28.3 KB
/
x86.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
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
// [x86.js]
// X86/X64 instruction-set utilities that use `x86data.js`.
//
// [License]
// Public Domain.
(function($scope, $as) {
"use strict";
function FAIL(msg) { throw new Error("[X86] " + msg); }
// Import.
const base = $scope.base ? $scope.base : require("./base.js");
const x86data = $scope.x86data ? $scope.x86data : require("./x86data.js");
const hasOwn = Object.prototype.hasOwnProperty;
const dict = base.dict;
const NONE = base.NONE;
const Parsing = base.Parsing;
// Export.
const x86 = $scope[$as] = {};
// ============================================================================
// [CpuRegs]
// ============================================================================
// Build an object containing CPU registers as keys mapping them to type, kind, and index.
function buildCpuRegs(defs) {
const map = dict();
for (var type in defs) {
const def = defs[type];
const kind = def.kind;
const names = def.names;
if (def.any)
map[def.any] = { type: type, kind: kind, index: -1 };
for (var i = 0; i < names.length; i++) {
var name = names[i];
var m = /^([A-Za-z\(\)]+)(\d+)-(\d+)([A-Za-z\(\)]*)$/.exec(name);
if (m) {
var a = parseInt(m[2], 10);
var b = parseInt(m[3], 10);
for (var n = a; n <= b; n++) {
const index = m[1] + n + m[4];
map[index] = { type: type, kind: kind, index: index };
}
}
else {
map[name] = { type: type, kind: kind, index: i };
}
}
}
// HACK: In instruction manuals `r8` denotes low 8-bit register, however,
// that collides with `r8`, which is a 64-bit register. Since the result
// of this function is only used internally we patch it to be compatible
// with what Intel specifies.
map.r8.type = "r8";
return map;
}
const kCpuRegisters = buildCpuRegs(x86data.registers);
// ============================================================================
// [asmdb.x86.Utils]
// ============================================================================
const RegSize = Object.freeze({
"r8" : 8,
"r8hi": 8,
"r16" : 16,
"r32" : 32,
"r64" : 64,
"mm" : 64,
"xmm" : 128,
"ymm" : 256,
"zmm" : 512,
"tmm" : 512, // Maximum size (64 bytes).
"bnd" : 128,
"k" : 64,
"st" : 80
});
// X86/X64 utilities.
class Utils {
// Split the operand(s) string into individual operands as defined by the
// instruction database.
//
// NOTE: X86/X64 doesn't require anything else than separating the commas,
// this function is here for compatibility with other instruction sets.
static splitOperands(s) {
const array = s.split(",");
for (var i = 0; i < array.length; i++)
array[i] = array[i].trim();
return array;
}
// Get whether the string `s` describes a register operand.
static isRegOp(s) { return s && hasOwn.call(kCpuRegisters, s); }
// Get whether the string `s` describes a memory operand.
static isMemOp(s) { return s && /^(?:mem|mib|tmem|(?:m(?:off)?\d+(?:dec|bcd|fp|int)?)|(?:m16_\d+)|(?:vm\d+(?:x|y|z)))$/.test(s); }
// Get whether the string `s` describes an immediate operand.
static isImmOp(s) { return s && /^(?:1|i4|u4|ib|ub|iw|uw|id|ud|if|iq|uq|p16_16|p16_32)$/.test(s); }
// Get whether the string `s` describes a relative displacement (label).
static isRelOp(s) { return s && /^rel\d+$/.test(s); }
// Get a register type of a `s`, returns `null` if the register is unknown.
static regTypeOf(s) { return hasOwn.call(kCpuRegisters, s) ? kCpuRegisters[s].type : null; }
// Get a register kind of a `s`, returns `null` if the register is unknown.
static regKindOf(s) { return hasOwn.call(kCpuRegisters, s) ? kCpuRegisters[s].kind : null; }
// Get a register type of a `s`, returns `null` if the register is unknown and `-1`
// if the given string does only represent a register type, but not a specific reg.
static regIndexOf(s) { return hasOwn.call(kCpuRegisters, s) ? kCpuRegisters[s].index : null; }
static regSize(s) {
if (s in RegSize)
return RegSize[s];
const reg = kCpuRegisters[s];
if (reg && reg.type in RegSize)
return RegSize[reg.type];
return -1;
}
// Get size of an immediate `s` [in bits].
//
// Handles "ib", "iw", "id", "if", "iq", and also "/is4".
static immSize(s) {
switch (s) {
case "1" : return 8;
case "i4" :
case "u4" :
case "/is4" : return 4;
case "ib" :
case "ub" : return 8;
case "iw" :
case "uw" : return 16;
case "id" :
case "ud" : return 32;
case "iq" :
case "uq" : return 64;
case "p16_16": return 32;
case "if" :
case "p16_32": return 48;
default : return -1;
}
}
// Get size of a relative displacement [in bits].
static relSize(s) {
switch (s) {
case "rel8" : return 8;
case "rel16" : return 16;
case "rel32" : return 32;
default : return -1;
}
}
}
x86.Utils = Utils;
// ============================================================================
// [asmdb.x86.Operand]
// ============================================================================
// X86/X64 operand.
class Operand extends base.Operand {
constructor(data, defaultAccess) {
super(data);
this.memSeg = ""; // Segment specified with register that is used to perform a memory IO.
this.memOff = false; // Memory operand is an absolute offset (only a specific version of MOV).
this.memFar = false; // Memory is a far pointer (includes segment in first two bytes).
this.vsibReg = ""; // AVX VSIB register type (xmm/ymm/zmm).
this.vsibSize = -1; // AVX VSIB register size (32/64).
this.bcstSize = -1; // AVX-512 broadcast size.
const type = [];
var s = data;
// Handle RWX decorators prefix "[RWwXx]:".
const mAccess = /^([RWwXx])\:/.exec(s);
if (mAccess) {
this.setAccess(mAccess[1]);
s = s.substr(mAccess[0].length);
}
// Handle commutativity attribute.
if (Parsing.isCommutative(s)) {
this.commutative = true;
s = Parsing.clearCommutative(s);
}
// Handle AVX-512 broadcast possibility specified as "/bN" suffix.
const mBcst = /\/b(\d+)/.exec(s);
if (mBcst) {
this.bcstSize = parseInt(mBcst[1], 10);
// Remove the broadcast attribute from the definition; it's not needed anymore.
s = s.substr(0, mBcst.index) + s.substr(mBcst.index + mBcst[0].length);
}
// Handle <implicit> attribute.
if (Parsing.isImplicit(s)) {
this.implicit = true;
s = Parsing.clearImplicit(s);
}
// Support multiple operands separated by "/" (only used by r/m and i/u).
var ops = s.split("/");
var oArr = [];
for (var i = 0; i < ops.length; i++) {
var origOp = ops[i].trim();
var op = origOp;
// Handle range suffix [A] or [A:B]:
const mRange = /\[(\d+)\s*(?:\:\s*(\d+)\s*)?\]$/.exec(op);
if (mRange) {
var a = parseInt(mRange[1], 10);
var b = parseInt(mRange[2] || String(a), 10);
if (a < b)
FAIL(`Operand '${origOp}' contains invalid range '[${a}:${b}]'`)
this.rwxIndex = b;
this.rwxWidth = a - b + 1;
op = op.substr(0, op.length - mRange[0].length);
}
oArr.push(op);
// Handle a segment specification if this is an implicit register performing
// memory access.
if (/^(?:ds|es)\:/.test(op)) {
this.memSeg = op.substr(0, 2);
op = op.substr(3);
}
var regIndexRel = 0;
if (op.endsWith("+1") || op.endsWith("+2") || op.endsWith("+3")) {
regIndexRel = parseInt(op.substr(op.length - 1, 1));
op = op.substring(0, op.length - 2);
}
if (Utils.isRegOp(op)) {
this.reg = op;
this.regType = Utils.regTypeOf(op);
this.regIndexRel = regIndexRel;
type.push("reg");
continue;
}
if (Utils.isMemOp(op)) {
this.mem = op;
// Handle memory size.
const mOff = /^m(?:off)?(\d+)/.exec(op);
this.memSize = mOff ? parseInt(mOff[1], 10) : 0;
this.memOff = op.indexOf("moff") === 0;
const mSeg = /^m16_(\d+)/.exec(op);
if (mSeg) {
this.memFar = true;
this.memSize = parseInt(mSeg[1], 10) + 16;
}
// Handle vector addressing mode and size "vmXXr".
const mVM = /^vm(\d+)(x|y|z)$/.exec(op);
if (mVM) {
this.vsibReg = mVM[2] + "mm";
this.vsibSize = parseInt(mVM[1], 10);
}
type.push("mem");
continue;
}
if (Utils.isImmOp(op)) {
const size = Utils.immSize(op);
if (!this.imm)
this.imm = size;
else if (this.imm !== size)
FAIL(`Immediate size mismatch: ${this.imm} != ${size}`);
// Sign-extend / zero-extend.
const sign = op.startsWith("i") ? "signed" : "unsigned";
if (!this.immSign)
this.immSign = sign;
else if (this.immType !== sign)
this.immSign = "any";
if (op === "1") {
this.immValue = 1;
this.implicit = true;
}
if (type.indexOf("imm") !== -1)
type.push("imm");
continue;
}
if (Utils.isRelOp(op)) {
this.rel = Utils.relSize(op);
type.push("rel");
continue;
}
FAIL(`Operand '${origOp}' unhandled`);
}
// In case the data has been modified it's always better to use the stripped off
// version as we have already processed and stored all the possible decorators.
this.data = oArr.join("/");
this.type = type.join("/");
if (this.rwxIndex === -1) {
const opSize = this.isReg() ? this.regSize :
this.isMem() ? this.memSize : -1;
if (opSize !== -1) {
this.rwxIndex = 0;
this.rwxWidth = opSize;
}
}
if (!mAccess && this.isRegOrMem())
this.setAccess(defaultAccess);
}
get regSize() {
return Utils.regSize(this.reg);
}
setAccess(x) {
const u = x.toUpperCase();
this.zext = x === "W" || x === "X";
this.read = u === "R" || u === "X";
this.write = u === "W" || u === "X";
return this;
}
isFixedReg() { return this.reg && this.reg !== this.regType && this.reg !== "st(i)"; }
isFixedMem() { return this.memSeg && this.isFixedReg(); }
isPartialOp() {
const maybePartial = this.regType === "r8" ||
this.regType === "r8hi" ||
this.regType === "r16" ||
this.regType === "xmm";
return maybePartial && !this.zext;
}
toRegMem() {
if (this.reg && this.mem)
return this.reg + "/m";
else if (this.mem && (this.vsibReg || /fp$|int$/.test(this.mem)))
return this.mem;
else if (this.mem)
return "m";
else
return this.toString();
}
toString() { return this.data; }
}
x86.Operand = Operand;
// ============================================================================
// [asmdb.x86.Instruction]
// ============================================================================
// X86/X64 instruction.
class Instruction extends base.Instruction {
constructor(db, name, operands, encoding, opcode, metadata) {
super(db);
this.name = name;
this.privilege = "L3"; // Privilege level required to execute the instruction.
this.prefix = ""; // Prefix - "", "3DNOW", "EVEX", "VEX", "XOP".
this.opcodeHex = ""; // A single opcode byte as hexadecimal string "00-FF".
this.l = ""; // Opcode L field (nothing, 128, 256, 512).
this.w = ""; // Opcode W field.
this.pp = ""; // Opcode PP part.
this.mm = ""; // Opcode MM[MMM] part.
this._67h = false; // Instruction requires a size override prefix.
this.modR = ""; // Instruction specific payload in ModRM byte (R part), specified as "/0..7".
this.modRM = ""; // Instruction specific payload in ModRM byte (RM part), specified as another opcode byte.
this.ri = false; // Instruction opcode is combined with register, "XX+r" or "XX+i".
this.rel = 0; // Displacement ("cb", "cw", and "cd" parts).
this.fpu = false; // If the instruction is an FPU instruction.
this.fpuTop = 0; // FPU top index manipulation [-1, 0, 1, 2].
this.vsibReg = ""; // AVX VSIB register type (xmm/ymm/zmm).
this.vsibSize = -1; // AVX VSIB register size (32/64).
this.broadcast = false; // AVX-512 broadcast support.
this.bcstSize = -1; // AVX-512 broadcast size.
this.kmask = false; // AVX-512 merging {k}.
this.zmask = false; // AVX-512 zeroing {kz}, implies {k}.
this.er = false; // AVX-512 embedded rounding {er}, implies {sae}.
this.sae = false; // AVX-512 suppress all exceptions {sae} support.
this.tupleType = ""; // AVX-512 tuple-type.
this.elementSize = -1; // Instruction's element size.
this.consecutiveLead = 0; // Consecutive register leading N other registers.
this._assignOperands(operands);
this._assignEncoding(encoding);
this._assignOpcode(opcode);
this._assignMetadata(metadata);
this._updateOperandsInfo();
this._postProcess();
}
_assignOperands(s) {
if (!s) return;
// First remove all flags specified as {...}. We put them into `flags`
// map and mix with others. This seems to be the best we can do here.
for (;;) {
var a = s.indexOf("{");
var b = s.indexOf("}");
if (a === -1 || b === -1)
break;
// Get the `flag` and remove it from `s`.
this._assignAttribute(s.substring(a + 1, b), true);
s = s.substr(0, a) + s.substr(b + 1);
}
// Split into individual operands and push them to `operands`.
const arr = Utils.splitOperands(s);
for (var i = 0; i < arr.length; i++) {
const operand = new Operand(arr[i].trim(), i === 0 ? "X" : "R");
if (operand.mem == "tmem")
this.attributes.Tsib = true;
this.operands.push(operand);
}
}
_assignEncoding(s) {
// Parse 'TUPLE-TYPE' as defined by AVX-512.
var i = s.indexOf("-");
if (i !== -1) {
this.tupleType = s.substr(i + 1);
s = s.substr(0, i);
}
this.encoding = s;
}
_assignOpcode(s) {
this.opcodeString = s;
var parts = s.split(" ");
var prefix, comp;
var i;
if (/^(EVEX|VEX|XOP)\./.test(s)) {
// Parse VEX and EVEX encoded instruction.
prefix = parts[0].split(".");
for (i = 0; i < prefix.length; i++) {
comp = prefix[i];
// Ignore NP, it's just a placeholder.
if (comp == "NP")
continue;
// Process "EVEX", "VEX", and "XOP" prefixes.
if (/^(?:EVEX|VEX|XOP)$/.test(comp)) { this.prefix = comp; continue; }
// Process `L` field.
if (/^LIG$/ .test(comp)) { this.l = "LIG"; continue; }
if (/^128|L0|LZ$/.test(comp)) { this.l = "128"; continue; }
if (/^256|L1$/ .test(comp)) { this.l = "256"; continue; }
if (/^512$/ .test(comp)) { this.l = "512"; continue; }
// Process `PP` field - 66/F2/F3.
if (comp === "P0") { /* ignored, `P` is zero... */ continue; }
if (/^(?:66|F2|F3)$/.test(comp)) { this.pp = comp; continue; }
// Process `MM` field - 0F/0F3A/0F38/MAP5/MAP6/M8/M9.
if (/^(?:0F|0F3A|0F38|MAP5|MAP6|M08|M09|M0A)$/.test(comp)) { this.mm = comp; continue; }
// Process `W` field.
if (/^WIG|W0|W1$/.test(comp)) { this.w = comp; continue; }
// ERROR.
this.report(`'${this.opcodeString}' Unhandled component: ${comp}`);
}
for (i = 1; i < parts.length; i++) {
comp = parts[i];
// Parse opcode.
if (/^[0-9A-Fa-f]{2}$/.test(comp)) {
this.opcodeHex = comp.toUpperCase();
continue;
}
// Parse "/r" or "/0-7".
if (/^\/[r0-7]$/.test(comp)) {
this.modR = comp.charAt(1);
continue;
}
// Parse immediate byte, word, dword, or qword.
if (/^(?:ib|iw|id|iq|\/is4)$/.test(comp)) {
this.imm += Utils.immSize(comp);
continue;
}
this.report(`'${this.opcodeString}' Unhandled opcode component: ${comp}`);
}
}
else {
// Parse X86/X64 instruction (including legacy MMX/SSE/3DNOW instructions).
for (i = 0; i < parts.length; i++) {
comp = parts[i];
// Parse REX.W prefix.
if (comp === "REX.W") {
this.w = "W1";
continue;
}
// Parse `PP` prefixes.
if ((this.mm === "" && ((this.pp === "" && /^(?:66|F2|F3)$/.test(comp)) ||
(this.pp === "66" && /^(?:F2|F3)$/ .test(comp))))) {
this.pp += comp;
continue;
}
// Parse `MM` prefixes.
if ((this.mm === "" && comp === "0F") ||
(this.mm === "0F" && /^(?:01|3A|38)$/.test(comp))) {
this.mm += comp;
continue;
}
// Recognize "0F 0F /r XX" encoding.
if (this.mm === "0F" && comp === "0F") {
this.prefix = "3DNOW";
continue;
}
// Parse opcode byte.
if (/^[0-9A-F]{2}(?:\+[ri])?$/.test(comp)) {
// Parse "+r" or "+i" suffix.
if (comp.length > 2) {
this.ri = true;
comp = comp.substr(0, 2);
}
// FPU instructions are encoded as "PREFIX XX", where prefix is not the same
// as MM prefixes used everywhere else. AsmJit internally extends MM field in
// instruction tables to allow storing this prefix together with other "MM"
// prefixes, currently the unused indexes are used, but if X86 moves forward
// and starts using these we can simply use more bits in the opcode DWORD.
if (!this.pp && this.opcodeHex === "9B") {
this.pp = this.opcodeHex;
this.opcodeHex = comp;
continue;
}
if (!this.mm && (/^(?:D8|D9|DA|DB|DC|DD|DE|DF)$/.test(this.opcodeHex))) {
this.mm = this.opcodeHex;
this.opcodeHex = comp;
continue;
}
if (this.opcodeHex) {
if (this.opcodeHex === "67") {
this._67h = true;
}
else {
if (!this.modR && !this.modRM) {
const value = parseInt(comp, 16);
if ((value & 0xC0) == 0xC0) {
this.modR = String((value >> 3) & 0x7);
this.modRM = String((value >> 0) & 0x7);
}
else {
this.report(`'${this.opcodeString}' Unsupported secondary opcode (MOD/RM) '${comp}' value`);
}
}
else {
this.report(`'${this.opcodeString}' Multiple opcodes, have ${this.opcodeHex}, found ${comp}`);
}
}
}
this.opcodeHex = comp;
continue;
}
// Parse "/r" or "/0-7".
if (/^\/[r0-7]$/.test(comp) && !this.modR) {
this.modR = comp.charAt(1);
continue;
}
// Parse immediate byte, word, dword, fword, or qword.
if (/^(?:ib|iw|id|iq|if)$/.test(comp)) {
this.imm += Utils.immSize(comp);
continue;
}
// Parse displacement.
if (/^(?:cb|cw|cd)$/.test(comp) && !this.rel) {
this.rel = comp === "cb" ? 1 :
comp === "cw" ? 2 :
comp === "cd" ? 4 : -1;
continue;
}
// ERROR.
this.report(`'${this.opcodeString}' Unhandled opcode component ${comp}`);
}
}
// HACK: Fix instructions having opcode "01".
if (this.opcodeHex === "" && this.mm.indexOf("0F01") === this.mm.length - 4) {
this.opcodeHex = "01";
this.mm = this.mm.substr(0, this.mm.length - 2);
}
if (this.opcodeHex)
this.opcodeValue = parseInt(this.opcodeHex, 16);
if (!this.opcodeHex)
this.report(`Couldn't parse instruction's opcode '${this.opcodeString}'`);
}
_assignSpecificAttribute(name, value) {
const db = this.db;
// Basics.
if (name == "X86" || name === "X64" || name === "ANY") {
this.arch = name;
return true;
}
// AVX-512 flag followed by "-VL" suffix is a combination of two extensions.
if (/^AVX512\w+-VL$/.test(name) && db.extensions[name.substr(0, name.length - 3)]) {
const ext = name.substr(0, name.length - 3);
this.extensions[ext] = true;
this.extensions.AVX512_VL = true;
return true;
}
switch (name) {
case "FPU":
this.fpu = true;
return true;
case "kz":
this.zmask = true;
// fall: {kz} implies {k}.
case "k":
this.kmask = true;
return true;
case "er":
this.er = true;
// fall: {er} implies {sae}.
case "sae":
this.sae = true;
return true;
case "PRIVILEGE":
if (!/^L[0123]$/.test(value))
this.report(`${this.name}: Invalid privilege level '${value}'`);
this.privilege = value;
return true;
case "broadcast":
this.broadcast = true;
this.elementSize = value;
return true;
case "FPU_PUSH" :
this.fpu = true;
this.fpuTop = -1;
return true;
case "FPU_POP":
this.fpu = true;
this.fpuTop = Number(value);
return true;
case "FPU_TOP":
this.fpu = true;
if (value === "-1") { this.fpuTop =-1; return true; }
if (value === "+1") { this.fpuTop = 1; return true; }
break;
}
return false;
}
_updateOperandsInfo() {
super._updateOperandsInfo();
var consecutiveLead = null;
var consecutiveLastIndex = 0;
for (var i = 0; i < this.operands.length; i++) {
const op = this.operands[i];
// Propagate broadcast.
if (op.bcstSize > 0)
this._assignAttribute("broadcast", op.bcstSize);
// Propagate VSIB.
if (op.vsibReg) {
if (this.vsibReg) {
this.report("Only one operand can be a vector memory address (vmNNx)");
}
this.vsibReg = op.vsibReg;
this.vsibSize = op.vsibSize;
}
if (op.regIndexRel) {
if (i - op.regIndexRel < 0) {
this.report(`The consecutive register information is invalid, index of the lead (${i - op.regIndexRel}) is out of range`);
}
else {
const lead = this.operands[i - op.regIndexRel];
if (consecutiveLead && consecutiveLead != lead) {
this.report(`The consecutive register chain is invalid`);
}
else {
consecutiveLead = lead;
consecutiveLastIndex = Math.max(consecutiveLastIndex, op.regIndexRel);
}
}
}
}
if (consecutiveLead) {
consecutiveLead.consecutiveLeadCount = consecutiveLastIndex + 1;
}
}
// Validate the instruction's definition. Common mistakes can be checked and
// reported easily, however, if the mistake is just an invalid opcode or
// something else it's impossible to detect.
_postProcess() {
var isValid = true;
var immCount = this.immCount;
var m;
// Verify that the immediate operand/operands are specified in instruction
// encoding and opcode field. Basically if there is an "ix" in operands,
// the encoding should contain "I".
if (immCount > 0) {
if (immCount === 1 && this.operands[this.operands.length - 1].data === "1") {
// This must be one of rcl|rcr|rol|ror|sar|sal|shr. We won't validate
// these as these have "1" as implicit (encoded within opcode, not after).
}
else {
var immEncoding = "I".repeat(immCount);
// "I" or "II" should be part of the encoding.
if (this.encoding.indexOf(immEncoding) === -1) {
isValid = false;
this.report(`Immediate(s) [${immCount}] missing in encoding: ${this.encoding}`);
}
// Every immediate should have its imm byte ("ib", "iw", "id", or "iq") in the opcode data.
m = this.opcodeString.match(/(?:^|\s+)(ib|iw|id|if|iq|\/is4)/g);
if (!m || m.length !== immCount) {
isValid = false;
this.report(`Immediate(s) [${immCount}] not found in opcode: ${this.opcodeString}`);
}
}
}
// Verify that AVX/XOP or AVX-512 instruction always specifies L and W fields.
// FIXME: Not passing, because Intel Manual sometimes doesn't specify W.
/*
if (this.isAVX() && (this.l === "" || this.w === "")) {
this.report(`AVX instruction should specify L and W fields: L=${this.l} W=${this.w}`);
}
*/
// Verify that if the instruction uses the "VVVV" part of VEX/EVEX prefix,
// that it has "NDS/NDD/DDS" part of the "VVVV" definition specified, and
// that the definition matches the opcode encoding.
}
isAVX() { return this.isVEX() || this.isEVEX(); }
isVEX() { return this.prefix === "VEX" || this.prefix === "XOP"; }
isEVEX() { return this.prefix === "EVEX" }
getWValue() {
switch (this.w) {
case "W0": return 0;
case "W1": return 1;
}
return -1;
}
// Get signature of the instruction as "ARCH PREFIX ENCODING[:operands]" form.
get signature() {
var operands = this.operands;
var sign = this.arch;
if (this.prefix) {
sign += " " + this.prefix;
if (this.prefix !== "3DNOW") {
if (this.l === "L1")
sign += ".256";
else if (this.l === "256" || this.l === "512")
sign += `.${this.l}`;
else
sign += ".128";
if (this.w === "W1")
sign += ".W";
}
}
else if (this.w === "W1") {
sign += " REX.W";
}
sign += " " + this.encoding;
for (var i = 0; i < operands.length; i++) {
sign += (i === 0) ? ":" : ",";
var operand = operands[i];
if (operand.implicit)
sign += `[${operand.reg}]`;
else
sign += operand.toRegMem();
}
return sign;
}
get immCount() {
var ops = this.operands;
var n = 0;
for (var i = 0; i < ops.length; i++)
if (ops[i].isImm())
n++;
return n;
}
get modRValue() {
if (/^[0-7]$/.test(this.modR))
return parseInt(this.modR, 10);
else
return 0;
}
get modRMValue() {
if (/^[0-7]$/.test(this.modRM))
return parseInt(this.modRM, 10);
else
return 0;
}
}
x86.Instruction = Instruction;
// ============================================================================
// [asmdb.x86.ISA]
// ============================================================================
// X86/X64 instruction database - stores Instruction instances in a map and
// aggregates all instructions with the same name.
class ISA extends base.ISA {
constructor(args) {
super(args);
if (!args)
args = NONE;
if (args.builtins !== false)
this.addData(x86data);
this.addData(args);
}
_createInstruction(name, operands, encoding, opcode, metadata) {
return new Instruction(this, name, operands, encoding, opcode, metadata);
}
}
x86.ISA = ISA;
// ============================================================================
// [asmdb.x86.X86DataCheck]
// ============================================================================
class X86DataCheck {
static checkVexEvex(db) {
const map = db.instructionMap;
for (var name in map) {
const insts = map[name];
for (var i = 0; i < insts.length; i++) {
const instA = insts[i];
for (var j = i + 1; j < insts.length; j++) {
const instB = insts[j];
if (instA.operands.join("_") === instB.operands.join("_")) {
const vex = instA.prefix === "VEX" ? instA : instB.prefix === "VEX" ? instB : null;
const evex = instA.prefix === "EVEX" ? instA : instB.prefix === "EVEX" ? instB : null;
if (vex && evex && vex.opcodeHex === evex.opcodeHex) {
// NOTE: There are some false positives, they will be printed as well.
var ok = vex.w === evex.w && vex.l === evex.l;
if (!ok) {
console.log(`Instruction ${name} differs:`);
console.log(` ${vex.operands.join(" ")}: ${vex.opcodeString}`);
console.log(` ${evex.operands.join(" ")}: ${evex.opcodeString}`);
}
}
}
}
}
}
}
}
x86.X86DataCheck = X86DataCheck;
}).apply(this, typeof module === "object" && module && module.exports
? [module, "exports"] : [this.asmdb || (this.asmdb = {}), "x86"]);