Debian Codegraph @

x86/x86map/map.go

raw symbols SCIP
1 // Copyright 2014 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // X86map constructs the x86 opcode map from the instruction set CSV file.
6 //
7 // Usage:
8 //
9 // x86map [-fmt=format] x86.csv
10 //
11 // The known output formats are:
12 //
13 // text (default) - print decoding tree in text form
14 // decoder - print decoding tables for the x86asm package
15 // scanner - print scanning tables for x86scan package
16 package main
17
18 import (
19 "bufio"
20 "bytes"
21 "encoding/csv"
22 "flag"
23 "fmt"
24 "io"
25 "log"
26 "os"
27 "sort"
28 "strconv"
29 "strings"
30 )
31
32 var format = flag.String("fmt", "text", "output format: text, decoder")
33
34 var inputFile string
35
36 func usage() {
37 fmt.Fprintf(os.Stderr, "usage: x86map [-fmt=format] x86.csv\n")
38 os.Exit(2)
39 }
40
41 func main() {
42 log.SetFlags(0)
43 log.SetPrefix("x86map: ")
44
45 flag.Usage = usage
46 flag.Parse()
47 if flag.NArg() != 1 {
48 usage()
49 }
50
51 inputFile = flag.Arg(0)
52
53 var print func(*Prog)
54 switch *format {
55 default:
56 log.Fatalf("unknown output format %q", *format)
57 case "text":
58 print = printText
59 case "decoder":
60 print = printDecoder
61 case "scanner":
62 print = printScanner
63 }
64
65 p, err := readCSV(flag.Arg(0))
66 if err != nil {
67 log.Fatal(err)
68 }
69
70 //p = mergeTail(p)
71
72 print(p)
73 }
74
75 // readCSV reads the CSV file and returns the corresponding Prog.
76 // It may print details about problems to standard error using the log package.
77 func readCSV(file string) (*Prog, error) {
78 // Read input.
79 // Skip leading blank and # comment lines.
80 f, err := os.Open(file)
81 if err != nil {
82 return nil, err
83 }
84 b := bufio.NewReader(f)
85 for {
86 c, err := b.ReadByte()
87 if err != nil {
88 break
89 }
90 if c == '\n' {
91 continue
92 }
93 if c == '#' {
94 b.ReadBytes('\n')
95 continue
96 }
97 b.UnreadByte()
98 break
99 }
100 table, err := csv.NewReader(b).ReadAll()
101 if err != nil {
102 return nil, fmt.Errorf("parsing %s: %v", file, err)
103 }
104 if len(table) == 0 {
105 return nil, fmt.Errorf("empty csv input")
106 }
107 if len(table[0]) < 6 {
108 return nil, fmt.Errorf("csv too narrow: need at least six columns")
109 }
110
111 p := &Prog{}
112 for _, row := range table {
113 add(p, row[0], row[1], row[2], row[3], row[4], row[5])
114 }
115
116 check(p)
117
118 return p, nil
119 }
120
121 // A Prog is a single node in the tree representing the instruction format.
122 // Collectively the tree of nodes form a kind of program for decoding.
123 // Each Prog has a single action, identifying the kind of node it is,
124 // and then children to be executed according to the action.
125 // For example, the Prog with Action="decode" has children named for each
126 // possible next byte in the input, and those children are the decoding
127 // tree to execute for the corresponding bytes.
128 type Prog struct {
129 Path string
130 Action string
131 Child map[string]*Prog
132 PC int
133 TailID int
134 }
135
136 // keys returns the child keys in sorted order.
137 func (p *Prog) keys() []string {
138 var keys []string
139 for key := range p.Child {
140 keys = append(keys, key)
141 }
142 sort.Strings(keys)
143 return keys
144 }
145
146 // findChildLeaf finds a leaf node in the subtree rooted at p
147 // and returns that node's full path. The path is useful in error
148 // messages as an example of where a particular subtree is headed.
149 func (p *Prog) findChildLeaf() string {
150 for {
151 if len(p.Child) == 0 {
152 return p.Path
153 }
154 p = p.Child[p.keys()[0]]
155 }
156 }
157
158 // walk advances from p to apply the given action and key.
159 // If p has no action yet, the action is recorded as p.Action.
160 // Otherwise the action must match p's action: every node in the
161 // tree can have at most one action, although possibly with many
162 // alternative keys.
163 // If p already has an alternative with the given key, walk returns
164 // that preexisting subtree. Otherwise walk allocates a new Prog
165 // representing that subtree and returns that node.
166 func (p *Prog) walk(action, key, text, opcode string) *Prog {
167 if p.Action == "" {
168 p.Action = action
169 } else if p.Action != action {
170 log.Printf("%s; %s: conflicting paths %s and %s|%s %s\n", text, opcode, p.findChildLeaf(), p.Path, action, key)
171 return new(Prog)
172 }
173 q := p.Child[key]
174 if q == nil {
175 if p.Child == nil {
176 p.Child = make(map[string]*Prog)
177 }
178 q = new(Prog)
179 q.Path = fmt.Sprintf("%s|%s %s", p.Path, action, key)
180 p.Child[key] = q
181 }
182 return q
183 }
184
185 // add adds a single instructions to the tree rooted at root.
186 // The string arguments match the CSV: instruction mnemonic,
187 // opcode encoding, validity in 32- and 64-bit modes, CPUID
188 // feature set (ignored), and additional tags.
189 //
190 // In effect, add adds a new path through the tree leading to
191 // the given instruction, but it reuses as much of the existing
192 // tree structure as possible. For example if there have already
193 // been instructions added starting with 0F and this instruction
194 // also starts with 0F, that 0F subtree node is reused instead of
195 // allocating a parallel one. To maximize the reuse, the check action
196 // sequence along the path being added is the same for every instruction:
197 // encoding pieces needed to make a decision, 64-bit mode check,
198 // rex check, prefix check, address size check, data size check,
199 // register vs memory argument check. Once all those checks have
200 // been applied, the assumption is that we have uniquely identified
201 // an instruction, and at that point it is okay to diverge from the
202 // uniform pattern to set the opcode and read the specific arguments
203 // corresponding to the instruction at hand.
204 //
205 // The maximimal reuse of the existing tree means that the tree
206 // resulting from all adds have been done amounts to a decision tree.
207 // There is one detail that makes it non-deterministic: some checks
208 // do not matter to some instructions and those are recorded as "any" keys.
209 // If you are decoding and there is a key for the specific thing you are
210 // seeing as well as the "any" key, both must be considered. To avoid
211 // adding complexity to the decoder execution, the 'check' function
212 // removes this case by merging "any" trees into specific keys when
213 // present.
214 func add(root *Prog, text, opcode, valid32, valid64, cpuid, tags string) {
215 // These are not real instructions: they are either
216 // prefixes for other instructions, composite instructions
217 // built from multiple individual instructions, or alternate
218 // mnemonics of other encodings.
219 // Discard for disassembly, because we want a unique decoding.
220 if strings.Contains(tags, "pseudo") {
221 return
222 }
223
224 // Treat REX.W + opcode as being like having an "operand64" tag.
225 // The REX.W flag sets the operand size to 64 bits; in this way it is
226 // not much different than the 66 prefix that inverts 32 vs 16 bits.
227 if strings.Contains(opcode, "REX.W") {
228 if !strings.Contains(tags, "operand64") {
229 if tags != "" {
230 tags += ","
231 }
232 tags += "operand64"
233 }
234 }
235
236 // If there is more than one operand size given, we need to do
237 // a separate add for each size, because we need multiple
238 // keys to be added in the operand size branch, and the code makes
239 // a linear pass through the tree adding just one key to each node.
240 // We would need to do the same for any other possible repeated tag
241 // (for example, if an instruction could have multiple address sizes)
242 // but so far operand size is the only tag we have needed to repeat.
243 if strings.Count(tags, "operand") > 1 {
244 f := strings.Split(tags, ",")
245 var ops []string
246 w := 0
247 for _, tag := range f {
248 if strings.HasPrefix(tag, "operand") {
249 ops = append(ops, tag)
250 } else {
251 if strings.Contains(tag, "operand") {
252 log.Fatalf("unknown tag %q", tag)
253 }
254 f[w] = tag
255 w++
256 }
257 }
258 f = f[:w]
259 for _, op := range ops {
260 add(root, text, opcode, valid32, valid64, cpuid, strings.Join(append(f, op), ","))
261 }
262 return
263 }
264
265 p := root
266 walk := func(action, item string) {
267 p = p.walk(action, item, text, opcode)
268 }
269
270 // Ignore VEX instructions for now.
271 if strings.HasPrefix(opcode, "VEX") {
272 return
273 }
274
275 var rex, prefix string
276 encoding := strings.Fields(opcode)
277 if len(encoding) > 0 && strings.HasPrefix(encoding[0], "REX") {
278 rex = encoding[0]
279 encoding = encoding[1:]
280 if len(encoding) > 0 && encoding[0] == "+" {
281 encoding = encoding[1:]
282 }
283 }
284 if len(encoding) > 0 && isPrefix[encoding[0]] {
285 prefix = encoding[0]
286 encoding = encoding[1:]
287 }
288 if rex == "" && len(encoding) > 0 && strings.HasPrefix(encoding[0], "REX") {
289 rex = encoding[0]
290 if rex == "REX" {
291 log.Printf("REX without REX.W: %s %s", text, opcode)
292 }
293 encoding = encoding[1:]
294 if len(encoding) > 0 && encoding[0] == "+" {
295 encoding = encoding[1:]
296 }
297 }
298 if len(encoding) > 0 && isPrefix[encoding[0]] {
299 log.Printf("%s %s: too many prefixes", text, opcode)
300 return
301 }
302
303 var haveModRM, havePlus bool
304 var usedReg string
305 for len(encoding) > 0 && (isHex(encoding[0]) || isSlashNum(encoding[0])) {
306 key := encoding[0]
307 if isSlashNum(key) {
308 if usedReg != "" {
309 log.Printf("%s %s: multiple modrm checks", text, opcode)
310 }
311 haveModRM = true
312 usedReg = key
313 }
314 if i := strings.Index(key, "+"); i >= 0 {
315 key = key[:i+1]
316 havePlus = true
317 }
318 walk("decode", key)
319 encoding = encoding[1:]
320 }
321
322 if valid32 != "V" {
323 walk("is64", "1")
324 } else if valid64 != "V" {
325 walk("is64", "0")
326 } else {
327 walk("is64", "any")
328 }
329
330 if prefix == "" {
331 prefix = "0"
332 }
333 walk("prefix", prefix)
334
335 if strings.Contains(tags, "address16") {
336 walk("addrsize", "16")
337 } else if strings.Contains(tags, "address32") {
338 walk("addrsize", "32")
339 } else if strings.Contains(tags, "address64") {
340 walk("addrsize", "64")
341 } else {
342 walk("addrsize", "any")
343 }
344
345 if strings.Contains(tags, "operand16") {
346 walk("datasize", "16")
347 } else if strings.Contains(tags, "operand32") {
348 walk("datasize", "32")
349 } else if strings.Contains(tags, "operand64") {
350 walk("datasize", "64")
351 } else {
352 walk("datasize", "any")
353 }
354
355 if len(encoding) > 0 && encoding[0] == "/r" {
356 haveModRM = true
357 }
358 if haveModRM {
359 if strings.Contains(tags, "modrm_regonly") {
360 walk("ismem", "0")
361 } else if strings.Contains(tags, "modrm_memonly") {
362 walk("ismem", "1")
363 } else {
364 walk("ismem", "any")
365 }
366 }
367
368 walk("op", strings.Fields(text)[0])
369
370 if len(encoding) > 0 && strings.HasPrefix(encoding[0], "VEX") {
371 for _, field := range encoding[2:] {
372 walk("read", field)
373 }
374 } else {
375 for _, field := range encoding {
376 walk("read", field)
377 }
378 }
379
380 var usedRM string
381 for _, arg := range strings.Fields(text)[1:] {
382 arg = strings.TrimRight(arg, ",")
383 if usesReg[arg] && !haveModRM && !havePlus {
384 log.Printf("%s %s: no modrm field to use for %s", text, opcode, arg)
385 continue
386 }
387 if usesRM[arg] && !haveModRM {
388 log.Printf("%s %s: no modrm field to use for %s", text, opcode, arg)
389 continue
390 }
391 if usesReg[arg] {
392 if usedReg != "" {
393 log.Printf("%s %s: modrm reg field used by both %s and %s", text, opcode, usedReg, arg)
394 continue
395 }
396 usedReg = arg
397 }
398 if usesRM[arg] {
399 if usedRM != "" {
400 log.Printf("%s %s: modrm r/m field used by both %s and %s", text, opcode, usedRM, arg)
401 continue
402 }
403 usedRM = arg
404 }
405 walk("arg", arg)
406 }
407
408 walk("match", "!")
409 }
410
411 // allKeys records the list of all possible child keys for actions that support "any".
412 var allKeys = map[string][]string{
413 "is64": {"0", "1"},
414 "ismem": {"0", "1"},
415 "addrsize": {"16", "32", "64"},
416 "datasize": {"16", "32", "64"},
417 }
418
419 // check checks that the program tree is well-formed.
420 // It also merges "any" keys into specific decoding keys in order to
421 // create an invariant that a particular check node either has a
422 // single "any" child - making it a no-op - or has no "any" children.
423 // See the discussion of "any" in the comment for add above.
424 func check(p *Prog) {
425 if p.Child["any"] != nil && len(p.Child) > 1 {
426 for _, key := range p.keys() {
427 if key != "any" {
428 mergeCopy(p.Child[key], p.Child["any"])
429 }
430 }
431 if allKeys[p.Action] == nil {
432 log.Printf("%s: unknown key space for %s=any", p.Path, p.Action)
433 }
434 for _, key := range allKeys[p.Action] {
435 if p.Child[key] == nil {
436 p.Child[key] = p.Child["any"]
437 }
438 }
439 delete(p.Child, "any")
440 }
441
442 for _, q := range p.Child {
443 check(q)
444 }
445
446 switch p.Action {
447 case "op", "read", "arg":
448 if len(p.Child) > 1 {
449 log.Printf("%s: multiple children for action=%s: %v", p.Path, p.Action, p.keys())
450 }
451 }
452 }
453
454 // mergeCopy merges a copy of the tree rooted at src into dst.
455 // It is only used once no more paths will be added to the tree,
456 // so it is safe to introduce cross-links that make the program
457 // a dag rather than a tree.
458 func mergeCopy(dst, src *Prog) {
459 //log.Printf("merge %s|%s and %s|%s\n", dst.Path, dst.Action, src.Path, src.Action)
460 if dst.Action != src.Action {
461 log.Printf("cannot merge %s|%s and %s|%s", dst.Path, dst.Action, src.Path, src.Action)
462 return
463 }
464
465 for _, key := range src.keys() {
466 if dst.Child[key] == nil {
467 // Create new subtree by creating cross-link.
468 dst.Child[key] = src.Child[key]
469 } else {
470 // Merge src subtree into existing dst subtree.
471 mergeCopy(dst.Child[key], src.Child[key])
472 }
473 }
474 }
475
476 // set returns a map mapping each of the words in all to true.
477 func set(all string) map[string]bool {
478 m := map[string]bool{}
479 for _, f := range strings.Fields(all) {
480 m[f] = true
481 }
482 return m
483 }
484
485 // isPrefix records the x86 opcode prefix bytes.
486 var isPrefix = set(`
487 26
488 2E
489 36
490 3E
491 64
492 65
493 66
494 67
495 F0
496 F2
497 F3
498 `)
499
500 // usesReg records the argument codes that use the modrm reg field.
501 var usesReg = set(`
502 r8
503 r16
504 r32
505 r64
506 `)
507
508 // usesRM records the argument codes that use the modrm r/m field.
509 var usesRM = set(`
510 r/m8
511 r/m16
512 r/m32
513 r/m64
514 `)
515
516 var isVexEncodablePrefix = set(`
517 0F
518 0F38
519 0F3A
520 66
521 F3
522 F2
523 `)
524
525 // isHex reports whether the argument is a two digit hex number
526 // possibly followed by a +foo suffix.
527 func isHex(s string) bool {
528 if i := strings.Index(s, "+"); i >= 0 {
529 s = s[:i]
530 }
531 if len(s) != 2 {
532 return false
533 }
534 for i := 0; i < len(s); i++ {
535 c := s[i]
536 if '0' <= c && c <= '9' || 'A' <= c && c <= 'F' {
537 continue
538 }
539 return false
540 }
541 return true
542 }
543
544 // isSlashNum reports whether the argument is /n for some number n in [0,7].
545 func isSlashNum(s string) bool {
546 return len(s) == 2 && s[0] == '/' && '0' <= s[1] && s[1] <= '7'
547 }
548
549 // mergeTail is supposed to merge common subtrees (program tails),
550 // reducing the size of the final program code.
551 // It identifies the subtrees using a bottom-up canonicalization.
552 //
553 // THIS CODE DOES NOT WORK. IT NEEDS TO BE DEBUGGED.
554 func mergeTail(p *Prog, emitted map[string]*Prog) *Prog {
555 if emitted == nil {
556 emitted = make(map[string]*Prog)
557 }
558
559 if p.Action == "match" {
560 return p
561 }
562
563 for _, key := range p.keys() {
564 p.Child[key] = mergeTail(p.Child[key], emitted)
565 }
566
567 op := ""
568 for _, key := range p.keys() {
569 q := p.Child[key]
570 if q.Action != "op" || len(q.Child) > 1 {
571 op = ""
572 break
573 }
574 qop := q.keys()[0]
575 if op == "" {
576 op = qop
577 } else if op != qop {
578 op = ""
579 break
580 }
581 }
582
583 if op != "" {
584 // Pull 'op x' up above the discriminator.
585 p1 := new(Prog)
586 *p1 = *p
587 for _, key := range p.keys() {
588 p1.Child[key] = p.Child[key].Child[op]
589 }
590 p.Action = "op"
591 p.Child = map[string]*Prog{op: p1}
592 }
593
594 var buf bytes.Buffer
595 fmt.Fprintf(&buf, "%s\n", p.Action)
596 for _, key := range p.keys() {
597 fmt.Fprintf(&buf, "%s %d\n", key, p.Child[key].TailID)
598 }
599 key := buf.String()
600
601 if q := emitted[key]; q != nil {
602 return q
603 }
604 emitted[key] = p
605 p.TailID = len(emitted)
606 return p
607 }
608
609 // printText prints the tree in textual form.
610 func printText(p *Prog) {
611 printTree(os.Stdout, p, 0, false)
612 }
613
614 var tabs = strings.Repeat(" ", 100)
615
616 func printTree(w io.Writer, p *Prog, depth int, compact bool) {
617 if compact && len(p.Child) == 1 {
618 fmt.Fprintf(w, "%.*s%s", 4*depth, tabs, p.Action)
619 for len(p.Child) == 1 {
620 key := p.keys()[0]
621 child := p.Child[key]
622 fmt.Fprintf(w, " %s %s", key, child.Action)
623 p = child
624 }
625 fmt.Fprintf(w, "\n")
626 } else {
627 fmt.Fprintf(w, "%.*s%s\n", 4*depth, tabs, p.Action)
628 }
629 for _, key := range p.keys() {
630 fmt.Fprintf(w, "%.*s%s\n", 4*(depth+1), tabs, key)
631 printTree(w, p.Child[key], depth+2, compact)
632 }
633 }
634
635 // printDecoder prints a Go array containing the decoder program.
636 // It runs in two passes, both of which traverse and could generate
637 // the entire program. The first pass records the PC for each Prog node,
638 // and the second pass emits the actual program, using the PCs as jump
639 // targets in the places where the program is a dag rather than a tree.
640 func printDecoder(p *Prog) {
641 opMap := map[string]bool{
642 "PAUSE": true,
643 }
644 printDecoderPass(p, 1, false, opMap)
645 fmt.Printf("// Code generated by x86map -fmt=decoder %s DO NOT EDIT.\n", inputFile)
646 fmt.Printf("\n")
647 fmt.Printf("package x86asm\n\n")
648 fmt.Printf("var decoder = [...]uint16{\n\tuint16(xFail),\n")
649 printDecoderPass(p, 1, true, opMap)
650 fmt.Printf("}\n\n")
651
652 var ops []string
653 for op := range opMap {
654 ops = append(ops, op)
655 }
656 sort.Strings(ops)
657
658 fmt.Printf("const (\n")
659 fmt.Printf("\t_ Op = iota\n\n")
660 last := ""
661 for _, op := range ops {
662 fmt.Printf("\t%s\n", op)
663 last = op
664 }
665 fmt.Printf(")\n\n")
666 fmt.Printf("const maxNonAVXOp = %s\n\n", last)
667
668 fmt.Printf("var opNames = [...]string{\n")
669 for _, op := range ops {
670 fmt.Printf("\t%s: \"%s\",\n", op, op)
671 }
672 fmt.Printf("}\n")
673 }
674
675 // printScanner prints the decoding table for a scanner.
676 // The scanner can identify instruction boundaries but does not do
677 // full decoding. It is meant to be lighter weight than the x86asm
678 // decoder tables.
679 func printScanner(p *Prog) {
680 walkScanTree(p, -1)
681 var out []uint16
682 out = append(out, 0)
683 emitScanFunc(p, &out)
684 fmt.Printf("var scanProg = []uint16{\n")
685 fmt.Printf("\t/*0*/ 0, // dead\n")
686 for i := 1; i < len(out); i++ {
687 fmt.Printf("\t/*%d*/ ", i)
688 switch out[i] {
689 default:
690 log.Fatalf("malformed program %#x", out[i])
691 case scanMatch:
692 fmt.Printf("scanMatch,\n")
693 continue
694 case scanJump:
695 fmt.Printf("scanJump, %d,\n", out[i+1])
696 i++
697 continue
698 case scanSwitchByte:
699 fmt.Printf("scanSwitchByte,\n")
700 for j := 0; j < 256/8; j++ {
701 fmt.Printf("\t")
702 fmt.Printf("/* %#02x-%#02x */", j*8, j*8+7)
703 for k := 0; k < 8; k++ {
704 fmt.Printf(" %d,", out[i+1+j*8+k])
705 }
706 fmt.Printf("\n")
707 }
708 i += 256
709 continue
710 case scanSwitchSlash:
711 fmt.Printf("scanSwitchSlash, %d,\n", out[i+1])
712 n := int(out[i+1])
713 for j := 0; j < n; j++ {
714 fmt.Printf("\t/* byte */ %#x, %d,\n", out[i+2+2*j], out[i+2+2*j+1])
715 }
716 for j := 0; j < 8; j++ {
717 fmt.Printf("\t/* /%d */ %d,\n", j, out[i+2+2*n+j])
718 }
719 i += 1 + 2*n + 8
720 continue
721 case scanSwitchPrefix:
722 fmt.Printf("scanSwitchPrefix, %d,\n", out[i+1])
723 n := int(out[i+1])
724 for j := 0; j < n; j++ {
725 fmt.Printf("\t/* prefix */ %#x, %d,\n", out[i+2+2*j], out[i+2+2*j+1])
726 }
727 i += 1 + 2*n
728 continue
729 case scanSwitchIs64:
730 fmt.Printf("scanSwitchIs64, %d, %d\n", out[i+1], out[i+2])
731 i += 2
732 continue
733 case scanSwitchDatasize:
734 fmt.Printf("scanSwitchDatasize, %d, %d, %d\n", out[i+1], out[i+2], out[i+3])
735 i += 3
736 continue
737 case scanSwitchIsMem:
738 fmt.Printf("scanSwitchIsMem, %d, %d\n", out[i+1], out[i+2])
739 i += 2
740 continue
741 case scanReadModRM:
742 fmt.Printf("scanReadModRM,\n")
743 continue
744 case scanReadIB:
745 fmt.Printf("scanReadIB,\n")
746 continue
747 case scanReadIW:
748 fmt.Printf("scanReadIW,\n")
749 continue
750 case scanReadIWD:
751 fmt.Printf("scanReadIWD,\n")
752 continue
753 case scanReadIWDO:
754 fmt.Printf("scanReadIWDO,\n")
755 continue
756 case scanReadCWD:
757 fmt.Printf("scanReadCWD,\n")
758 continue
759 case scanReadCB:
760 fmt.Printf("scanReadCB,\n")
761 continue
762 case scanReadCDP:
763 fmt.Printf("scanReadCDP,\n")
764 continue
765 case scanReadCM:
766 fmt.Printf("scanReadCM,\n")
767 continue
768 }
769 }
770 fmt.Printf("}\n")
771 }
772
773 func walkScanTree(p *Prog, is64 int) {
774 keys := p.keys()
775 for _, key := range keys {
776 if p.Action == "is64" {
777 switch key {
778 case "0":
779 is64 = 0
780 case "1":
781 is64 = 1
782 }
783 }
784 walkScanTree(p.Child[key], is64)
785 }
786
787 switch p.Action {
788 case "read", "match":
789 // keep
790 return
791 case "decode":
792 if len(keys) >= 8 && keys[0] == "/0" && keys[7] == "/7" && allSame(p, keys) {
793 p.Action = "read"
794 p.Child = map[string]*Prog{"/r": p.Child[keys[0]]}
795 return
796 }
797 case "op", "arg":
798 // drop
799 *p = *p.Child[keys[0]]
800 return
801 case "prefix":
802 if len(keys) >= 1 && keys[0] == "0" && allSame(p, keys) {
803 *p = *p.Child[keys[0]]
804 return
805 }
806 case "is64", "addrsize", "datasize", "ismem":
807 if len(keys) == 1 && keys[0] == "any" {
808 *p = *p.Child[keys[0]]
809 return
810 }
811 nkey := len(allKeys[p.Action])
812 if p.Action == "addrsize" {
813 nkey = 2
814 }
815 if p.Action == "datasize" && is64 == 0 {
816 nkey = 2
817 }
818 if len(keys) == nkey && allSame(p, keys) {
819 *p = *p.Child[keys[0]]
820 return
821 }
822 }
823
824 switch p.Action {
825 case "datasize":
826 if len(keys) == 2 && is64 == 0 || len(keys) == 3 {
827 if treeText(p.Child["16"]) == "read iw match ! \n" && treeText(p.Child["32"]) == "read id match ! \n" && (len(keys) == 2 || treeText(p.Child["64"]) == "read id match ! \n") {
828 p.Action = "read"
829 p.Child = map[string]*Prog{"iwd/d": p.Child["16"].Child["iw"]}
830 return
831 }
832 if len(keys) == 3 && treeText(p.Child["16"]) == "read iw match ! \n" && treeText(p.Child["32"]) == "read id match ! \n" && treeText(p.Child["64"]) == "read io match ! \n" {
833 p.Action = "read"
834 p.Child = map[string]*Prog{"iwdo/d": p.Child["16"].Child["iw"]}
835 return
836 }
837 if treeText(p.Child["16"]) == "read /r read iw match ! \n" && treeText(p.Child["32"]) == "read /r read id match ! \n" && (len(keys) == 2 || treeText(p.Child["64"]) == "read /r read id match ! \n") {
838 p.Action = "read"
839 p.Child = map[string]*Prog{"/r": {Action: "read", Child: map[string]*Prog{"iwd/d": p.Child["16"].Child["/r"].Child["iw"]}}}
840 return
841 }
842 if treeText(p.Child["16"]) == "read cw match ! \n" && treeText(p.Child["32"]) == "read cd match ! \n" && (len(keys) == 2 || treeText(p.Child["64"]) == "read cd match ! \n") {
843 p.Action = "read"
844 p.Child = map[string]*Prog{"cwd/d": p.Child["16"].Child["cw"]}
845 return
846 }
847 if treeText(p.Child["16"]) == "read cd match ! \n" && treeText(p.Child["32"]) == "read cp match ! \n" && (len(keys) == 2 || treeText(p.Child["64"]) == "read cp match ! \n") {
848 p.Action = "read"
849 p.Child = map[string]*Prog{"cdp/d": p.Child["16"].Child["cd"]}
850 return
851 }
852 fmt.Printf("!! %q\n", treeText(p.Child["16"]))
853 }
854
855 case "is64":
856 if len(keys) == 2 && treeText(p.Child["0"]) == "read cwd/d match ! \n" && treeText(p.Child["1"]) == "read cd match ! \n" {
857 *p = *p.Child["0"]
858 return
859 }
860 if len(keys) == 2 && treeText(p.Child["0"]) == "read iwd/d match ! \n" && treeText(p.Child["1"]) == "read iwdo/d match ! \n" {
861 *p = *p.Child["1"]
862 return
863 }
864 }
865
866 /*
867 match := make(map[string][]string)
868 for _, key := range keys {
869 text := treeText(p.Child[key])
870 match[text] = append(match[text], key)
871 }
872 child := make(map[string]*Prog)
873 for _, keys := range match {
874 child[strings.Join(keys, ",")] = p.Child[keys[0]]
875 }
876 p.Child = child
877 */
878 }
879
880 func treeText(p *Prog) string {
881 var buf bytes.Buffer
882 printTree(&buf, p, 0, true)
883 return buf.String()
884 }
885
886 func allSame(p *Prog, keys []string) bool {
887 var tree string
888 for i, key := range keys {
889 if i == 0 {
890 tree = treeText(p.Child[key])
891 continue
892 }
893 if treeText(p.Child[key]) != tree {
894 return false
895 }
896 }
897 return true
898 }
899
900 var scanCache = map[string]uint16{}
901
902 const (
903 _ uint16 = iota
904 scanMatch
905 scanJump
906 scanSwitchByte
907 scanSwitchSlash
908 scanSwitchIs64
909 scanSwitchDatasize
910 scanSwitchIsMem
911 scanSwitchPrefix
912 scanReadModRM
913 scanReadIB
914 scanReadIW
915 scanReadIWD
916 scanReadIWDO
917 scanReadCWD
918 scanReadCB
919 scanReadCDP
920 scanReadCM
921 )
922
923 func decodeKeyPlus(key string) (val, n int) {
924 n = 1
925 if strings.HasSuffix(key, "+") {
926 n = 8
927 key = key[:len(key)-1]
928 }
929 v, err := strconv.ParseUint(key, 16, 8)
930 if err != nil {
931 log.Fatalf("unexpected decode key %q", key)
932 }
933 return int(v), n
934 }
935
936 func decodeKey(key string) int {
937 val, n := decodeKeyPlus(key)
938 if n != 1 {
939 log.Panicf("unexpected decode key+ %q", key)
940 }
941 return val
942 }
943
944 func emitScanFunc(p *Prog, out *[]uint16) uint16 {
945 keys := p.keys()
946 text := treeText(p)
947 if off, ok := scanCache[text]; ok {
948 return off
949 }
950 start := uint16(len(*out))
951 scanCache[text] = start
952 switch p.Action {
953 case "decode":
954 if keys[0][0] != '/' {
955 *out = append(*out, scanSwitchByte)
956 off := len(*out)
957 for i := 0; i < 256; i++ {
958 *out = append(*out, 0)
959 }
960 for _, key := range keys {
961 val, n := decodeKeyPlus(key)
962 dst := emitScanFunc(p.Child[key], out)
963 for j := 0; j < n; j++ {
964 (*out)[off+val+j] = dst
965 }
966 }
967 return start
968 }
969
970 n := len(keys)
971 for n > 0 && keys[n-1][0] != '/' {
972 n--
973 }
974 total := 0
975 for i := n; i < len(keys); i++ {
976 key := keys[i]
977 _, n := decodeKeyPlus(key)
978 total += n
979 }
980 *out = append(*out, scanSwitchSlash, uint16(total))
981 off := len(*out)
982 for i := 0; i < total; i++ {
983 *out = append(*out, 0, 0)
984 }
985 for i := 0; i < 8; i++ {
986 *out = append(*out, 0)
987 }
988 for i := n; i < len(keys); i++ {
989 key := keys[i]
990 val, valn := decodeKeyPlus(key)
991 targ := emitScanFunc(p.Child[key], out)
992 for j := 0; j < valn; j++ {
993 (*out)[off] = uint16(val + j)
994 off++
995 (*out)[off] = targ
996 off++
997 }
998 }
999 for i := 0; i < n; i++ {
1000 key := keys[i]
1001 if len(key) != 2 || key[0] != '/' || key[1] < '0' || '8' <= key[1] {
1002 log.Fatalf("unexpected decode key %q", key)
1003 }
1004 (*out)[off+int(key[1]-'0')] = emitScanFunc(p.Child[key], out)
1005 }
1006 return start
1007
1008 case "read":
1009 switch keys[0] {
1010 default:
1011 log.Fatalf("unexpected read %q", keys[0])
1012 case "/r":
1013 *out = append(*out, scanReadModRM)
1014 case "ib":
1015 *out = append(*out, scanReadIB)
1016 case "iw":
1017 *out = append(*out, scanReadIW)
1018 case "cb":
1019 *out = append(*out, scanReadCB)
1020 case "cm":
1021 *out = append(*out, scanReadCM)
1022 case "iwd/d":
1023 *out = append(*out, scanReadIWD)
1024 case "iwdo/d":
1025 *out = append(*out, scanReadIWDO)
1026 case "cwd/d":
1027 *out = append(*out, scanReadCWD)
1028 case "cdp/d":
1029 *out = append(*out, scanReadCDP)
1030 }
1031 next := p.Child[keys[0]]
1032 if next.Action == "match" {
1033 *out = append(*out, scanMatch)
1034 } else {
1035 *out = append(*out, scanJump, 0)
1036 off := len(*out)
1037 (*out)[off-1] = emitScanFunc(next, out)
1038 }
1039 return start
1040
1041 case "match":
1042 *out = append(*out, scanMatch)
1043 return start
1044
1045 case "is64":
1046 *out = append(*out, scanSwitchIs64, 0, 0)
1047 if next := p.Child["0"]; next != nil {
1048 (*out)[start+1] = emitScanFunc(next, out)
1049 }
1050 if next := p.Child["1"]; next != nil {
1051 (*out)[start+2] = emitScanFunc(next, out)
1052 }
1053 return start
1054
1055 case "ismem":
1056 *out = append(*out, scanSwitchIsMem, 0, 0)
1057 if next := p.Child["0"]; next != nil {
1058 (*out)[start+1] = emitScanFunc(next, out)
1059 }
1060 if next := p.Child["1"]; next != nil {
1061 (*out)[start+2] = emitScanFunc(next, out)
1062 }
1063 return start
1064
1065 case "datasize":
1066 *out = append(*out, scanSwitchDatasize, 0, 0, 0)
1067 if next := p.Child["16"]; next != nil {
1068 (*out)[start+1] = emitScanFunc(next, out)
1069 }
1070 if next := p.Child["32"]; next != nil {
1071 (*out)[start+2] = emitScanFunc(next, out)
1072 }
1073 if next := p.Child["64"]; next != nil {
1074 (*out)[start+3] = emitScanFunc(next, out)
1075 }
1076 return start
1077 case "prefix":
1078 *out = append(*out, scanSwitchPrefix, uint16(len(keys)))
1079 n := len(keys)
1080 for i := 0; i < n; i++ {
1081 *out = append(*out, uint16(decodeKey(keys[i])), 0)
1082 }
1083 for i := 0; i < n; i++ {
1084 (*out)[int(start)+2+2*i+1] = emitScanFunc(p.Child[keys[i]], out)
1085 }
1086 return start
1087
1088 }
1089
1090 log.Fatalf("unexpected action %q", p.Action)
1091 return start
1092 }
1093
1094 // printDecoderPass prints the decoding table program for p,
1095 // assuming that we are emitting code at the given program counter.
1096 // It returns the new current program counter, that is, the program
1097 // counter after the printed instructions.
1098 // If printing==false, printDecoderPass does not print the actual
1099 // code words but still does the PC computation.
1100 func printDecoderPass(p *Prog, pc int, printing bool, ops map[string]bool) int {
1101 // Record PC on first pass.
1102 if p.PC == 0 {
1103 p.PC = pc
1104 }
1105
1106 // If PC doesn't match, we've already printed this code
1107 // because it was reached some other way. Jump to that copy.
1108 if p.PC != pc {
1109 if printing {
1110 fmt.Printf("/*%d*/\tuint16(xJump), %d,\n", pc, p.PC)
1111 }
1112 return pc + 2
1113 }
1114
1115 // Otherwise, emit the code for the given action.
1116
1117 // At the bottom, if next is non-nil, emit code for next.
1118 // Then emit the code for the children named by the keys.
1119 keys := p.keys()
1120 var next *Prog
1121
1122 switch p.Action {
1123 default:
1124 log.Printf("printDecoderPass: unknown action %q: %s", p.Action, p.Path)
1125
1126 case "decode":
1127 // Decode hex bytes or /n modrm op checks.
1128 // Hex bytes take priority, so do them first.
1129 // Hex bytes of the form "40+" indicate an
1130 // 8 entry-wide swath of codes: 40, 41, ..., 47.
1131 hex := 0
1132 slash := 0
1133 for _, key := range keys {
1134 if isHex(key) {
1135 if strings.Contains(key, "+") {
1136 hex += 8
1137 } else {
1138 hex++
1139 }
1140 }
1141 if isSlashNum(key) {
1142 slash++
1143 }
1144 }
1145 if hex > 0 {
1146 // TODO(rsc): Introduce an xCondByte256 that has 256 child entries
1147 // and no explicit keys. That will cut the size in half for large
1148 // tables.
1149 if printing {
1150 fmt.Printf("/*%d*/\tuint16(xCondByte), %d,\n", pc, hex)
1151 for _, key := range keys {
1152 if !isHex(key) {
1153 continue
1154 }
1155 if i := strings.Index(key, "+"); i >= 0 {
1156 nextPC := p.Child[key].PC
1157 n, _ := strconv.ParseUint(key[:i], 16, 0)
1158 for j := 0; j < 8; j++ {
1159 fmt.Printf("\t%#02x, %d,\n", int(n)+j, nextPC)
1160 }
1161 continue
1162 }
1163 fmt.Printf("\t0x%s, %d,\n", key, p.Child[key].PC)
1164 }
1165 }
1166 pc += 2 + 2*hex
1167
1168 // All other condition checks fail the decoding if nothing is found,
1169 // but this one falls through so that we can then do /n checks.
1170 // If there are no upcoming /n checks, insert an explicit failure.
1171 if slash == 0 {
1172 if printing {
1173 fmt.Printf("\tuint16(xFail),\n")
1174 }
1175 pc++
1176 }
1177 }
1178 if slash > 0 {
1179 if printing {
1180 fmt.Printf("/*%d*/\tuint16(xCondSlashR),\n", pc)
1181 for i := 0; i < 8; i++ {
1182 fmt.Printf("\t%d, // %d\n", p.childPC(fmt.Sprintf("/%d", i)), i)
1183 }
1184 }
1185 pc += 1 + 8
1186 }
1187
1188 case "is64":
1189 // Decode based on processor mode: 64-bit or not.
1190 if len(keys) == 1 && keys[0] == "any" {
1191 next = p.Child["any"]
1192 break
1193 }
1194 if p.Child["any"] != nil {
1195 log.Printf("%s: mixed is64 keys: %v", p.Path, keys)
1196 }
1197
1198 if printing {
1199 fmt.Printf("/*%d*/\tuint16(xCondIs64), %d, %d,\n", pc, p.childPC("0"), p.childPC("1"))
1200 }
1201 pc += 3
1202
1203 case "prefix":
1204 // Decode based on presence of prefix.
1205 // The "0" prefix means "none of the above", so if there's
1206 // nothing else, it's the same as "any".
1207 if len(keys) == 1 && (keys[0] == "any" || keys[0] == "0") {
1208 next = p.Child["any"]
1209 break
1210 }
1211 if p.Child["any"] != nil {
1212 log.Printf("%s: mixed prefix keys: %v", p.Path, keys)
1213 }
1214
1215 // Emit the prefixes in reverse sorted order, so that F3 and F2 are
1216 // considered before 66, and the fallback 0 is considered last.
1217 if printing {
1218 fmt.Printf("/*%d*/\tuint16(xCondPrefix), %d,\n", pc, len(keys))
1219 for i := len(keys) - 1; i >= 0; i-- {
1220 key := keys[i]
1221 nextPC := p.Child[key].PC
1222 fmt.Printf("\t0x%s, %d,\n", key, nextPC)
1223 }
1224 }
1225 pc += 2 + 2*len(keys)
1226
1227 case "addrsize":
1228 // Decode based on address size attribute.
1229 if len(keys) == 1 && keys[0] == "any" {
1230 next = p.Child["any"]
1231 break
1232 }
1233 if p.Child["any"] != nil {
1234 log.Printf("%s: mixed addrsize keys: %v", p.Path, keys)
1235 }
1236
1237 if printing {
1238 fmt.Printf("/*%d*/\tuint16(xCondAddrSize), %d, %d, %d,\n", pc, p.childPC("16"), p.childPC("32"), p.childPC("64"))
1239 }
1240 pc += 4
1241
1242 case "datasize":
1243 // Decode based on operand size attribute.
1244 if len(keys) == 1 && keys[0] == "any" {
1245 next = p.Child["any"]
1246 break
1247 }
1248 if p.Child["any"] != nil {
1249 log.Printf("%s: mixed datasize keys: %v", p.Path, keys)
1250 }
1251
1252 if printing {
1253 fmt.Printf("/*%d*/\tuint16(xCondDataSize), %d, %d, %d,\n", pc, p.childPC("16"), p.childPC("32"), p.childPC("64"))
1254 }
1255 pc += 4
1256
1257 case "ismem":
1258 // Decode based on modrm form: memory or register reference.
1259 if len(keys) == 1 && keys[0] == "any" {
1260 next = p.Child["any"]
1261 break
1262 }
1263 if p.Child["any"] != nil {
1264 log.Printf("%s: mixed ismem keys: %v", p.Path, keys)
1265 }
1266
1267 if printing {
1268 fmt.Printf("/*%d*/\tuint16(xCondIsMem), %d, %d,\n", pc, p.childPC("0"), p.childPC("1"))
1269 }
1270 pc += 3
1271
1272 case "op":
1273 // Set opcode.
1274 ops[keys[0]] = true
1275 if printing {
1276 fmt.Printf("/*%d*/\tuint16(xSetOp), uint16(%s),\n", pc, keys[0])
1277 }
1278 next = p.Child[keys[0]]
1279 pc += 2
1280
1281 case "read":
1282 // Read argument bytes.
1283 if printing {
1284 fmt.Printf("/*%d*/\tuint16(xRead%s),\n", pc, xOp(keys[0]))
1285 }
1286 next = p.Child[keys[0]]
1287 pc++
1288
1289 case "arg":
1290 // Record instruction argument (interpret bytes loaded with read).
1291 if printing {
1292 fmt.Printf("/*%d*/\tuint16(xArg%s),\n", pc, xOp(keys[0]))
1293 }
1294 next = p.Child[keys[0]]
1295 pc++
1296
1297 case "match":
1298 // Finish match.
1299 if printing {
1300 fmt.Printf("/*%d*/\tuint16(xMatch),\n", pc)
1301 }
1302 pc++
1303 return pc
1304 }
1305
1306 if next != nil {
1307 pc = printDecoderPass(next, pc, printing, ops)
1308 }
1309
1310 for _, key := range keys {
1311 q := p.Child[key]
1312 if q.PC == 0 || q.PC == pc {
1313 pc = printDecoderPass(q, pc, printing, ops)
1314 }
1315 }
1316
1317 return pc
1318 }
1319
1320 // childPC returns the PC for the given child key.
1321 // If the key is not present, it returns PC 0,
1322 // which is known to be an xFail instruction.
1323 func (p *Prog) childPC(key string) int {
1324 q := p.Child[key]
1325 if q == nil {
1326 return 0
1327 }
1328 return q.PC
1329 }
1330
1331 // isLower reports whether c is an ASCII lower case letter.
1332 func isLower(c byte) bool {
1333 return 'a' <= c && c <= 'z'
1334 }
1335
1336 // isLetterDigit reports whether c is an ASCII letter or digit.
1337 func isLetterDigit(c byte) bool {
1338 return 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' || '0' <= c && c <= '9'
1339 }
1340
1341 // xOp converts arg, an Intel manual shorthand, into a decoder opcode suffix.
1342 // The standard form is LeadingUpperLetter with a few punctuation symbols
1343 // turned into purely lower case words: M16and32, M16colon32, CR0dashCR7.
1344 func xOp(arg string) string {
1345 var buf []byte
1346 for i := 0; i < len(arg); i++ {
1347 c := arg[i]
1348 if isLower(c) && (i == 0 || !isLetterDigit(arg[i-1])) {
1349 c -= 'a' - 'A'
1350 }
1351 buf = append(buf, c)
1352 }
1353 return argFix.Replace(string(buf))
1354 }
1355
1356 var argFix = strings.NewReplacer(
1357 "/R", "SlashR",
1358 "/", "",
1359 "<", "",
1360 ">", "",
1361 "+", "plus",
1362 "-", "dash",
1363 ":", "colon",
1364 "&", "and",
1365 "ST(0)", "ST",
1366 "ST(I)", "STi",
1367 "ST(I)+Op", "STi",
1368 )