Debian Codegraph @

opcodes/k1om.py

raw ◀ ▶
1 Debian patch touch this file
1 from __future__ import print_function
2 import xml.etree.ElementTree as ET
3
•4 from importlib.resources import files
5
6 class Instruction:
7 """Instruction is defined by its mnemonic name (in Intel-style assembly).
8
9 An instruction may have multiple forms, that mainly differ by operand types.
10
11 :ivar name: instruction name in Intel-style assembly (PeachPy, NASM and YASM assemblers).
12 :ivar summary: a summary description of the instruction name.
13 :ivar forms: a list of :class:`InstructionForm` objects representing the instruction forms.
14 """
15 def __init__(self, name):
16 self.name = name
17 self.summary = None
18 self.forms = []
19
20 def __str__(self):
21 """Returns string representation of the instruction and the number of instruction forms"""
22 return "%s (%d forms)" % (self.name, len(self.forms))
23
24 def __repr__(self):
25 return str(self)
26
27
28 class InstructionForm:
29 """Instruction form is a combination of mnemonic name and operand types.
30
31 An instruction form may have multiple possible encodings.
32
33 :ivar name: instruction name in PeachPy assembler.
34 :ivar gas_name: instruction form name in GNU assembler (gas).
35 :ivar cancelling_inputs: indicates that the instruction form has not dependency on the values of input operands
36 when they refer to the same register. E.g. **VPXORD zmm1, zmm0, zmm0** does not depend on *zmm0*.
37
38 Instruction forms with cancelling inputs have only two input operands, which have the same register type.
39
40 :ivar operands: a list of :class:`Operand` objects representing the instruction operands.
41 :ivar implicit_inputs: a set of register names that are implicitly read by this instruction.
42 :ivar implicit_outputs: a set of register names that are implicitly written by this instruction.
43 :ivar encodings: a list of :class:`Encoding` objects representing the possible encodings for this instruction.
44 """
45
46 def __init__(self, name):
47 self.name = name
48 self.gas_name = None
49 self.cancelling_inputs = None
50 self.operands = []
51 self.implicit_inputs = set()
52 self.implicit_outputs = set()
53 self.encodings = []
54
55 def __str__(self):
56 """Returns string representation of the instruction form and its operands in Intel-style assembly"""
57 if self.operands:
58 return self.name + " " + ", ".join(operand.type for operand in self.operands)
59 else:
60 return self.name
61
62 def __repr__(self):
63 return str(self)
64
65
66 class Operand:
67 """An explicit instruction operand.
68
69 :ivar type: the type of the instruction operand. Possible values are:
70
71 "1"
72 The constant value `1`.
73
74 "3"
75 The constant value `3`.
76
77 "al"
78 The al register.
79
80 "ax"
81 The ax register.
82
83 "eax"
84 The eax register.
85
86 "rax"
87 The rax register.
88
89 "cl"
90 The cl register.
91
92 "rel8"
93 An 8-bit signed offset relative to the address of instruction end.
94
95 "rel32"
96 A 32-bit signed offset relative to the address of instruction end.
97
98 "imm8"
99 An 8-bit immediate value.
100
101 "imm16"
102 A 16-bit immediate value.
103
104 "imm32"
105 A 32-bit immediate value.
106
107 "imm64"
108 A 64-bit immediate value.
109
110 "r8"
111 An 8-bit general-purpose register (al, bl, cl, dl, sil, dil, bpl, spl, r8b-r15b).
112
113 "r16"
114 A 16-bit general-purpose register (ax, bx, cx, dx, si, di, bp, sp, r8w-r15w).
115
116 "r32"
117 A 32-bit general-purpose register (eax, ebx, ecx, edx, esi, edi, ebp, esp, r8d-r15d).
118
119 "r64"
120 A 64-bit general-purpose register (rax, rbx, rcx, rdx, rsi, rdi, rbp, rsp, r8-r15).
121
122 "zmm"
123 A 512-bit ZMM SIMD register (zmm0-zmm31).
124
125 "zmm{k}"
126 A 512-bit ZMM SIMD register (zmm0-zmm31), optionally masked by a mask register (k1-k7).
127
128 "S(zmm)"
129 A 512-bit ZMM SIMD register (zmm0-zmm31), optionally with an elements swizzle ({cdab}, {badc}, \
130 {dacb}, {aaaa}, {bbbb}, {cccc}, {dddd}).
131
132 "Cf32(zmm)"
133 A 512-bit ZMM SIMD register (zmm0-zmm31), optionally with a single-precision store down-conversion \
134 ({float16}, {uint8}, {sint8}, {uint16}, {sint16}).
135
136 "Ci32(zmm)"
137 A 512-bit ZMM SIMD register (zmm0-zmm31), optionally with a 32-bit integer store down-conversion \
138 ({uint8}, {sint8}, {uint16}, {sint16}).
139
140 "k"
141 A mask register (k0-k7).
142
143 "k{k}"
144 A mask register (k0-k7), optionally masked by another mask register (k1-k7).
145
146 "m"
147 A memory operand of any size.
148
149 "m8"
150 An 8-bit memory operand.
151
152 "m16"
153 A 16-bit memory operand.
154
155 "m32"
156 A 32-bit memory operand.
157
158 "m64"
159 A 64-bit memory operand.
160
161 "m80"
162 An 80-bit memory operand.
163
164 "m128"
165 A 128-bit memory operand.
166
167 "m512"
168 A 512-bit memory operand.
169
170 "m512{k}"
171 A 512-bit memory operand, optionally masked by a mask register (k1-k7).
172
173 "BCf32(m512)"
174 A 512-bit memory operand, optionally with a single-precision memory broadcast/conversion ({1to16}, \
175 {4to16}, {float16}, {uint8}, {uint16}, {sint16})
176
177 "BCi32(m512)"
178 A 512-bit memory operand, optionally with a 32-bit integer memory broadcast/conversion ({1to16}, {4to16}, \
179 {uint8}, {sint8}, {uint16}, {sint16})
180
181 "B64(m512)"
182 A 512-bit memory operand, optionally with a 64-bit elements broadcast ({1to8}, {4to8})
183
184 "Cf32(m512)"
185 A 512-bit memory operand, optionally with a single-precision memory up-conversion ({float16}, \
186 {uint8}, {sint8}, {uint16}, {sint16})
187
188 "Ci32(m512)"
189 A 512-bit memory operand, optionally with a 32-bit integer memory up-conversion ({uint8}, {sint8}, \
190 {uint16}, {sint16})
191
192 "vm32z"
193 A vector of memory addresses using VSIB with 32-bit indices in ZMM register.
194
195 "vm32z{k}"
196 A vector of memory addresses using VSIB with 32-bit indices in ZMM register masked by a mask register \
197 (k1-k7).
198
199 "Cf32(vm32z)"
200 A vector of memory addresses using VSIB with 32-bit indices in ZMM register, optionally with a \
201 single-precision memory up-conversion ({float16}, {uint8}, {sint8}, {uint16}, {sint16}).
202
203 "Ci32(vm32z)"
204 A vector of memory addresses using VSIB with 32-bit indices in ZMM register, optionally with a 32-bit \
205 integer memory up-conversion ({uint8}, {sint8}, {uint16}, {sint16}).
206
207 "Cf32(vm32z){k}"
208 A vector of memory addresses using VSIB with 32-bit indices in ZMM register masked by a mask register, \
209 optionally with a single-precision memory up-conversion ({float16}, {uint8}, {sint8}, {uint16}, {sint16}).
210
211 "{sae}"
212 Suppress-all-exceptions modifier. This operand is optional and can be omitted.
213
214 "{er}"
215 Embedded rounding control. This operand is optional and can be omitted.
216
217 :ivar allow_conversion: for a memory operand with BCf32/BCi32 primitive indicates if memory conversion primitive \
218 can be used for the operand. For all other types of operands this variable is meaningless, and its value is None.
219 :ivar allow_1to16: for a memory operand with BCf32/BCi32 primitive indicates if {1to16} primitive can be used for \
220 the operand. For all other types of operands this variable is meaningless, and its value is None.
221
222 :ivar is_input: indicates if the instruction reads the variable specified by this operand.
223 :ivar is_output: indicates if the instruction writes the variable specified by this operand.
224 :ivar extended_size: for immediate operands the size of the value in bytes after size-extension.
225
226 The extended size affects which operand values can be encoded. E.g. a signed imm8 operand would normally \
227 encode values in the [-128, 127] range. But if it is extended to 4 bytes, it can also encode values in \
228 [2**32 - 128, 2**32 - 1] range.
229 """
230 def __init__(self, type):
231 self.type = type
232 self.allow_1to16 = None
233 self.allow_conversion = None
234 self.is_input = False
235 self.is_output = False
236 self.extended_size = None
237
238 if self.type.startswith("S") and self.is_memory:
239 self.allow_1to16 = True
240 self.allow_conversion = True
241
242 def __str__(self):
243 """Return string representation of the operand type and its read/write attributes"""
244 return {
245 (False, False): self.type,
246 (True, False): "[in] " + self.type,
247 (False, True): "[out] " + self.type,
248 (True, True): "[in/out] " + self.type
249 }[(self.is_input, self.is_output)]
250
251 def __repr__(self):
252 return str(self)
253
254 @property
255 def is_variable(self):
256 """Indicates whether this operand refers to a variable (i.e. specifies either a register or a memory location)"""
257 return self.is_input or self.is_output
258
259 @property
260 def is_register(self):
261 """Indicates whether this operand specifies a register"""
262 return self.type \
263 in ["al", "cl", "ax", "eax", "rax", "r8", "r16", "r32", "r64", "r8l", "r16l", "r32l",
264 "zmm", "zmm{k}", "S(zmm)", "Cf32(zmm)", "Ci32(zmm)", "k", "k{k}"]
265
266 @property
267 def is_memory(self):
268 """Indicates whether this operand specifies a memory location"""
269 return self.type \
270 in ["m", "m8", "m16", "m32", "m64", "m80", "m128",
271 "m512", "m512{k}", "BCf32(m512)", "BCi32(m512)", "B64(m512)", "Cf32(m512)", "Ci32(m512)",
272 "vm32z", "vm32z{k}", "Cf32(vm32z)", "Ci32(vm32z)", "Cf32(vm32z){k}"]
273
274 @property
275 def is_immediate(self):
276 """Indicates whether this operand is an immediate constant"""
277 return self.type in ["imm8", "imm16", "imm32", "imm64"]
278
279
280 class Encoding:
281 """Instruction encoding
282
283 :ivar components: a list of :class:`Prefix`, :class:`REX`, :class:`VEX`, :class:`Opcode`, :class:`ModRM`, \
284 :class:`RegisterByte`, :class:`Immediate`, :class:`DataOffset`, :class:`CodeOffset` objects that \
285 specify the components of encoded instruction
286 """
287
288 def __init__(self):
289 self.components = []
290
291
292 class Prefix:
293 """0x66/0xF2/0xF3 prefix
294
295 :ivar is_mandatory: indicates that the prefix is used not for its primary purpose, but for extending instruction \
296 opcode. Mandatory prefixes are common in SSE instructions. Non-mandatory prefix is usually 0x66 that modifies \
297 the instruction to operate on 16-bit operands.
298 :ivar byte: numerical representation of the prefix byte.
299 """
300
301 def __init__(self):
302 self.byte = None
303 self.is_mandatory = None
304
305
306 class REX:
307 """REX prefix.
308
309 Encoding may have only one REX prefix and if present, it immediately precedes the opcode.
310
311 :ivar is_mandatory: indicates whether the REX prefix must be encoded even if no extended registers are used.
312
313 REX is mandatory for most 64-bit instructions (encoded with REX.W = 1) and instructions that operate on the \
314 extended set of 8-bit registers (to indicate access to dil/sil/bpl/spl as opposed to ah/bh/ch/dh which use the \
315 same ModR/M).
316
317 :ivar W: the REX.W bit. Possible values are 0, 1, and None.
318
319 None indicates that the bit is ignored.
320
321 :ivar R: the REX.R bit. Possible values are 0, 1, None, or a reference to one of the instruction operands.
322
323 The value None indicates that this bit is ignored. \
324 If R is a reference to an instruction operand, the operand is of register type and REX.R bit specifies the \
325 high bit (bit 3) of the register number.
326
327 :ivar B: the REX.B bit. Possible values are 0, 1, None, or a reference to one of the instruction operands.
328
329 The value None indicates that this bit is ignored. \
330 If R is a reference to an instruction operand, the operand can be of register or memory type. If the operand \
331 is of register type, the REX.R bit specifies the high bit (bit 3) of the register number, and the REX.X bit is \
332 ignored. If the operand is of memory type, the REX.R bit specifies the high bit (bit 3) of the base register \
333 number, and the X instance variable refers to the same operand.
334
335 :ivar X: the REX.X bit. Possible values are 0, 1, None, or a reference to one of the instruction operands.
336
337 The value None indicates that this bit is ignored. \
338 If X is a reference to an instruction operand, the operand is of memory type and the REX.X bit specifies the \
339 high bit (bit 3) of the index register number, and the B instance variable refers to the same operand.
340 """
341
342 def __init__(self):
343 self.is_mandatory = None
344 self.W = None
345 self.R = None
346 self.X = None
347 self.B = None
348
349 def set_ignored(self, w=0, r=0, x=0, b=0):
350 """Sets values for ignored bits
351
352 :param int w: the value (0 or 1) to be assigned to REX.W bit if it is ignored.
353 :param int r: the value (0 or 1) to be assigned to REX.R bit if it is ignored.
354 :param int x: the value (0 or 1) to be assigned to REX.X bit if it is ignored.
355 :param int b: the value (0 or 1) to be assigned to REX.B bit if it is ignored.
356 """
357 assert w in [0, 1], "REX.W can be only 0 or 1"
358 assert r in [0, 1], "REX.R can be only 0 or 1"
359 assert x in [0, 1], "REX.X can be only 0 or 1"
360 assert b in [0, 1], "REX.B can be only 0 or 1"
361 if self.W is None:
362 self.W = w
363 if self.R is None:
364 self.R = r
365 if self.X is None:
366 self.X = x
367 if self.B is None:
368 self.B = b
369
370
371 class VEX:
372 """VEX prefix.
373
374 Encoding may have only one VEX prefix and if present, it immediately precedes the opcode, and no other prefix is \
375 allowed.
376
377 :ivar mmmmm: the VEX m-mmmm (implied leading opcode bytes) field. Possible values are:
378
379 0b00001
380 Implies 0x0F leading opcode byte.
381
382 0b00011
383 Implies 0x0F 0x3A leading opcode bytes.
384
385 Only VEX prefix with m-mmmm equal to 0b00001 could be encoded in two bytes.
386
387 :ivar pp: the VEX pp (implied legacy prefix) field. Possible values are:
388
389 0b00
390 No implied prefix.
391
392 0b01
393 Implied 0x66 prefix.
394
395 0b10
396 Implied 0xF3 prefix.
397
398 0b11
399 Implied 0xF2 prefix.
400
401 :ivar W: the VEX.W bit. Possible values are 0, 1, and None.
402
403 None indicates that the bit is ignored.
404
405 :ivar L: the VEX.L bit. Possible values are 0 or 1.
406
407 :ivar R: the VEX.R bit. Possible values are 0, 1, None, or a reference to one of the instruction operands.
408
409 The value None indicates that this bit is ignored. \
410 If R is a reference to an instruction operand, the operand is of register type and VEX.R bit specifies the \
411 high bit (bit 3) of the register number.
412
413 :ivar B: the VEX.B bit. Possible values are 0, 1, None, or a reference to one of the instruction operands.
414
415 The value None indicates that this bit is ignored. \
416 If R is a reference to an instruction operand, the operand can be of register or memory type. If the operand is \
417 of register type, the VEX.R bit specifies the high bit (bit 3) of the register number, and the VEX.X bit is \
418 ignored. If the operand is of memory type, the VEX.R bit specifies the high bit (bit 3) of the base register \
419 number, and the X instance variable refers to the same operand.
420
421 :ivar X: the VEX.X bit. Possible values are 0, 1, None, or a reference to one of the instruction operands.
422
423 The value None indicates that this bit is ignored. \
424 If X is a reference to an instruction operand, the operand is of memory type and the VEX.X bit specifies the \
425 high bit (bit 3) of the index register number, and the B instance variable refers to the same operand.
426
427 :ivar vvvv: the VEX vvvv field. Possible values are 0b0000 or a reference to one of the instruction operands.
428
429 The value 0b0000 indicates that this field is not used. \
430 If vvvv is a reference to an instruction operand, the operand is of register type and VEX.vvvv field specifies \
431 its number.
432 """
433
434 def __init__(self):
435 self.type = None
436 self.mmmmm = None
437 self.pp = None
438 self.W = None
439 self.L = None
440 self.R = None
441 self.X = None
442 self.B = None
443 self.vvvv = None
444
445 def set_ignored(self, w=0, r=0, x=0, b=0):
446 """Sets values for ignored bits
447
448 :param int w: the value (0 or 1) to be assigned to VEX.W bit if it is ignored.
449 :param int r: the value (0 or 1) to be assigned to VEX.R bit if it is ignored.
450 :param int x: the value (0 or 1) to be assigned to VEX.X bit if it is ignored.
451 :param int b: the value (0 or 1) to be assigned to VEX.B bit if it is ignored.
452 """
453 assert w in [0, 1], "VEX.W can be only 0 or 1"
454 assert r in [0, 1], "VEX.R can be only 0 or 1"
455 assert x in [0, 1], "VEX.X can be only 0 or 1"
456 assert b in [0, 1], "VEX.B can be only 0 or 1"
457 if self.W is None:
458 self.W = w
459 if self.R is None:
460 self.R = r
461 if self.X is None:
462 self.X = x
463 if self.B is None:
464 self.B = b
465
466
467 class MVEX:
468 """MVEX prefix.
469
470 Encoding may have only one MVEX prefix and if present, it immediately precedes the opcode, and no other prefix is \
471 allowed.
472
473 :ivar mmmm: the MVEX mmmm (compressed legacy escape) field. Identical to two low bits of VEX.m-mmmm field. \
474 Possible values are:
475
476 0b0001
477 Implies 0x0F leading opcode byte.
478
479 0b0010
480 Implies 0x0F 0x38 leading opcode bytes.
481
482 0b0011
483 Implies 0x0F 0x3A leading opcode bytes.
484
485 :ivar pp: the MVEX pp (compressed legacy prefix) field. Possible values are:
486
487 0b00
488 No implied prefix.
489
490 0b01
491 Implied 0x66 prefix.
492
493 0b10
494 Implied 0xF3 prefix.
495
496 0b11
497 Implied 0xF2 prefix.
498
499 :ivar W: the MVEX.W bit. Possible values are 0, 1, and None.
500
501 None indicates that the bit is ignored.
502
503 :ivar RR: the MVEX.R'R bits. Possible values are None, or a reference to an register-type instruction operand.
504
505 None indicates that the field is ignored. \
506 The R' bit specifies bit 4 of the register number and the R bit specifies bit 3 of the register number.
507
508 :ivar B: the MVEX.B bit. Possible values are None, or a reference to one of the instruction operands.
509
510 None indicates that this bit is ignored. \
511 If R is a reference to an instruction operand, the operand can be of register or memory type. If the operand is\
512 of register type, the MVEX.R bit specifies the high bit (bit 3) of the register number, and the MVEX.X bit is \
513 ignored. If the operand is of memory type, the MVEX.R bit specifies the high bit (bit 3) of the base register \
514 number, and the X instance variable refers to the same operand.
515
516 :ivar X: the MVEX.X bit. Possible values are None, or a reference to one of the instruction operands.
517
518 The value None indicates that this bit is ignored. \
519 If X is a reference to an instruction operand, the operand is of memory type and the MVEX.X bit specifies the \
520 high bit (bit 3) of the index register number, and the B instance variable refers to the same operand.
521
522 :ivar vvvv: the MVEX vvvv field. Possible values are 0b0000 or a reference to one of the instruction operands.
523
524 The value 0b0000 indicates that this field is not used. \
525 If vvvv is a reference to an instruction operand, the operand is of register type and MVEX.vvvv field \
526 specifies the register number.
527
528 :ivar V: the MVEX V field. Possible values are 0, or a reference to one of the instruction operands.
529
530 The value 0 indicates that this field is not used (MVEX.vvvv is not used or encodes a general-purpose register).
531
532 :ivar SSS: the MVEX SSS (swizzle/broadcast/up-convert/down-convert) field. Possible values are 0, or a reference \
533 to one of the instruction operands.
534
535 The value 0 indicates that this field is not used. \
536 If SSS is a reference to an instruction operand, the operand type either includes a swizzle, broadcast, or \
537 conversion primitive, or the operand type is {er} (static rounding control), or the operand type is {sae}. \
538 If SSS is a reference to a memory/register operand, it encodes the primitive applied to the operand. \
539 If SSS is a reference to a static rounding control operand, it the high bit of MVEX.SSS encodes \
540 suppress-all-exceptions mode (1 = enabled, 0 = disabled) and the two low bits encode rounding mode (round \
541 to nearest even = 0b00, round down = 0b01, round up = 0b10, round toward zero = 0b11) \
542 If SSS is a reference to a suppress-all-exceptions operand, the high bit of MVEX.SSS encodes the \
543 suppress-all-exceptions mode (1 = enabled, 0 = disabled) and the two low bits are ignored.
544
545 :ivar aaa: the MVEX aaa (embedded opmask register specifier) field. Possible values are 0 or a reference to one of \
546 the instruction operands.
547
548 The value 0 indicates that this field is not used. \
549 If aaa is a reference to an instruction operand, the operand supports register mask, and MVEX.aaa encodes the \
550 mask register.
551
552 :ivar E: the MVEX E (eviction hint/MVEX.SSS override) bit. Possible values are 0, 1, or a reference to an \
553 instruction operand.
554
555 The value 0 indicates that MVEX.SSS field specifies swizzle primitive for a register operand. \
556 The value 1 indicates that MVEX.SSS field specifies static rounding mode and/or suppress-all-exceptions mode \
557 for the instruction. \
558 If E is a reference to an instruction operand, the operand is of memory type, and MVEX.E encodes whether \
559 eviction hint applies to the operand (1 = eviction hint set, 0 = eviction hint not set).
560
561 :ivar disp8xN: the N value used for encoding compressed 8-bit displacement of memory operands when no broadcast or \
562 conversion is specified. Possible values are powers of 2 in [4, 64] range or None.
563
564 None indicates that this instruction form does not use displacement (the form has no memory operands).
565
566 When broadcast or conversion is specified, N is decreased by the following factors:
567
568 {1to16}
569 N is decreased by 16
570
571 {4to16}
572 N is decreased by 4
573
574 {1to8}
575 N is decreased by 8
576
577 {4to8}
578 N is decreased by 2
579
580 {float16}
581 N is decreased by 2
582
583 {uint16}
584 N is decreased by 2
585
586 {sint16}
587 N is decreased by 2
588
589 {uint8}
590 N is decreased by 4
591
592 {sint8}
593 N is decreased by 4
594 """
595
596 def __init__(self):
597 self.mmmm = None
598 self.pp = None
599 self.W = None
600 self.LL = None
601 self.RR = None
602 self.B = None
603 self.X = None
604 self.vvvv = None
605 self.V = None
606 self.SSS = None
607 self.aaa = None
608
609 def set_ignored(self, w=0, rr=0, x=0, z=0):
610 """Sets values for ignored bits
611
612 :param int w: the value (0 or 1) to be assigned to MVEX.W bit if it is ignored.
613 :param int rr: the value (0b00, 0b01, 0b10, or 0b11) to be assigned to MVEX.R'R field if it is ignored.
614 :param int x: the value (0 or 1) to be assigned to MVEX.X bit if it is ignored.
615 :param int z: the value (0 or 1) to be assigned to MVEX.z bit if it is ignored.
616 """
617 assert w in [0, 1], "MVEX.W can be only 0 or 1"
618 assert rr in [0b00, 0b01, 0b10, 0b11], "MVEX.R'R must be a 2-bit integer value"
619 assert x in [0, 1], "MVEX.X can be only 0 or 1"
620 assert z in [0, 1], "MVEX.z can be only 0 or 1"
621 if self.W is None:
622 self.W = w
623 if self.RR is None:
624 self.RR = rr
625 if self.X is None:
626 self.X = x
627 if self.z is None:
628 self.z = z
629
630
631 class Opcode:
632 """Operation code
633
634 Encoding may include more than one opcode. Opcodes do not necessarily go in sequence.
635
636 :ivar byte: operation code as a byte integer (0 <= `byte` <= 255)
637 :ivar addend: None or a reference to an instruction operand.
638
639 If addend is a reference to an instruction operand, the operand is of register type and the three lowest bits \
640 of its number must be ORed with `byte` to produce the final opcode value.
641 """
642 def __init__(self, byte):
643 self.byte = byte
644 self.addend = None
645
646 def __str__(self):
647 return "0x%02X".format(self.byte)
648
649 def __repr__(self):
650 return str(self)
651
652
653 class ModRM:
654 """Mod R/M byte that can encode a register operand, a memory operand, or provide an opcode extension.
655
656 If memory operand requires SIB byte, the SIB byte immediately follows the Mod R/M byte in instruction encoding.
657
658 :ivar mode: addressing mode. Possible values are 0b11 or a reference to an instruction operand.
659
660 If mode value is 0b11, the Mod R/M encodes two register operands or a register operand and an opcode extension.
661
662 If mode is a reference to an instruction operand, the operand has memory type and its addressing mode must be \
663 coded instruction the Mod R/M mode field.
664
665 :ivar rm: a register or memory operand. Must be a reference to an instruction operand.
666
667 If rm is a reference to a operand, rm specifies bits 0-2 of the register number. If the operand is of memory \
668 type, rm specifies bits 0-2 of the base register number unless a SIB byte is used.
669
670 :ivar reg: a register or an opcode extension. Possible values are an int value, or a reference to an instruction \
671 operand.
672
673 If reg is an int value, this value extends the opcode and must be directly coded in the reg field.
674
675 If reg is a reference to an instruction operand, the operand is of register type, and the reg field specifies \
676 bits 0-2 of the register number.
677 """
678 def __init__(self):
679 self.mode = None
680 self.rm = None
681 self.reg = None
682
683 def set_ignored(self, mode=0b11, rm=0):
684 """Sets values for ignored fields
685
686 :param int mode: the value (0b00, 0b01, 0b10, or 0b11) to be assigned to Mod R/M mode field if it is ignored.
687 :param int rm: the value (an integer, 0 <= rm <= 7) to be assigned to Mod R/M rm field if it is ignored.
688 """
689 assert mode in [0b00, 0b01, 0b10, 0b11], "Mod R/M mode must be 0b00, 0b01, 0b10 or 0b11"
690 assert rm in [0, 1, 2, 3, 4, 5, 6, 7], "Mod R/M rm must be an integer in 0-7 range"
691 if self.mode is None:
692 self.mode = mode
693 if self.rm is None:
694 self.rm = rm
695
696
697 class Immediate:
698 """Immediate constant embedded into instruction encoding.
699
700 :ivar size: size of the constant in bytes. Possible values are 1, 2, 4, or 8.
701 :ivar value: value of the constant. Can be an int value or a reference to an instruction operand.
702
703 If value is a reference to an instruction operand, the operand has "imm" type of the matching size.
704 """
705 def __init__(self):
706 self.size = None
707 self.value = None
708
709
710 class RegisterByte:
711 def __init__(self):
712 self.register = None
713 self.payload = None
714
715
716 class CodeOffset:
717 """Relative code offset embedded into instruction encoding.
718
719 Offset is relative to the end of the instruction.
720
721 :ivar size: size of the offset in bytes. Possible values are 1 or 4.
722 :ivar value: value of the offset. Must be a reference to an instruction operand.
723
724 The instruction operand has "rel" type of the matching size.
725 """
726 def __init__(self):
727 self.size = None
728 self.value = None
729
730
731 class DataOffset:
732 """Absolute data offset embedded into instruction encoding.
733
734 Only MOV instruction has forms that use direct data offset.
735
736 :ivar size: size of the offset in bytes. Possible values are 4 or 8.
737 :ivar value: value of the offset. Must be a reference to an instruction operand.
738
739 The instruction operand has "moffs" type of the matching size.
740 """
741 def __init__(self):
742 self.size = None
743 self.value = None
744
745
746 def _parse_boolean(xml_boolean):
747 """Converts strings "true" and "false" from XML files to Python bool"""
748
749 if xml_boolean is not None:
750 assert xml_boolean in ["true", "false"], \
751 "The boolean string must be \"true\" or \"false\""
752 return {"true": True, "false": False}[xml_boolean]
753
754
755 def _parse_value(value, operands, base=None):
756 """Parses string, which can be a number, a reference to an operand, or None
757
758 :param value: the string to parse.
759 :param operands: the list of operands. If value starts with "#", it is interpreted as a reference to an operand.
760 :param base: the base of the integer representation of value.
761 """
762 if value is not None:
763 if value.startswith("#"):
764 return operands[int(value[1:])]
765 else:
766 assert base is not None
767 return int(value, base)
768
769
770 def read_instruction_set(filename=None):
771 """Reads instruction set data from an XML file and returns a list of :class:`Instruction` objects
772
773 :param filename: path to an XML file with instruction set data
774 """
775 if filename is None:
•776 data = (files("opcodes").joinpath("k1om.xml")).open('rb')
777 xml_tree = ET.parse(data)
778 else:
779 xml_tree = ET.parse(filename)
780
781 xml_instruction_set = xml_tree.getroot()
782 assert xml_instruction_set.tag == "InstructionSet"
783 assert xml_instruction_set.attrib["name"] == "k1om"
784
785 instruction_set = []
786 for xml_instruction in xml_instruction_set:
787 assert xml_instruction.tag == "Instruction"
788 instruction = Instruction(xml_instruction.attrib["name"])
789 instruction.summary = xml_instruction.attrib["summary"]
790 for xml_instruction_form in xml_instruction:
791 instruction_form = InstructionForm(instruction.name)
792 instruction_form.gas_name = xml_instruction_form.attrib["gas-name"]
793 instruction_form.cancelling_inputs = \
794 _parse_boolean(xml_instruction_form.attrib.get("cancelling-inputs", "false"))
795 for xml_operand in xml_instruction_form.findall("Operand"):
796 operand = Operand(xml_operand.attrib["type"])
797 allow_conversion = _parse_boolean(xml_operand.attrib.get("allow-conversion"))
798 if allow_conversion is not None:
799 operand.allow_conversion = allow_conversion
800 allow_1to16 = _parse_boolean(xml_operand.attrib.get("allow-1to16"))
801 if allow_1to16 is not None:
802 operand.allow_1to16 = allow_1to16
803 operand.is_input = _parse_boolean(xml_operand.attrib.get("input", "false"))
804 operand.is_output = _parse_boolean(xml_operand.attrib.get("output", "false"))
805 operand.extended_size = _parse_value(xml_operand.attrib.get("extended-size"), [], 10)
806 instruction_form.operands.append(operand)
807 for xml_implicit_operand in xml_instruction_form.findall("ImplicitOperand"):
808 if _parse_boolean(xml_implicit_operand.attrib["input"]):
809 instruction_form.implicit_inputs.add(xml_implicit_operand.attrib["id"])
810 if _parse_boolean(xml_implicit_operand.attrib["output"]):
811 instruction_form.implicit_outputs.add(xml_implicit_operand.attrib["id"])
812 for xml_encoding in xml_instruction_form.findall("Encoding"):
813 encoding = Encoding()
814 for xml_component in xml_encoding:
815 if xml_component.tag == "Prefix":
816 prefix = Prefix()
817 prefix.byte = _parse_value(xml_component.attrib.get("byte"), [], 16)
818 assert prefix.byte in [0x66, 0xF2, 0xF3]
819 prefix.is_mandatory = _parse_boolean(xml_component.attrib.get("mandatory"))
820 encoding.components.append(prefix)
821 elif xml_component.tag == "REX":
822 rex = REX()
823 rex.is_mandatory = _parse_boolean(xml_component.attrib["mandatory"])
824 rex.W = _parse_value(xml_component.attrib.get("W"), [], 2)
825 rex.R = _parse_value(xml_component.attrib.get("R"), instruction_form.operands, 2)
826 rex.B = _parse_value(xml_component.attrib.get("B"), instruction_form.operands, 2)
827 rex.X = _parse_value(xml_component.attrib.get("X"), instruction_form.operands, 2)
828 encoding.components.append(rex)
829 elif xml_component.tag == "VEX":
830 vex = VEX()
831 vex.pp = int(xml_component.attrib["pp"], 2)
832 vex.mmmmm = int(xml_component.attrib["m-mmmm"], 2)
833 vex.W = _parse_value(xml_component.attrib.get("W"), [], 2)
834 vex.L = int(xml_component.attrib["L"], 2)
835 vex.R = _parse_value(xml_component.attrib.get("R"), instruction_form.operands, 2)
836 vex.B = _parse_value(xml_component.attrib.get("B"), instruction_form.operands, 2)
837 vex.X = _parse_value(xml_component.attrib.get("X"), instruction_form.operands)
838 vex.vvvv = _parse_value(xml_component.attrib.get("vvvv"), instruction_form.operands, 2)
839 encoding.components.append(vex)
840 elif xml_component.tag == "MVEX":
841 mvex = MVEX()
842 mvex.pp = int(xml_component.attrib["pp"], 2)
843 mvex.mmmm = int(xml_component.attrib["mmmm"], 2)
844 mvex.W = _parse_value(xml_component.attrib.get("W"), [], 2)
845 mvex.vvvv = _parse_value(xml_component.attrib["vvvv"], instruction_form.operands, 2)
846 mvex.V = _parse_value(xml_component.attrib["V"], instruction_form.operands, 2)
847 mvex.SSS = _parse_value(xml_component.attrib["SSS"], instruction_form.operands, 2)
848 mvex.aaa = _parse_value(xml_component.attrib["aaa"], instruction_form.operands, 2)
849 mvex.X = _parse_value(xml_component.attrib.get("X"), instruction_form.operands)
850 mvex.B = _parse_value(xml_component.attrib["B"], instruction_form.operands)
851 mvex.RR = _parse_value(xml_component.attrib.get("RR"), instruction_form.operands)
852 encoding.components.append(mvex)
853 elif xml_component.tag == "Opcode":
854 opcode = Opcode(int(xml_component.attrib["byte"], 16))
855 opcode.addend = _parse_value(xml_component.get("addend"), instruction_form.operands)
856 encoding.components.append(opcode)
857 elif xml_component.tag == "ModRM":
858 modrm = ModRM()
859 modrm.mode = _parse_value(xml_component.attrib.get("mode"), instruction_form.operands, 2)
860 modrm.reg = _parse_value(xml_component.attrib.get("reg"), instruction_form.operands, 10)
861 modrm.rm = _parse_value(xml_component.attrib.get("rm"), instruction_form.operands)
862 encoding.components.append(modrm)
863 elif xml_component.tag == "Immediate":
864 assert "size" in xml_component.attrib
865 immediate = Immediate()
866 immediate.size = int(xml_component.attrib["size"])
867 assert immediate.size in [1, 2, 4, 8]
868 immediate.value = _parse_value(xml_component.attrib.get("value"), instruction_form.operands)
869 encoding.components.append(immediate)
870 elif xml_component.tag == "CodeOffset":
871 assert "size" in xml_component.attrib
872 code_offset = CodeOffset()
873 code_offset.size = int(xml_component.attrib["size"])
874 assert code_offset.size in [1, 4]
875 code_offset.value = _parse_value(xml_component.attrib.get("value"), instruction_form.operands)
876 encoding.components.append(code_offset)
877 elif xml_component.tag == "DataOffset":
878 assert "size" in xml_component.attrib
879 data_offset = DataOffset()
880 data_offset.size = int(xml_component.attrib["size"])
881 assert data_offset.size in [4, 8]
882 data_offset.value = _parse_value(xml_component.attrib.get("value"), instruction_form.operands)
883 encoding.components.append(data_offset)
884 else:
885 print("Unknown encoding tag: " + xml_component.tag)
886
887 instruction_form.encodings.append(encoding)
888 instruction.forms.append(instruction_form)
889 instruction_set.append(instruction)
890 return instruction_set