-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathgenerator.py
More file actions
1490 lines (1317 loc) · 51.6 KB
/
generator.py
File metadata and controls
1490 lines (1317 loc) · 51.6 KB
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
# Copyright (c) 2011 The Native Client Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import time
from memoize import Memoize
import objdump_check
import trie
def Byte(x):
return '%02x' % x
regs32 = ('eax', 'ecx', 'edx', 'ebx', 'esp', 'ebp', 'esi', 'edi')
regs16 = ('ax', 'cx', 'dx', 'bx', 'sp', 'bp', 'si', 'di')
regs8 = ('al', 'cl', 'dl', 'bl', 'ah', 'ch', 'dh', 'bh')
regs_x87 = ['st(%i)' % regnum for regnum in range(8)]
regs_mmx = ['mm%i' % regnum for regnum in range(8)]
regs_xmm = ['xmm%i' % regnum for regnum in range(8)]
regs_by_size = {
32: regs32,
16: regs16,
8: regs8,
'x87': regs_x87,
'mmx': regs_mmx,
'mmx32': regs_mmx,
'mmx64': regs_mmx,
'xmm': regs_xmm,
'xmm32': regs_xmm,
'xmm64': regs_xmm,
}
mem_sizes = {
64: 'QWORD PTR ',
32: 'DWORD PTR ',
16: 'WORD PTR ',
8: 'BYTE PTR ',
'mmx32': 'DWORD PTR ',
'mmx64': 'QWORD PTR ',
'xmm': 'XMMWORD PTR ',
'xmm32': 'DWORD PTR ',
'xmm64': 'QWORD PTR ',
'lea_mem': '',
80: 'TBYTE PTR ',
'other_x87_size': '',
'fxsave_size': '',
'lddqu_size': '', # Should be XMMWORD, but objdump omits this.
}
cond_codes = (
'o', 'no', 'b', 'ae', 'e', 'ne', 'be', 'a',
's', 'ns', 'p', 'np', 'l', 'ge', 'le', 'g',
)
form_map = {
'Ib': ('imm', 8),
'Gd': ('reg', 32),
'Ed': ('rm', 32),
'Md': ('mem', 32),
'Mq': ('mem', 64),
'Mdq': ('mem', 'xmm'),
'Pd': ('reg', 'mmx'),
'Pq': ('reg', 'mmx'),
'Vd': ('reg', 'xmm32'),
'Nq': ('reg2', 'mmx'),
'Qd': ('rm', 'mmx32'),
'Qq': ('rm', 'mmx64'),
}
form_position_map = {
'R': 'reg2',
'U': 'reg2', # %xmm
'V': 'reg', # %xmm
'W': 'rm', # %xmm
}
form_size_map = {
'dq': 'xmm', # XMMWORD
'pd': 'xmm', # XMMWORD
'ps': 'xmm', # XMMWORD
'sd': 'xmm64', # QWORD
'ss': 'xmm32', # DWORD
'q': 'xmm64', # QWORD
}
time0 = time.time()
prev_time = time0
def Log(msg):
global prev_time
now = time.time()
print '[+%.3fs] %.3fs: %s' % (now - prev_time, now - time0, str(msg))
prev_time = now
def AssertEq(x, y):
if x != y:
raise AssertionError('%r != %r' % (x, y))
def CatBits(values, sizes_in_bits):
result = 0
for value, size_in_bits in zip(values, sizes_in_bits):
assert isinstance(value, int)
assert 0 <= value
assert value < (1 << size_in_bits)
result = (result << size_in_bits) | value
return result
def CatBitsRev(value, sizes_in_bits):
parts = []
for size_in_bits in reversed(sizes_in_bits):
parts.insert(0, value & ((1 << size_in_bits) - 1))
value >>= size_in_bits
AssertEq(value, 0)
return tuple(parts)
@Memoize
def Sib(mod, rm_size, disp_size, disp_str, tail):
nodes = []
for index_reg, index_regname in enumerate(regs32):
if index_reg == 4:
# %esp is not accepted in the position '(reg, %esp)'.
# In this context, register 4 is %eiz (an always-zero value).
index_regname = 'eiz'
for scale in (0, 1, 2, 3):
# 5 is a special case and is not always %ebp.
# %esi/%edi are missing from headings in table in doc.
for base_reg, base_regname in enumerate(regs32):
if index_regname == 'eiz' and base_regname == 'esp' and scale == 0:
index_result = ''
else:
index_result = '%s*%s' % (index_regname, 1 << scale)
if base_reg == 5 and mod == 0:
base_regname = ''
extra = 'VALUE32'
extra2 = ['XX'] * 4
else:
extra = ''
extra2 = []
parts = [base_regname, index_result, extra, disp_str]
bytes = ([Byte((scale << 6) | (index_reg << 3) | base_reg)]
+ extra2
+ ['XX'] * disp_size)
nodes.append(TrieOfList(bytes,
DftLabel('rm_arg',
FormatMemAccess(rm_size, parts),
tail)))
return MergeMany(nodes, NoMerge)
def FormatMemAccess(size, parts):
parts = [part for part in parts if part != '']
return '%s[%s]' % (mem_sizes[size], '+'.join(parts))
@Memoize
def ModRMMem(rm_size, tail):
got = []
got.append((0, 5, TrieOfList(['XX'] * 4,
DftLabel('rm_arg',
'%sds:VALUE32' % mem_sizes[rm_size],
tail))))
for mod, dispsize, disp_str in ((0, 0, ''),
(1, 1, 'VALUE8'),
(2, 4, 'VALUE32')):
for reg2, regname2 in enumerate(regs32):
if reg2 == 4:
# %esp is not accepted in this position.
# 4 is a special value: adds SIB byte.
continue
if reg2 == 5 and mod == 0:
continue
got.append((mod, reg2,
TrieOfList(['XX'] * dispsize,
DftLabel('rm_arg',
FormatMemAccess(rm_size,
[regname2, disp_str]),
tail))))
reg2 = 4
got.append((mod, reg2, Sib(mod, rm_size, dispsize, disp_str, tail)))
return got
@Memoize
def ModRMReg(rm_size, tail):
got = []
mod = 3
for reg2, regname2 in enumerate(regs_by_size[rm_size]):
got.append((mod, reg2, DftLabel('rm_arg', regname2, tail)))
return got
def ModRM1(rm_size, rm_allow_reg, rm_allow_mem, tail):
if rm_allow_mem:
for result in ModRMMem(rm_size, tail):
yield result
if rm_allow_reg:
for result in ModRMReg(rm_size, tail):
yield result
def ModRM(reg_size, rm_size, rm_allow_reg, rm_allow_mem, tail):
for reg, regname in enumerate(regs_by_size[reg_size]):
for mod, reg2, node in ModRM1(rm_size, rm_allow_reg, rm_allow_mem, tail):
yield TrieOfList([Byte((mod << 6) | (reg << 3) | reg2)],
DftLabel('reg_arg', regname, node))
# Although the node this function returns won't get reused, the child
# nodes do get reused, which makes this worth memoizing.
@Memoize
def ModRMSingleArg(rm_size, rm_allow_reg, rm_allow_mem, opcode, tail):
nodes = []
for mod, reg2, node in ModRM1(rm_size, rm_allow_reg, rm_allow_mem, tail):
test_keep = (mod == 0 and reg2 == 0) or (mod == 3 and reg2 == 7)
nodes.append(TrieOfList([Byte((mod << 6) | (opcode << 3) | reg2)],
DftLabel('test_keep', test_keep, node)))
return MergeMany(nodes, NoMerge)
def TrieNode(children, accept=False):
node = trie.Trie()
node.children = children
node.accept = accept
return node
def TrieOfList(bytes, node):
for byte in reversed(bytes):
node = TrieNode({byte: node})
return node
class DftLabel(object):
def __init__(self, key, value, next):
self.key = key
self.value = value
self.next = next
def DftLabels(pairs, node):
for key, value in pairs:
node = DftLabel(key, value, node)
return node
# Assumes all the input nodes are immutable.
def MergeMany(nodes, merge_accept_types):
if len(nodes) == 1:
return list(nodes)[0]
if len(nodes) == 0:
return trie.EmptyNode
children = {}
accept_types = set()
if isinstance(nodes[0], DftLabel):
for node in nodes:
AssertEq(node.key, nodes[0].key)
AssertEq(node.value, nodes[0].value)
return DftLabel(nodes[0].key,
nodes[0].value,
MergeMany([node.next for node in nodes],
merge_accept_types))
by_key = {}
for node in nodes:
accept_types.add(node.accept)
for key, value in node.children.iteritems():
by_key.setdefault(key, []).append(value)
for key, subnodes in by_key.iteritems():
children[key] = MergeMany(subnodes, merge_accept_types)
if len(accept_types) == 1:
accept = list(accept_types)[0]
else:
accept = merge_accept_types(accept_types)
return trie.MakeInterned(children, accept)
def TrieSize(start_node, expand_wildcards):
@Memoize
def Rec(node):
if isinstance(node, DftLabel):
return Rec(node.next)
x = 0
if node.accept:
x += 1
if expand_wildcards and 'XX' in node.children:
return x + 256 * Rec(node.children['XX'])
else:
for child in node.children.itervalues():
x += Rec(child)
return x
return Rec(start_node)
def TrieNodeCount(root):
seen = set()
def Rec(node):
if node not in seen:
seen.add(node)
if isinstance(node, DftLabel):
Rec(node.next)
else:
for child in node.children.itervalues():
Rec(child)
Rec(root)
return len(seen)
def NoMerge(x):
raise Exception('Cannot merge %r' % x)
@Memoize
def ImmediateNode(immediate_size):
assert immediate_size in (0, 8, 16, 32), immediate_size
return TrieOfList(['XX'] * (immediate_size / 8), trie.AcceptNode)
@Memoize
def ModRMNode(reg_size, rm_size, rm_allow_reg, rm_allow_mem, tail):
nodes = list(ModRM(reg_size, rm_size, rm_allow_reg, rm_allow_mem, tail))
node = MergeMany(nodes, NoMerge)
return TrieNode(dict((key, DftLabel('test_keep', key == '00' or key == 'ff',
value))
for key, value in node.children.iteritems()))
# In cases where the instruction name and format depend on the
# contents of the ModRM byte, we need to apply the labels after the
# ModRM byte.
def PushLabels(labels, node):
return TrieNode(dict((key, DftLabels(labels, value))
for key, value in node.children.iteritems()))
def FlattenTrie(node, bytes=[], labels=[]):
if isinstance(node, DftLabel):
for result in FlattenTrie(node.next, bytes, labels + [node]):
yield result
else:
if node.accept:
label_map = dict((label.key, label.value) for label in labels)
yield (bytes, label_map)
for byte, next in sorted(node.children.iteritems()):
for result in FlattenTrie(next, bytes + [byte], labels):
yield result
# Convert from a transducer (with labels) to an acceptor (no labels).
# Strip all labels, converting relative_jump labels into accept states.
@Memoize
def ConvertToDfa(node, accept_type='normal_inst'):
if isinstance(node, DftLabel):
if node.key == 'relative_jump':
assert accept_type == 'normal_inst'
accept_type = 'jump_rel%i' % node.value
return ConvertToDfa(node.next, accept_type)
else:
assert node.accept in (True, False)
if node.accept:
accept = accept_type
else:
accept = False
return trie.MakeInterned(dict((key, ConvertToDfa(value, accept_type))
for key, value in node.children.iteritems()),
accept)
# Expand wildcard bytes. This has two benefits:
# * It allows wildcard edges to be merged with non-wildcards, in
# order to support the 'superinst_start' case.
# * It allows some nodes to be combined into one (combining explicit
# and implicit wildcards).
@Memoize
def ExpandWildcards(node):
if 'XX' in node.children:
assert len(node.children) == 1, node.children.keys()
dest = ExpandWildcards(node.children['XX'])
children = dict((Byte(byte), dest) for byte in xrange(256))
else:
children = dict((key, ExpandWildcards(value))
for key, value in node.children.iteritems())
return trie.MakeInterned(children, node.accept)
@Memoize
def FilterModRM(node):
if isinstance(node, DftLabel):
if node.key == 'test_keep' and not node.value:
return trie.EmptyNode
return DftLabel(node.key, node.value, FilterModRM(node.next))
else:
children = {}
for key, value in node.children.iteritems():
value = FilterModRM(value)
if value != trie.EmptyNode:
children[key] = value
return TrieNode(children, node.accept)
def FilterPrefix(bytes, node):
if len(bytes) == 0:
return node
elif isinstance(node, DftLabel):
return DftLabel(node.key, node.value, FilterPrefix(bytes, node.next))
else:
return TrieNode({bytes[0]: FilterPrefix(bytes[1:],
node.children[bytes[0]])},
node.accept)
def SubstSize(dec, size):
def Subst(value):
if value == 'imm8':
return ('imm', 8)
else:
return (value, size)
return map(Subst, dec)
# Instructions which can use the 'lock' prefix.
lock_whitelist = set([
'adc', 'add', 'and', 'btc', 'btr', 'bts',
'cmpxchg', 'cmpxchg8b', 'dec', 'inc',
'neg', 'not', 'or', 'sbb', 'sub',
'xadd', 'xchg', 'xor'])
def GetCoreRoot(nacl_mode, mem_access_only=False, lockable_only=False,
gs_access_only=False):
top_nodes = []
def Add(bytes, instr_name, args, modrm_opcode=None, data16=False):
if lockable_only and instr_name not in lock_whitelist:
return
bytes = bytes.split()
if nacl_mode:
# The following restrictions are enforced by the original x86-32
# NaCl validator, but might not be needed for safety.
# %gs is allowed only with a limited set of instructions.
if gs_access_only and (instr_name not in ('mov', 'cmp') or data16):
return
# Combining the data16 prefix with rep/repnz is not allowed.
if data16 and bytes[0] in ('f2', 'f3'):
return
# repnz is not allowed with movs/stos, though that may just be a
# mistake in the original validator.
if instr_name in ('repnz movs', 'repnz stos'):
return
# These instructions are not allowed in their 16-bit forms.
if data16 and instr_name in ('xadd', 'cmpxchg', 'shld', 'shrd',
'bsf', 'bsr', 'jmp'):
return
immediate_size = 0 # Size in bits
rm_size = None
rm_allow_reg = not mem_access_only
rm_allow_mem = True
reg_size = None
out_args = []
labels = []
mem_access = False
def SimpleArg(arg):
out_args.append((False, arg))
for kind, size in args:
if kind == 'imm':
# We can have multiple immediates. Needed for 'insertq'.
immediate_size += size
SimpleArg('VALUE%i' % size)
elif kind == 'rm':
assert rm_size is None
rm_size = size
out_args.append((True, kind))
mem_access = True
elif kind == 'lea_mem':
assert rm_size is None
# For 'lea', the size is really irrelevant.
rm_size = 'lea_mem'
rm_allow_reg = False
out_args.append((True, 'rm'))
elif kind == 'mem':
assert rm_size is None
rm_size = size
rm_allow_reg = False
out_args.append((True, 'rm'))
mem_access = True
elif kind == 'reg2':
# Register specified by the ModRM r/m field. This is like the
# 'rm' kind except that no memory access is allowed.
assert rm_size is None
rm_size = size
rm_allow_mem = False
out_args.append((True, 'rm'))
elif kind == 'reg':
# Register specified by the ModRM reg field.
assert reg_size is None
reg_size = size
out_args.append((True, kind))
elif kind == 'addr':
assert immediate_size == 0
immediate_size = 32
# We use mem_arg to allow 'ds:' to be replaced with 'gs:' later.
out_args.append((True, 'mem'))
labels.append(('mem_arg', 'ds:VALUE32'))
mem_access = True
elif kind == 'jump_dest':
assert immediate_size == 0
immediate_size = size
SimpleArg('JUMP_DEST')
labels.append(('relative_jump', size / 8))
elif kind == '*ax':
SimpleArg(regs_by_size[size][0])
elif kind in ('1', 'cl', 'st'):
SimpleArg(kind)
elif isinstance(kind, tuple) and len(kind) == 2 and kind[0] == 'fixreg':
SimpleArg(regs_by_size[size][kind[1]])
elif kind in ('es:[edi]', 'ds:[esi]'):
SimpleArg(mem_sizes[size] + kind)
# Although this accesses memory, we don't set 'mem_access = True'
# because this cannot be used with lock/gs prefixes.
else:
raise AssertionError('Unknown arg type: %s' % repr(kind))
if mem_access_only and not mem_access:
return
labels.append(('args', out_args))
labels.append(('instr_name', instr_name))
if rm_size is not None and reg_size is not None:
assert modrm_opcode is None
node = ModRMNode(reg_size, rm_size, rm_allow_reg, rm_allow_mem,
ImmediateNode(immediate_size))
if not (rm_allow_reg and rm_allow_mem):
node = PushLabels(labels, node)
labels = []
elif rm_size is not None and reg_size is None:
assert modrm_opcode is not None
node = ModRMSingleArg(rm_size, rm_allow_reg, rm_allow_mem,
modrm_opcode, ImmediateNode(immediate_size))
node = PushLabels(labels, node)
labels = []
elif rm_size is None and reg_size is None:
assert modrm_opcode is None
node = ImmediateNode(immediate_size)
else:
raise AssertionError('Unknown type')
node = TrieOfList(bytes, DftLabels(labels, node))
if data16:
node = TrieOfList(['66'], node)
top_nodes.append(node)
def Add3DNow(instrs):
# AMD 3DNow instructions are treated specially because the 3DNow
# opcode is placed at the end of the instruction, in the position
# where immediate values are normally placed.
if lockable_only:
return
if nacl_mode and gs_access_only:
return
node = TrieNode(dict((Byte(imm_opcode),
DftLabel('instr_name', name, trie.AcceptNode))
for imm_opcode, name in instrs))
rm_allow_reg = not mem_access_only
rm_allow_mem = True
node = DftLabel('args', [(True, 'reg'), (True, 'rm')],
ModRMNode('mmx', 'mmx64', rm_allow_reg, rm_allow_mem, node))
top_nodes.append(TrieOfList(['0f', '0f'], node))
def AddFPMem(bytes, instr_name, modrm_opcode, size=32):
Add(bytes, instr_name, [('mem', size)], modrm_opcode=modrm_opcode)
x87_formats = {
'st reg': [('st', 'x87'), ('reg2', 'x87')],
'reg st': [('reg2', 'x87'), ('st', 'x87')],
'reg': [('reg2', 'x87')],
}
def AddFPReg(bytes, instr_name, modrm_opcode, format='st reg'):
Add(bytes, instr_name, x87_formats[format], modrm_opcode=modrm_opcode)
def AddFPRM(bytes, instr_name, modrm_opcode, format='st reg', size=32):
AddFPMem(bytes, instr_name, modrm_opcode, size)
AddFPReg(bytes, instr_name, modrm_opcode, format)
def AddLW(opcode, instr, format, **kwargs):
Add(Byte(opcode), instr, SubstSize(format, 16), data16=True, **kwargs)
Add(Byte(opcode), instr, SubstSize(format, 32), **kwargs)
# Like AddLW(), but takes a string rather than an int.
# TODO: Unify these.
def AddLW2(opcode, instr, format, **kwargs):
Add(opcode, instr, SubstSize(format, 16), data16=True, **kwargs)
Add(opcode, instr, SubstSize(format, 32), **kwargs)
def AddPair(opcode, instr, format, **kwargs):
Add(Byte(opcode), instr, SubstSize(format, 8), **kwargs)
AddLW(opcode + 1, instr, format, **kwargs)
# Like AddPair(), but also takes a prefix.
def AddPair2(prefix, opcode, instr, format, **kwargs):
Add(prefix + ' ' + Byte(opcode), instr, SubstSize(format, 8), **kwargs)
AddLW2(prefix + ' ' + Byte(opcode + 1), instr, format, **kwargs)
def AddForm(bytes, instr_name, format, modrm_opcode=None):
def MapArg(arg):
if arg in form_map:
return form_map[arg]
else:
return (form_position_map[arg[0]], form_size_map[arg[1:]])
Add(bytes, instr_name, map(MapArg, format.split()),
modrm_opcode=modrm_opcode)
def AddSSEMMXPair(opcode, name):
AddForm(opcode, name, 'Pq Qq')
AddForm('66 ' + opcode, name, 'Vdq Wdq')
# Arithmetic instructions
for arith_opcode, instr in enumerate(['add', 'or', 'adc', 'sbb',
'and', 'sub', 'xor', 'cmp']):
for format_num, format in enumerate([['rm', 'reg'],
['reg', 'rm'],
['*ax', 'imm']]):
opcode = CatBits([arith_opcode, format_num, 0], [5, 2, 1])
AddPair(opcode, instr, format)
# Group 1
AddPair(0x80, instr, ['rm', 'imm'], modrm_opcode=arith_opcode)
# 0x82 is a hole in the table. We don't use AddPair(0x82) here
# because 0x80 and 0x82 would be equivalent (both 8-bit ops with
# imm8).
AddLW(0x83, instr, ['rm', 'imm8'], modrm_opcode=arith_opcode)
# Group 2: shift instructions
for instr, modrm_opcode in [('rol', 0),
('ror', 1),
('rcl', 2),
('rcr', 3),
('shl', 4),
('shr', 5),
# 6 is absent.
('sar', 7),
]:
AddPair(0xc0, instr, ['rm', 'imm8'], modrm_opcode=modrm_opcode)
AddPair(0xd0, instr, ['rm', '1'], modrm_opcode=modrm_opcode)
AddPair(0xd2, instr, ['rm', 'cl'], modrm_opcode=modrm_opcode)
for reg_num in range(8):
AddLW(0x40 + reg_num, 'inc', [('fixreg', reg_num)])
AddLW(0x48 + reg_num, 'dec', [('fixreg', reg_num)])
AddLW(0x50 + reg_num, 'push', [('fixreg', reg_num)])
AddLW(0x58 + reg_num, 'pop', [('fixreg', reg_num)])
# These both move %esp by 4 bytes.
AddLW(0x68, 'push', ['imm'])
Add('6a', 'push', [('imm', 8)])
# This moves %esp by 2 bytes.
Add('66 6a', 'data16 push', [('imm', 8)])
AddLW(0x69, 'imul', ['reg', 'rm', 'imm'])
AddLW(0x6b, 'imul', ['reg', 'rm', 'imm8'])
# Short (8-bit offset) conditional jumps
for cond_num, cond_name in enumerate(cond_codes):
Add(Byte(0x70 + cond_num), 'j' + cond_name, [('jump_dest', 8)])
AddPair(0x84, 'test', ['rm', 'reg'])
AddPair(0x86, 'xchg', ['rm', 'reg'])
AddLW(0x8d, 'lea', ['reg', 'lea_mem'])
# Group 1a just contains 'pop'.
AddLW(0x8f, 'pop', ['rm'], modrm_opcode=0)
# 'nop' is really 'xchg %eax, %eax'.
Add('90', 'nop', [])
# This might also be called 'data16 nop'.
Add('66 90', 'xchg ax, ax', [])
# 'pause' is really 'rep nop'.
Add('f3 90', 'pause', [])
for reg_num in range(8):
if reg_num != 0:
AddLW(0x90 + reg_num, 'xchg', [('fixreg', reg_num), '*ax'])
# Long nops
Add('0f 1f', 'nop', [('rm', 32)], modrm_opcode=0)
if not nacl_mode:
Add('0f 1f', 'nop', [('rm', 16)], modrm_opcode=0, data16=True)
# "Convert word to long". Sign-extends %ax into %eax.
Add('98', 'cwde', [])
# "Convert byte to word". Sign-extends %al into %ax.
Add('66 98', 'cbw', [])
# "Convert long to double long". Fills %edx with the top bit of %eax.
Add('99', 'cdq', [])
# "Convert word to double word". Fills %dx with the top bit of %ax.
Add('66 99', 'cwd', [])
# Note that assemblers and disassemblers treat 'fwait' as a prefix
# such that 'fwait; fnXXX' is a shorthand for 'fXXX'. (For example,
# 'fwait; fnstenv ARG' can be written as 'fstenv ARG'.) This might
# cause cross-check tests to fail if these instructions are placed
# together. Really, though, fwait is an instruction in its own
# right.
Add('9b', 'fwait', [])
Add('9e', 'sahf', [])
Add('9f', 'lahf', [])
Add('f4', 'hlt', [])
if not nacl_mode:
Add('27', 'daa', [])
Add('2f', 'das', [])
Add('37', 'aaa', [])
Add('3f', 'aas', [])
Add('60', 'pusha', [])
Add('61', 'popa', [])
Add('9c', 'pushf', [])
Add('9d', 'popf', [])
Add('c2', 'ret', [('imm', 16)])
Add('c3', 'ret', [])
Add('cc', 'int3', [])
Add('cd', 'int', [('imm', 8)])
Add('ce', 'into', [])
Add('cf', 'iret', [])
Add('fa', 'cli', [])
Add('fb', 'sti', [])
Add('c9', 'leave', [])
# 'data16 leave' is probably never useful, but we allow it for
# consistency with the original NaCl x86-32 validator.
# See http://code.google.com/p/nativeclient/issues/detail?id=2244
Add('66 c9', 'data16 leave', [])
Add('e8', 'call', [('jump_dest', 32)])
# String operations.
for prefix_bytes, prefix in [('', ''),
('f2', 'repnz '),
('f3', 'rep ')]:
AddPair2(prefix_bytes, 0xa4, prefix + 'movs', ['es:[edi]', 'ds:[esi]'])
AddPair2(prefix_bytes, 0xaa, prefix + 'stos', ['es:[edi]', '*ax'])
if not nacl_mode:
AddPair2(prefix_bytes, 0xac, prefix + 'lods', ['*ax', 'ds:[esi]'])
for prefix_bytes, prefix in [('', ''),
('f2', 'repnz '),
('f3', 'repz ')]:
AddPair2(prefix_bytes, 0xa6, prefix + 'cmps', ['ds:[esi]', 'es:[edi]'])
AddPair2(prefix_bytes, 0xae, prefix + 'scas', ['*ax', 'es:[edi]'])
AddPair(0xa8, 'test', ['*ax', 'imm'])
if not nacl_mode:
Add('e0', 'loopne', [('jump_dest', 8)])
Add('e1', 'loope', [('jump_dest', 8)])
Add('e2', 'loop', [('jump_dest', 8)])
Add('e3', 'jecxz', [('jump_dest', 8)])
AddLW(0xe9, 'jmp', ['jump_dest'])
Add('eb', 'jmp', [('jump_dest', 8)])
Add('f5', 'cmc', []) # Complement carry flag
Add('f8', 'clc', []) # Clear carry flag
Add('f9', 'stc', []) # Set carry flag
Add('fc', 'cld', []) # Clear direction flag
Add('fd', 'std', []) # Set direction flag
# Group 3
AddPair(0xf6, 'test', ['rm', 'imm'], modrm_opcode=0)
for instr, modrm_opcode in [('not', 2),
('neg', 3),
('mul', 4),
('imul', 5),
('div', 6),
('idiv', 7)]:
AddPair(0xf6, instr, ['rm'], modrm_opcode=modrm_opcode)
# Group 4/5
AddPair(0xfe, 'inc', ['rm'], modrm_opcode=0)
AddPair(0xfe, 'dec', ['rm'], modrm_opcode=1)
# Group 5
AddLW(0xff, 'push', ['rm'], modrm_opcode=6)
# NaCl disallows using these without a mask instruction first.
# Note that allowing jmp/call with a data16 prefix isn't very useful.
if not nacl_mode:
AddLW(0xff, 'call', ['rm'], modrm_opcode=2)
AddLW(0xff, 'jmp', ['rm'], modrm_opcode=4)
AddPair(0x88, 'mov', ['rm', 'reg'])
AddPair(0x8a, 'mov', ['reg', 'rm'])
AddPair(0xc6, 'mov', ['rm', 'imm'], modrm_opcode=0) # Group 11
AddPair(0xa0, 'mov', ['*ax', 'addr'])
AddPair(0xa2, 'mov', ['addr', '*ax'])
for reg_num in range(8):
Add(Byte(0xb0 + reg_num), 'mov', [(('fixreg', reg_num), 8), ('imm', 8)])
AddLW(0xb8 + reg_num, 'mov', [('fixreg', reg_num), 'imm'])
# Two-byte opcodes.
if not nacl_mode:
Add('0f 05', 'syscall', [])
Add('0f 06', 'clts', [])
Add('0f 07', 'sysret', [])
Add('0f 08', 'invd', [])
Add('0f 09', 'wbinvd', [])
Add('0f 0b', 'ud2', [])
Add('0f 01 d8', 'vmrun', [])
Add('0f 01 d9', 'vmmcall', [])
Add('0f 01 da', 'vmload', [])
Add('0f 01 db', 'vmsave', [])
Add('0f 01 dc', 'stgi', [])
Add('0f 01 dd', 'clgi', [])
Add('0f 01 de', 'skinit', [])
Add('0f 01 df', 'invlpga', [])
# 'swapgs' is 64-bit-only.
# Add('0f 01 f8', 'swapgs', [])
Add('0f 01 f9', 'rdtscp', [])
Add('0f 0e', 'femms', [])
# TODO: 0f 0f (3DNow)
# Group P: prefetches
# TODO: Other modrm_opcode values for prefetches might be allowed.
Add('0f 0d', 'prefetch', [('mem', 8)], modrm_opcode=0)
Add('0f 0d', 'prefetchw', [('mem', 8)], modrm_opcode=1)
Add('0f 10', 'movups', [('reg', 'xmm'), ('rm', 'xmm')])
Add('0f 11', 'movups', [('rm', 'xmm'), ('reg', 'xmm')])
Add('0f 12', 'movlps', [('reg', 'xmm'), ('mem', 64)])
Add('0f 12', 'movhlps', [('reg', 'xmm'), ('reg2', 'xmm')])
Add('0f 13', 'movlps', [('mem', 64), ('reg', 'xmm')])
Add('0f 14', 'unpcklps', [('reg', 'xmm'), ('rm', 'xmm')])
Add('0f 15', 'unpckhps', [('reg', 'xmm'), ('rm', 'xmm')])
Add('0f 16', 'movhps', [('reg', 'xmm'), ('mem', 64)])
Add('0f 16', 'movlhps', [('reg', 'xmm'), ('reg2', 'xmm')])
Add('0f 17', 'movhps', [('mem', 64), ('reg', 'xmm')])
# Group 16
Add('0f 18', 'prefetchnta', [('mem', 8)], modrm_opcode=0)
Add('0f 18', 'prefetcht0', [('mem', 8)], modrm_opcode=1)
Add('0f 18', 'prefetcht1', [('mem', 8)], modrm_opcode=2)
Add('0f 18', 'prefetcht2', [('mem', 8)], modrm_opcode=3)
Add('f3 0f 10', 'movss', [('reg', 'xmm'), ('rm', 'xmm32')])
Add('f3 0f 11', 'movss', [('rm', 'xmm32'), ('reg', 'xmm')])
Add('f3 0f 12', 'movsldup', [('reg', 'xmm'), ('rm', 'xmm')])
Add('f3 0f 16', 'movshdup', [('reg', 'xmm'), ('rm', 'xmm')])
Add('66 0f 10', 'movupd', [('reg', 'xmm'), ('rm', 'xmm')])
Add('66 0f 11', 'movupd', [('rm', 'xmm'), ('reg', 'xmm')])
Add('66 0f 12', 'movlpd', [('reg', 'xmm'), ('mem', 64)])
Add('66 0f 13', 'movlpd', [('mem', 64), ('reg', 'xmm')])
Add('66 0f 14', 'unpcklpd', [('reg', 'xmm'), ('rm', 'xmm')])
Add('66 0f 15', 'unpckhpd', [('reg', 'xmm'), ('rm', 'xmm')])
Add('66 0f 16', 'movhpd', [('reg', 'xmm'), ('mem', 64)])
Add('66 0f 17', 'movhpd', [('mem', 64), ('reg', 'xmm')])
Add('f2 0f 10', 'movsd', [('reg', 'xmm'), ('rm', 'xmm64')])
Add('f2 0f 11', 'movsd', [('rm', 'xmm64'), ('reg', 'xmm')])
Add('f2 0f 12', 'movddup', [('reg', 'xmm'), ('rm', 'xmm64')])
# Skip 0f 2x ('mov' on control registers)
AddForm('0f 28', 'movaps', 'Vps Wps')
AddForm('0f 29', 'movaps', 'Wps Vps')
AddForm('66 0f 28', 'movapd', 'Vpd Wpd')
AddForm('66 0f 29', 'movapd', 'Wpd Vpd')
AddForm('0f 2a', 'cvtpi2ps', 'Vps Qq')
AddForm('f3 0f 2a', 'cvtsi2ss', 'Vss Ed') # Ed/q
AddForm('66 0f 2a', 'cvtpi2pd', 'Vpd Qq')
AddForm('f2 0f 2a', 'cvtsi2sd', 'Vsd Ed') # Ed/q
AddForm('0f 2b', 'movntps', 'Mdq Vps')
AddForm('f3 0f 2b', 'movntss', 'Md Vss')
AddForm('66 0f 2b', 'movntpd', 'Mdq Vpd')
AddForm('f2 0f 2b', 'movntsd', 'Mq Vsd')
# binutils correctly disassembles 'cvttps2pi' with 'QWORD PTR', but
# the assembler wrongly only accepts 'XMMWORD PTR'.
# See http://sourceware.org/bugzilla/show_bug.cgi?id=13572
# The AMD manual has 'Pq Wps' for 'cvttps2pi', but 'W' is wrong (it
# should be an MMX register, not an XMM register) and 'ps' is wrong
# (it should be 64-bit, not 128-bit).
Add('0f 2c', 'FIXME cvttps2pi', [('reg', 'mmx'), ('rm', 'xmm64')])
AddForm('f3 0f 2c', 'cvttss2si', 'Gd Wss') # Gd/q
AddForm('66 0f 2c', 'cvttpd2pi', 'Pq Wpd')
AddForm('f2 0f 2c', 'cvttsd2si', 'Gd Wsd') # Gd/q
Add('0f 2d', 'cvtps2pi', [('reg', 'mmx'), ('rm', 'xmm64')])
AddForm('f3 0f 2d', 'cvtss2si', 'Gd Wss') # Gd/q
AddForm('66 0f 2d', 'cvtpd2pi', 'Pq Wpd')
AddForm('f2 0f 2d', 'cvtsd2si', 'Gd Wsd') # Gd/q
AddForm('0f 2e', 'ucomiss', 'Vss Wss')
AddForm('66 0f 2e', 'ucomisd', 'Vsd Wsd')
# The AMD manual uses 'Vps Wps', but 'ps' is not correct because
# this writes to a 32-bit memory location.
Add('0f 2f', 'comiss', [('reg', 'xmm'), ('rm', 'xmm32')])
AddForm('66 0f 2f', 'comisd', 'Vpd Wsd')
Add('0f 31', 'rdtsc', [])
if not nacl_mode:
Add('0f 30', 'wrmsr', [])
Add('0f 32', 'rdmsr', [])
Add('0f 33', 'rdpmc', [])
Add('0f 34', 'sysenter', [])
Add('0f 35', 'sysexit', [])
AddForm('0f 50', 'movmskps', 'Gd Ups')
AddForm('0f 51', 'sqrtps', 'Vps Wps')
AddForm('0f 52', 'rsqrtps', 'Vps Rps')
AddForm('0f 53', 'rcpps', 'Vps Wps')
AddForm('0f 54', 'andps', 'Vps Wps')
AddForm('0f 55', 'andnps', 'Vps Wps')
AddForm('0f 56', 'orps', 'Vps Wps')
AddForm('0f 57', 'xorps', 'Vps Wps')
AddForm('f3 0f 51', 'sqrtss', 'Vss Wss')
AddForm('f3 0f 52', 'rsqrtss', 'Vss Wss')
AddForm('f3 0f 53', 'rcpss', 'Vss Wss')
AddForm('66 0f 50', 'movmskpd', 'Gd Upd')
AddForm('66 0f 51', 'sqrtpd', 'Vpd Wpd')
AddForm('66 0f 54', 'andpd', 'Vpd Wpd')
AddForm('66 0f 55', 'andnpd', 'Vpd Wpd')
AddForm('66 0f 56', 'orpd', 'Vpd Wpd')
AddForm('66 0f 57', 'xorpd', 'Vpd Wpd')
AddForm('f2 0f 51', 'sqrtsd', 'Vsd Wsd')
for opcode, name in [('0f 58', 'add'),
('0f 59', 'mul'),
('0f 5c', 'sub'),
('0f 5d', 'min'),
('0f 5e', 'div'),
('0f 5f', 'max')]:
AddForm(opcode, name + 'ps', 'Vps Wps')
AddForm('f3 ' + opcode, name + 'ss', 'Vss Wss')
AddForm('66 ' + opcode, name + 'pd', 'Vpd Wpd')
AddForm('f2 ' + opcode, name + 'sd', 'Vsd Wsd')
# The AMD manual has 'Vpd Wps', but 'Wps' is not correct because the
# operand is 64-bit.
Add('0f 5a', 'cvtps2pd', [('reg', 'xmm'), ('rm', 'xmm64')])
AddForm('f3 0f 5a', 'cvtss2sd', 'Vsd Wss')
AddForm('66 0f 5a', 'cvtpd2ps', 'Vps Wpd')
AddForm('f2 0f 5a', 'cvtsd2ss', 'Vss Wsd')
AddForm('0f 5b', 'cvtdq2ps', 'Vps Wdq')
AddForm('f3 0f 5b', 'cvttps2dq', 'Vdq Wps')
AddForm('66 0f 5b', 'cvtps2dq', 'Vdq Wps')
# 'f3 0f 5b' is invalid.
# MMX
AddForm('0f 60', 'punpcklbw', 'Pq Qd')
AddForm('0f 61', 'punpcklwd', 'Pq Qd')
AddForm('0f 62', 'punpckldq', 'Pq Qd')
AddForm('0f 63', 'packsswb', 'Pq Qq')
AddForm('0f 64', 'pcmpgtb', 'Pq Qq')
AddForm('0f 65', 'pcmpgtw', 'Pq Qq')
AddForm('0f 66', 'pcmpgtd', 'Pq Qq')
AddForm('0f 67', 'packuswb', 'Pq Qq')
# SSE
# The AMD manual says 'Wq' rather than 'Wdq' for the next three, but
# it seems to be wrong.
AddForm('66 0f 60', 'punpcklbw', 'Vdq Wdq')
AddForm('66 0f 61', 'punpcklwd', 'Vdq Wdq')
AddForm('66 0f 62', 'punpckldq', 'Vdq Wdq')
AddForm('66 0f 63', 'packsswb', 'Vdq Wdq')
AddForm('66 0f 64', 'pcmpgtb', 'Vdq Wdq')
AddForm('66 0f 65', 'pcmpgtw', 'Vdq Wdq')
AddForm('66 0f 66', 'pcmpgtd', 'Vdq Wdq')
AddForm('66 0f 67', 'packuswb', 'Vdq Wdq')
AddSSEMMXPair('0f 68', 'punpckhbw')
AddSSEMMXPair('0f 69', 'punpckhwd')
AddSSEMMXPair('0f 6a', 'punpckhdq')
AddSSEMMXPair('0f 6b', 'packssdw')
# The AMD manual says 'Wq' rather than 'Wdq' for punpcklqdq and
# punpckhqdq, but it seems to be wrong.
AddForm('66 0f 6c', 'punpcklqdq', 'Vdq Wdq')
AddForm('66 0f 6d', 'punpckhqdq', 'Vdq Wdq')
AddForm('0f 6e', 'movd', 'Pq Ed') # Ed/q
AddForm('66 0f 6e', 'movd', 'Vdq Ed') # Ed/q
AddForm('0f 6f', 'movq', 'Pq Qq')
AddForm('f3 0f 6f', 'movdqu', 'Vdq Wdq')
AddForm('66 0f 6f', 'movdqa', 'Vdq Wdq')
# The AMD manual says 'Wq' rather than 'Wdq' for pshufhw and
# pshuflw, but it seems to be wrong.
AddForm('0f 70', 'pshufw', 'Pq Qq Ib')
AddForm('f3 0f 70', 'pshufhw', 'Vq Wdq Ib')
AddForm('66 0f 70', 'pshufd', 'Vdq Wdq Ib')
AddForm('f2 0f 70', 'pshuflw', 'Vq Wdq Ib')
AddForm('0f 74', 'pcmpeqb', 'Pq Qq')
AddForm('0f 75', 'pcmpeqw', 'Pq Qq')
AddForm('0f 76', 'pcmpeqd', 'Pq Qq')
AddForm('0f 77', 'emms', '')
AddForm('66 0f 74', 'pcmpeqb', 'Vdq Wdq')
AddForm('66 0f 75', 'pcmpeqw', 'Vdq Wdq')
AddForm('66 0f 76', 'pcmpeqd', 'Vdq Wdq')
AddForm('f2 0f 78', 'insertq', 'Vdq Uq Ib Ib')
AddForm('66 0f 79', 'extrq', 'Vdq Uq')
AddForm('f2 0f 79', 'insertq', 'Vdq Udq')
AddForm('66 0f 7c', 'haddpd', 'Vpd Wpd')
AddForm('f2 0f 7c', 'haddps', 'Vps Wps')
AddForm('66 0f 7d', 'hsubpd', 'Vpd Wpd')