aboutsummaryrefslogtreecommitdiff
path: root/src/armv7.rs
blob: 50cde071336fe6ce93943952390cb185b18e5dfd (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
//#[cfg(feature="use-serde")]
//use serde::{Serialize, Deserialize};

use std::fmt::{self, Display, Formatter};

use yaxpeax_arch::{Arch, Colorize, Decoder, LengthedInstruction, NoColors, ShowContextual, YaxColors};

pub struct ConditionedOpcode(pub Opcode, pub ConditionCode);

impl Display for ConditionedOpcode {
    fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
        write!(f, "{}{}", self.0, self.1)
    }
}

pub struct NoContext;

#[allow(non_snake_case)]
impl <T: fmt::Write, Color: fmt::Display, Y: YaxColors<Color>> ShowContextual<u32, NoContext, Color, T, Y> for Instruction {
    fn contextualize(&self, colors: &Y, _address: u32, _context: Option<&NoContext>, out: &mut T) -> fmt::Result {
        match self.opcode {
            Opcode::LDR(true, false, false) => {
                match self.operands {
                    Operands::TwoRegImm(13, Rt, 4) => {
                        ConditionedOpcode(Opcode::POP, self.condition).colorize(colors, out)?;
                        return write!(out, " {{{}}}", reg_name_colorize(Rt, colors));
                    },
                    _ => {}
                }
            },
            Opcode::STR(false, true, true) => {
                match self.operands {
                    Operands::TwoRegImm(13, Rt, 4) => {
                        ConditionedOpcode(Opcode::PUSH, self.condition).colorize(colors, out)?;
                        return write!(out, " {{{}}}", reg_name_colorize(Rt, colors));
                    },
                    _ => {}
                }
            },
            Opcode::LDM(true, false, true, _usermode) => {
                // TODO: what indicates usermode in the ARM syntax?
                match self.operands {
                    Operands::RegRegList(13, list) => {
                        ConditionedOpcode(Opcode::POP, self.condition).colorize(colors, out)?;
                        write!(out, " ")?;
                        return format_reg_list(out, list, colors);
                    }
                    _ => {}
                }
            }
            Opcode::STM(false, true, true, _usermode) => {
                // TODO: what indicates usermode in the ARM syntax?
                match self.operands {
                    Operands::RegRegList(13, list) => {
                        ConditionedOpcode(Opcode::PUSH, self.condition).colorize(colors, out)?;
                        write!(out, " ")?;
                        return format_reg_list(out, list, colors);
                    }
                    _ => {}
                }
            }
            _ => {}
        }

        match self.opcode {
            Opcode::LDR(add, pre, wback) |
            Opcode::STR(add, pre, wback) |
            Opcode::STRB(add, pre, wback) |
            Opcode::LDRB(add, pre, wback) => {
                match self.operands {
                    Operands::TwoRegImm(Rn, Rt, imm) => {
                        ConditionedOpcode(self.opcode, self.condition).colorize(colors, out)?;
                        write!(
                            out, " {}, ",
                            reg_name_colorize(Rt, colors),
                        )?;
                        return format_reg_imm_mem(out, Rn, imm, add, pre, wback, colors);
                    }
                    // TODO: this might not be necessary
                    Operands::RegImm(Rt, imm) => {
                        ConditionedOpcode(self.opcode, self.condition).colorize(colors, out)?;
                        write!(
                            out, " {}, ",
                            reg_name_colorize(Rt, colors)
                        )?;
                        return format_reg_imm_mem(out, 15, imm, add, pre, wback, colors);
                    },
                    Operands::ThreeOperandWithShift(Rd, Rn, Rm, shift) => {
                        ConditionedOpcode(self.opcode, self.condition).colorize(colors, out)?;
                        write!(
                            out, " {}, ",
                            reg_name_colorize(Rn, colors)
                        )?;
                        return format_reg_shift_mem(out, Rd, Rm, shift, add, pre, wback, colors);
                    }
                    _ => { unreachable!(); }
                }
            }
            // TODO: [add, pre, usermode]
            Opcode::STM(_add, _pre, wback, _usermode) |
            Opcode::LDM(_add, _pre, wback, _usermode) => {
                match self.operands {
                    Operands::RegRegList(Rr, list) => {
                        ConditionedOpcode(self.opcode, self.condition).colorize(colors, out)?;
                        write!(
                            out, " {}{}, ",
                            reg_name_colorize(Rr, colors),
                            if wback { "!" } else { "" }
                        )?;
                        return format_reg_list(out, list, colors);
                    },
                    _ => { unreachable!(); }
                }
            },
            Opcode::Incomplete(word) => {
                write!(out, "incomplete: {:#x}", word)
            },
            _ => {
                ConditionedOpcode(self.opcode, self.condition).colorize(colors, out)?;
                match self.operands {
                    Operands::RegisterList(list) => {
                        write!(out, " ")?;
                        format_reg_list(out, list, colors)?;
                    },
                    Operands::OneOperand(a) => {
                        write!(out, " {}", reg_name_colorize(a, colors))?;
                    },
                    Operands::TwoOperand(a, b) => {
                        write!(out, " {}, {}", reg_name_colorize(a, colors), reg_name_colorize(b, colors))?;
                    },
                    Operands::RegImm(a, imm) => {
                        write!(out, " {}, {:#x}", reg_name_colorize(a, colors), imm)?;
                    },
                    Operands::RegRegList(r, list) => {
                        write!(out, " {}, ", reg_name_colorize(r, colors))?;
                        format_reg_list(out, list, colors)?;
                    },
                    Operands::TwoRegImm(_a, _b, _imm) => {
                        // TODO:
                        write!(out, " <unimplemented>")?;
                    },
                    Operands::ThreeOperand(a, b, c) => {
                        write!(out, " {}, {}, {}", reg_name_colorize(a, colors), reg_name_colorize(b, colors), reg_name_colorize(c, colors))?;
                    },
                    Operands::ThreeOperandImm(_a, _b, _imm) => {
                        // TODO:
                        write!(out, " <unimplemented>")?;
                    },
                    Operands::ThreeOperandWithShift(a, b, c, shift) => {
                        write!(out, " {}, {}, ", reg_name_colorize(a, colors), reg_name_colorize(b, colors))?;
                        format_shift(out, c, shift, colors)?;
                    },
                    Operands::MulThreeRegs(a, b, c) => {
                        write!(out, " {}, {}, {}", reg_name_colorize(a, colors), reg_name_colorize(b, colors), reg_name_colorize(c, colors))?;
                    },
                    Operands::MulFourRegs(_a, _b, _c, _d) => {
                        // TODO:
                        write!(out, " <unimplemented>")?;
                    },
                    Operands::BranchOffset(imm) => {
                        if imm < 0 {
                            write!(out, " $-{:#x}", (-imm) * 4)?;
                        } else {
                            write!(out, " $+{:#x}", imm * 4)?;
                        }
                    }
                };
                Ok(())
            }
        }
    }
}

impl <T: fmt::Write, Color: fmt::Display, Y: YaxColors<Color>> Colorize<T, Color, Y> for ConditionedOpcode {
    fn colorize(&self, colors: &Y, out: &mut T) -> fmt::Result {
        match self.0 {
            Opcode::Incomplete(_) |
            Opcode::Invalid => { write!(out, "{}", colors.invalid_op(self)) },
            Opcode::B |
            Opcode::BL |
            Opcode::BLX |
            Opcode::BX |
            Opcode::BXJ => { write!(out, "{}", colors.control_flow_op(self)) },

            Opcode::AND |
            Opcode::EOR |
            Opcode::ORR |
            Opcode::LSL |
            Opcode::LSR |
            Opcode::ROR |
            Opcode::ASR |
            Opcode::RRX |
            Opcode::BIC |

            Opcode::ADR |
            Opcode::SUB |
            Opcode::RSB |
            Opcode::ADD |
            Opcode::ADC |
            Opcode::SBC |
            Opcode::RSC |

            Opcode::MUL |
            Opcode::MLA |
            Opcode::UMAAL |
            Opcode::MLS |
            Opcode::UMULL |
            Opcode::UMLAL |
            Opcode::SMULL |
            Opcode::SMLAL => { write!(out, "{}", colors.arithmetic_op(self)) },

            Opcode::PUSH |
            Opcode::POP => { write!(out, "{}", colors.stack_op(self)) },

            Opcode::TST |
            Opcode::TEQ |
            Opcode::CMP |
            Opcode::CMN => { write!(out, "{}", colors.comparison_op(self)) },

            Opcode::LDREXH |
            Opcode::STREXH |
            Opcode::LDREXB |
            Opcode::STREXB |
            Opcode::LDREXD |
            Opcode::STREXD |
            Opcode::LDREX |
            Opcode::STREX |
            Opcode::LDM(false, false, _, _) |
            Opcode::LDM(false, true, _, _) |
            Opcode::LDM(true, false, _, _) |
            Opcode::LDM(true, true, _, _) |
            Opcode::STM(false, false, _, _) |
            Opcode::STM(false, true, _, _) |
            Opcode::STM(true, false, _, _) |
            Opcode::STM(true, true, _, _) |
            Opcode::LDR(_, _, _) |
            Opcode::STR(_, _, _) |
            Opcode::LDRB(_, _, _) |
            Opcode::STRB(_, _, _) |
            Opcode::LDRT(_) |
            Opcode::STRT(_) |
            Opcode::LDRBT(_) |
            Opcode::STRBT(_) |
            Opcode::SWP |
            Opcode::SWPB |
            Opcode::MOV |
            Opcode::MVN => { write!(out, "{}", colors.data_op(self)) },
        }
    }
}

impl Display for Opcode {
    fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
        match self {
            Opcode::Incomplete(word) => { write!(f, "incomplete: {:#x}", word) },
            Opcode::Invalid => { write!(f, "invalid") },
            Opcode::POP => { write!(f, "pop") },
            Opcode::PUSH => { write!(f, "push") },
            Opcode::B => { write!(f, "b") },
            Opcode::BL => { write!(f, "bl") },
            Opcode::BLX => { write!(f, "blx") },
            Opcode::BX => { write!(f, "bx") },
            Opcode::BXJ => { write!(f, "bxj") },
            Opcode::AND => { write!(f, "and") },
            Opcode::EOR => { write!(f, "eor") },
            Opcode::SUB => { write!(f, "sub") },
            Opcode::RSB => { write!(f, "rsb") },
            Opcode::ADD => { write!(f, "add") },
            Opcode::ADC => { write!(f, "adc") },
            Opcode::SBC => { write!(f, "sbc") },
            Opcode::RSC => { write!(f, "rsc") },
            Opcode::TST => { write!(f, "tst") },
            Opcode::TEQ => { write!(f, "teq") },
            Opcode::CMP => { write!(f, "cmp") },
            Opcode::CMN => { write!(f, "cmn") },
            Opcode::ORR => { write!(f, "orr") },
            Opcode::MOV => { write!(f, "mov") },
            Opcode::BIC => { write!(f, "bic") },
            Opcode::MVN => { write!(f, "mvn") },
            Opcode::LSL => { write!(f, "lsl") },
            Opcode::LSR => { write!(f, "lsr") },
            Opcode::ASR => { write!(f, "asr") },
            Opcode::RRX => { write!(f, "rrx") },
            Opcode::ROR => { write!(f, "ror") },
            Opcode::ADR => { write!(f, "adr") },
            Opcode::LDREXH => { write!(f, "ldrexh") },
            Opcode::STREXH => { write!(f, "strexh") },
            Opcode::LDREXB => { write!(f, "ldrexb") },
            Opcode::STREXB => { write!(f, "strexb") },
            Opcode::LDREXD => { write!(f, "ldrexd") },
            Opcode::STREXD => { write!(f, "strexd") },
            Opcode::LDREX => { write!(f, "ldrex") },
            Opcode::STREX => { write!(f, "strex") },
            Opcode::LDM(false, false, _, _) => { write!(f, "ldmda") },
            Opcode::LDM(false, true, _, _) => { write!(f, "ldmdb") },
            Opcode::LDM(true, false, _, _) => { write!(f, "ldm") },
            Opcode::LDM(true, true, _, _) => { write!(f, "ldmia") },
            Opcode::STM(false, false, _, _) => { write!(f, "stmda") },
            Opcode::STM(false, true, _, _) => { write!(f, "stmdb") },
            Opcode::STM(true, false, _, _) => { write!(f, "stm") },
            Opcode::STM(true, true, _, _) => { write!(f, "stmia") },
            Opcode::LDR(_, _, _) => { write!(f, "ldr") },
            Opcode::STR(_, _, _) => { write!(f, "str") },
            Opcode::LDRB(_, _, _) => { write!(f, "ldrb") },
            Opcode::STRB(_, _, _) => { write!(f, "strb") },
            Opcode::LDRT(_) => { write!(f, "ldrt") },
            Opcode::STRT(_) => { write!(f, "strt") },
            Opcode::LDRBT(_) => { write!(f, "ldrbt") },
            Opcode::STRBT(_) => { write!(f, "strbt") },
            Opcode::SWP => { write!(f, "swp") },
            Opcode::SWPB => { write!(f, "swpb") },
            Opcode::MUL => { write!(f, "mul") },
            Opcode::MLA => { write!(f, "mla") },
            Opcode::UMAAL => { write!(f, "umaal") },
            Opcode::MLS => { write!(f, "mls") },
            Opcode::UMULL => { write!(f, "umull") },
            Opcode::UMLAL => { write!(f, "umlal") },
            Opcode::SMULL => { write!(f, "smull") },
            Opcode::SMLAL => { write!(f, "smlal") }
        }
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum Opcode {
    Incomplete(u32),
    Invalid,
    /*
     * These two don't really have direct encodings, but are for the specific instances
     * where the semantics of the original instruction are the same as push (specifically
     * ldm/stm/mov that write to the stack and increment/decrement appropriately
     */
    POP,
    PUSH,

    B,
    BL,
    BLX,
    BX,
    BXJ,
    AND,
    EOR,
    SUB,
    RSB,
    ADD,
    ADC,
    SBC,
    RSC,
    TST,
    TEQ,
    CMP,
    CMN,
    ORR,
    MOV,
    BIC,
    MVN,
    LSL,
    LSR,
    ASR,
    RRX,
    ROR,
    ADR,
    LDREXH,
    STREXH,
    LDREXB,
    STREXB,
    LDREXD,
    STREXD,
    LDREX,
    STREX,
    LDM(bool, bool, bool, bool),
    STM(bool, bool, bool, bool),
    LDR(bool, bool, bool),
    STR(bool, bool, bool),
    LDRB(bool, bool, bool),
    STRB(bool, bool, bool),
    LDRT(bool),
    STRT(bool),
    LDRBT(bool),
    STRBT(bool),
    SWP,
    SWPB,
    MUL,
    MLA,
    UMAAL,
    MLS,
    UMULL,
    UMLAL,
    SMULL,
    SMLAL
}

static DATA_PROCESSING_OPCODES: [Opcode; 16] = [
    Opcode::AND,
    Opcode::EOR,
    Opcode::SUB,
    Opcode::RSB,
    Opcode::ADD,
    Opcode::ADC,
    Opcode::SBC,
    Opcode::RSC,
    Opcode::TST,
    Opcode::TEQ,
    Opcode::CMP,
    Opcode::CMN,
    Opcode::ORR,
    Opcode::MOV,
    Opcode::BIC,
    Opcode::MVN
];

#[derive(Debug, PartialEq, Eq, Copy, Clone)]
pub enum ShiftSpec {
    Immediate(u8),
    Register(u8)
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Operands {
    RegisterList(u16),
    OneOperand(u8),
    TwoOperand(u8, u8),
    RegImm(u8, u32),
    RegRegList(u8, u16),
    TwoRegImm(u8, u8, u32),
    ThreeOperand(u8, u8, u8),
    ThreeOperandImm(u8, u8, u16),
    ThreeOperandWithShift(u8, u8, u8, ShiftSpec),
    MulThreeRegs(u8, u8, u8),
    MulFourRegs(u8, u8, u8, u8),
    BranchOffset(i32)
}

#[derive(Debug, PartialEq, Eq)]
pub struct Instruction {
    pub condition: ConditionCode,
    pub opcode: Opcode,
    pub operands: Operands,
    pub s: bool
}

#[derive(Debug, PartialEq)]
pub enum DecodeError {
    ExhaustedInput,
    InvalidOpcode,
    InvalidOperand,
    Incomplete,
}

impl fmt::Display for DecodeError {
    fn fmt(&self, f:  &mut fmt::Formatter) -> fmt::Result {
        match self {
            DecodeError::ExhaustedInput => write!(f, "exhausted input"),
            DecodeError::InvalidOpcode => write!(f, "invalid opcode"),
            DecodeError::InvalidOperand => write!(f, "invalid operand"),
            DecodeError::Incomplete => write!(f, "incomplete decoder"),
        }
    }
}

impl yaxpeax_arch::DecodeError for DecodeError {
    fn data_exhausted(&self) -> bool { self == &DecodeError::ExhaustedInput }
    fn bad_opcode(&self) -> bool { self == &DecodeError::InvalidOpcode }
    fn bad_operand(&self) -> bool { self == &DecodeError::InvalidOperand }
}

impl yaxpeax_arch::Instruction for Instruction {
    // TODO: this is wrong!!
    fn well_defined(&self) -> bool { true }
}

impl Default for Instruction {
    fn default() -> Self {
        Instruction {
            condition: ConditionCode::AL,
            opcode: Opcode::Invalid,
            operands: Operands::BranchOffset(0),
            s: false
        }
    }
}

impl Instruction {
    fn set_s(&mut self, value: bool) {
        self.s = value;
    }
    pub fn s(&self) -> bool { self.s }
}

fn format_reg_list<T: fmt::Write, C: fmt::Display, Y: YaxColors<C>>(f: &mut T, mut list: u16, colors: &Y) -> Result<(), fmt::Error> {
    write!(f, "{{")?;
    let mut i = 0;
    let mut tail = false;
    while i < 16 {
        let present = (list & 1) == 1;
        if present {
            if tail {
                write!(f, ", ")?;
            } else {
                tail = true;
            }
            write!(f, "{}", reg_name_colorize(i, colors))?;
        }
        i += 1;
        list >>= 1;
    }
    write!(f, "}}")
}

#[allow(non_snake_case)]
fn format_shift<T: fmt::Write, C: fmt::Display, Y: YaxColors<C>>(f: &mut T, Rm: u8, shift: ShiftSpec, colors: &Y) -> Result<(), fmt::Error> {
    fn shift_tpe_to_str(tpe: u8) -> &'static str {
        match tpe {
            0b00 => "lsl",
            0b01 => "lsr",
            0b10 => "asr",
            0b11 => "ror",
            _ => { unreachable!(); }
        }
    }
    match shift {
        ShiftSpec::Immediate(0) => {
            write!(f, "{}", reg_name_colorize(Rm, colors))
        },
        ShiftSpec::Immediate(v) => {
            let tpe = v & 0x3;
            let imm = v >> 2;
            write!(f, "{}, {} {}", reg_name_colorize(Rm, colors), shift_tpe_to_str(tpe), imm)
        },
        ShiftSpec::Register(v) => {
            let tpe = v & 0x3;
            let Rs = v >> 3;
            write!(f, "{}, {} {}", reg_name_colorize(Rm, colors), shift_tpe_to_str(tpe), reg_name_colorize(Rs, colors))
        },
    }
}

#[allow(non_snake_case)]
fn format_reg_shift_mem<T: fmt::Write, C: fmt::Display, Y: YaxColors<C>>(f: &mut T, Rd: u8, Rm: u8, shift: ShiftSpec, add: bool, pre: bool, wback: bool, colors: &Y) -> Result<(), fmt::Error> {
    let op = if add { "" } else { "-" };

    match (pre, wback) {
        (true, true) => {
            write!(f, "[{}, {}", reg_name_colorize(Rd, colors), op)?;
            format_shift(f, Rm, shift, colors)?;
            write!(f, "]!")
        },
        (true, false) => {
            write!(f, "[{}, {}", reg_name_colorize(Rd, colors), op)?;
            format_shift(f, Rm, shift, colors)?;
            write!(f, "]")
        },
        (false, true) => {
            unreachable!("I don't know how to render an operand with pre==false and wback==true, this seems like it should be LDRT");
        },
        (false, false) => {
            write!(f, "[{}], {}", reg_name_colorize(Rd, colors), op)?;
            format_shift(f, Rm, shift, colors)
        }
    }
}

#[allow(non_snake_case)]
fn format_reg_imm_mem<T: fmt::Write, C: fmt::Display, Y: YaxColors<C>>(f: &mut T, Rn: u8, imm: u32, add: bool, pre: bool, wback: bool, colors: &Y) -> Result<(), fmt::Error> {
    if imm != 0 {
        let op = if add { "" } else { "-" };

        match (pre, wback) {
            (true, true) => {
                write!(f, "[{}, #{}{:#x}]!", reg_name_colorize(Rn, colors), op, imm * 4)
            },
            (true, false) => {
                write!(f, "[{}, #{}{:#x}]", reg_name_colorize(Rn, colors), op, imm * 4)
            },
            (false, true) => {
                unreachable!("I don't know how to render an operand with pre==false and wback==true, this seems like it should be LDRT");
            },
            (false, false) => {
                write!(f, "[{}], #{}{:#x}", reg_name_colorize(Rn, colors), op, imm * 4)
            }
        }
    } else {
        match (pre, wback) {
            (true, true) => {
                write!(f, "[{}]!", reg_name_colorize(Rn, colors))
            },
            (true, false) => {
                write!(f, "[{}]", reg_name_colorize(Rn, colors))
            },
            (false, true) => {
                unreachable!("I don't know how to render an operand with pre==false and wback==true, this seems like it should be LDRT");
            },
            (false, false) => {
                write!(f, "[{}]", reg_name_colorize(Rn, colors))
            }
        }
    }
}
fn reg_name_colorize<C: fmt::Display, Y: YaxColors<C>>(num: u8, colors: &Y) -> impl fmt::Display {
    match num {
        0 => colors.register("r0"),
        1 => colors.register("r1"),
        2 => colors.register("r2"),
        3 => colors.register("r3"),
        4 => colors.register("r4"),
        5 => colors.register("r5"),
        6 => colors.register("r6"),
        7 => colors.register("r7"),
        8 => colors.register("r8"),
        9 => colors.register("sb"),
        10 => colors.register("r10"),
        11 => colors.register("fp"),
        12 => colors.register("ip"),
        13 => colors.register("sp"),
        14 => colors.register("lr"),
        15 => colors.program_counter("pc"),
        _ => { unreachable!(); }
    }
}

impl Display for Instruction {
    fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
        self.contextualize(&NoColors, 0, Some(&NoContext), f)
    }
}

impl LengthedInstruction for Instruction {
    type Unit = <ARMv7 as Arch>::Address;
    fn min_size() -> Self::Unit {
        4
    }
    fn len(&self) -> Self::Unit {
        4
    }
}

#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum ConditionCode {
    EQ,
    NE,
    HS,
    LO,
    MI,
    PL,
    VS,
    VC,
    HI,
    LS,
    GE,
    LT,
    GT,
    LE,
    AL
}

impl Display for ConditionCode {
    fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
        match self {
            ConditionCode::EQ => write!(f, "eq"),
            ConditionCode::NE => write!(f, "ne"),
            ConditionCode::HS => write!(f, "hs"),
            ConditionCode::LO => write!(f, "lo"),
            ConditionCode::MI => write!(f, "mi"),
            ConditionCode::PL => write!(f, "pl"),
            ConditionCode::VS => write!(f, "vs"),
            ConditionCode::VC => write!(f, "vc"),
            ConditionCode::HI => write!(f, "hi"),
            ConditionCode::LS => write!(f, "ls"),
            ConditionCode::GE => write!(f, "ge"),
            ConditionCode::LT => write!(f, "lt"),
            ConditionCode::GT => write!(f, "gt"),
            ConditionCode::LE => write!(f, "le"),
            ConditionCode::AL => Ok(())
        }
    }
}

impl ConditionCode {
    pub fn build(value: u8) -> ConditionCode {
        match value {
            0b0000 => ConditionCode::EQ,
            0b0001 => ConditionCode::NE,
            0b0010 => ConditionCode::HS,
            0b0011 => ConditionCode::LO,
            0b0100 => ConditionCode::MI,
            0b0101 => ConditionCode::PL,
            0b0110 => ConditionCode::VS,
            0b0111 => ConditionCode::VC,
            0b1000 => ConditionCode::HI,
            0b1001 => ConditionCode::LS,
            0b1010 => ConditionCode::GE,
            0b1011 => ConditionCode::LT,
            0b1100 => ConditionCode::GT,
            0b1101 => ConditionCode::LE,
            0b1110 => ConditionCode::AL,
            _ => {
                // this means the argument `value` must never be outside [0,15]
                // which itself means this function shouldn't be public
                unreachable!();
            }
        }
    }
}

#[derive(Default, Debug)]
pub struct InstDecoder {}

#[allow(non_snake_case)]
impl Decoder<Instruction> for InstDecoder {
    type Error = DecodeError;

    fn decode_into<T: IntoIterator<Item=u8>>(&self, inst: &mut Instruction, bytes: T) -> Result<(), Self::Error> {
        fn read_word<T: IntoIterator<Item=u8>>(bytes: T) -> Result<u32, DecodeError> {
            let mut iter = bytes.into_iter();
            let instr: u32 =
                ((iter.next().ok_or(DecodeError::ExhaustedInput)? as u32)      ) |
                ((iter.next().ok_or(DecodeError::ExhaustedInput)? as u32) << 8 ) |
                ((iter.next().ok_or(DecodeError::ExhaustedInput)? as u32) << 16) |
                ((iter.next().ok_or(DecodeError::ExhaustedInput)? as u32) << 24);

            Ok(instr)
        }

        let word = read_word(bytes)?;

        let (cond, opc_upper) = {
            let top_byte = word >> 24;
            (
                ((top_byte >> 4) & 0xf) as u8,
                ((top_byte >> 1) & 0x7) as u8
            )
        };

        if cond == 0b1111 {
            // do unconditional instruction stuff
            inst.condition = ConditionCode::AL;
            let op1 = (word >> 20) as u8;
            if op1 > 0x80 {
                match (op1 >> 5) & 0b11 {
                    0b00 => {
                        inst.opcode = Opcode::Incomplete(word);
                    }
                    0b01 => {
                        inst.opcode = Opcode::BLX;
                        let operand = ((word & 0xffffff) as i32) << 8 >> 6;
                        inst.operands = Operands::BranchOffset(
                            operand | (
                                ((word >> 23) & 0b10) as i32
                            )
                        );
                    }
                    0b10 => {
                        inst.opcode = Opcode::Incomplete(word);
                    }
                    0b11 => {
                        inst.opcode = Opcode::Incomplete(word);
                    }
                    _ => {
                        unreachable!();
                    }
                }
            } else {
                inst.opcode = Opcode::Incomplete(word);
            }
            return Ok(());
        } else {
            inst.condition = ConditionCode::build(cond);
        }

        // distinction at this point is on page A5-192
        match opc_upper {
            0b000 => {
                // the instruction looks like
                // |c o n d|0 0 0|x x x x|x|x x x x|x x x x|x x x x x|x x|x|x x x x|
                let (s, opcode) = {
                    let part = word >> 20;
                    (
                        (part & 0x01) == 1,
                        ((part >> 1) & 0x0f) as u8
                    )
                };

                if (word & 0b10010000) == 0b10010000 {
                    // the instruction looks like
                    // |c o n d|0 0 0|x x x x|x|x x x x|x x x x|x x x x 1|x x|1|x x x x|
                    // which is a category of multiplies and extra load/store
                    if (word & 0x0f0000f0) == 0x00000090 {
                    // |c o n d|0 0 0 0|x x x x x x x x x x x x x x x x|1 0 0 1|x x x x|
                        // Multiply instruction extension space
                        // (page A5-200)
                        let op = ((word >> 20) & 0x0f) as u8;
                        let s = (op & 1) == 1;
                        let op = op >> 1;
                        let R = [
                            (word & 0x0f) as u8,
                            ((word >> 8) & 0x0f) as u8,
                            ((word >> 12) & 0x0f) as u8,
                            ((word >> 16) & 0x0f) as u8
                        ];
                        inst.set_s(s);
                        match op {
                            0b000 => {
                                inst.opcode = Opcode::MUL;
                                inst.operands = Operands::MulThreeRegs(R[3], R[0], R[1]);
                            },
                            0b001 => {
                                inst.opcode = Opcode::MLA;
                                inst.operands = Operands::MulFourRegs(R[3], R[0], R[1], R[2]);
                            },
                            0b010 => {
                                if s {
                                    inst.opcode = Opcode::Invalid;
                                    return Err(DecodeError::InvalidOpcode);
                                }
                                inst.opcode = Opcode::UMAAL;
                                inst.operands = Operands::MulFourRegs(R[2], R[3], R[0], R[1]);
                            },
                            0b011 => {
                                if s {
                                    inst.opcode = Opcode::Invalid;
                                    return Err(DecodeError::InvalidOpcode);
                                }
                                inst.opcode = Opcode::MLS;
                                inst.operands = Operands::MulFourRegs(R[3], R[0], R[1], R[2]);
                            }
                            0b100 => {
                                inst.opcode = Opcode::UMULL;
                                inst.operands = Operands::MulFourRegs(R[2], R[3], R[0], R[1]);
                            }
                            0b101 => {
                                inst.opcode = Opcode::UMLAL;
                                inst.operands = Operands::MulFourRegs(R[2], R[3], R[0], R[1]);
                            }
                            0b110 => {
                                inst.opcode = Opcode::SMULL;
                                inst.operands = Operands::MulFourRegs(R[2], R[3], R[0], R[1]);
                            }
                            0b111 => {
                                inst.opcode = Opcode::SMLAL;
                                inst.operands = Operands::MulFourRegs(R[2], R[3], R[0], R[1]);
                            }
                            _ => { unreachable!(format!("mul upcode: {:x}", op)) }
                        }
                    } else {
                    // |c o n d|0 0 0 u|x x x x x x x x x x x x x x x x|1 u u 1|x x x x|
                    // with at least one of u being 1
                    // misc instructions
                        let (flags, Rn, Rd, HiOffset, op, LoOffset) = {
                            let LoOffset = (word & 0x0f) as u8;
                            let word = word >> 5;
                            let op = (word & 0x3) as u8;
                            let word = word >> 3;
                            let HiOffset = (word & 0x0f) as u8;
                            let word = word >> 4;
                            let Rd = (word & 0x0f) as u8;
                            let word = word >> 4;
                            let Rn = (word & 0x0f) as u8;
                            let word = word >> 4;
                            let flags = (word & 0x1f) as u8;
                            (flags, Rn, Rd, HiOffset, op, LoOffset)
                        };
                        println!("{:032b}", word);
                        println!("       {:05b}|{:04b}|{:04b}|{:04b}|1{:02b}1|{:04b}", flags, Rn, Rd, HiOffset, op, LoOffset);
                        match op {
                            0b00 => {
                    // |c o n d|0 0 0 1|x x x x x x x x x x x x x x x x|1 0 0 1|x x x x|
                                // this is swp or {ld,st}ex, conditional on bit 23
                                match flags {
                                    0b10000 => {
                                        inst.opcode = Opcode::SWP;
                                        inst.operands = Operands::ThreeOperand(Rn, Rd, LoOffset);
                                    },
                                    0b10001 | 0b10010 | 0b10011 => {
                                        inst.opcode = Opcode::Invalid;
                                        return Err(DecodeError::InvalidOpcode);
                                    }
                                    0b10100 => {
                                        inst.opcode = Opcode::SWPB;
                                        inst.operands = Operands::ThreeOperand(Rn, Rd, LoOffset);
                                    },
                                    0b10101 | 0b10110 | 0b10111 => {
                                        inst.opcode = Opcode::Invalid;
                                        return Err(DecodeError::InvalidOpcode);
                                    }
                                    0b11000 => {
                                        inst.opcode = Opcode::STREX;
                                        inst.operands = Operands::ThreeOperand(Rn, Rd, LoOffset);
                                    }
                                    0b11001 => {
                                        inst.opcode = Opcode::LDREX;
                                        inst.operands = Operands::ThreeOperand(Rn, Rd, LoOffset);
                                    }
                                    0b11010 => {
                                        inst.opcode = Opcode::STREXD;
                                        inst.operands = Operands::ThreeOperand(Rn, Rd, LoOffset);
                                    }
                                    0b11011 => {
                                        inst.opcode = Opcode::LDREXD;
                                        inst.operands = Operands::ThreeOperand(Rn, Rd, LoOffset);
                                    }
                                    0b11100 => {
                                        inst.opcode = Opcode::STREXB;
                                        inst.operands = Operands::ThreeOperand(Rn, Rd, LoOffset);
                                    }
                                    0b11101 => {
                                        inst.opcode = Opcode::LDREXB;
                                        inst.operands = Operands::ThreeOperand(Rn, Rd, LoOffset);
                                    }
                                    0b11110 => {
                                        inst.opcode = Opcode::STREXH;
                                        inst.operands = Operands::ThreeOperand(Rn, Rd, LoOffset);
                                    }
                                    0b11111 => {
                                        inst.opcode = Opcode::LDREXH;
                                        inst.operands = Operands::ThreeOperand(Rn, Rd, LoOffset);
                                    }
                                    _ => {
                                        /*
                                         * This is unreachable because we have checked op is b1001,
                                         * meaning the high bit of flags *MUST* be 1.
                                         *
                                         * high bit and mid-bits of op all being 0 was checked
                                         * before reaching here.
                                         */
                                        unreachable!(format!("load/store flags: {:x}", flags));
                                    }
                                }
                            }
                            0b01 => {
                    // |c o n d|0 0 0 x|x x x x x x x x x x x x x x x x|1 0 1 1|x x x x|
                    // page A5-201
                                inst.opcode = Opcode::Incomplete(word);
                                // return Some(());
                                match flags {
                                    0b00010 => {
                                        // inst.opcode = Opcode::STRHT_sub;
                                        inst.opcode = Opcode::Incomplete(word);
                                        inst.operands = Operands::ThreeOperand(Rn, Rd, LoOffset);
                                    }
                                    0b01010 => {
                                        // inst.opcode = Opcode::STRHT_add;
                                        inst.opcode = Opcode::Incomplete(word);
                                        inst.operands = Operands::ThreeOperand(Rn, Rd, LoOffset);
                                    }
                                    0b00110 => {
                                        // inst.opcode = Opcode::STRHT_sub;
                                        inst.opcode = Opcode::Incomplete(word);
                                        let imm = (HiOffset << 4) as u16 | LoOffset as u16;
                                        inst.operands = Operands::ThreeOperandImm(Rn, Rd, imm);
                                    }
                                    0b01110 => {
                                        // inst.opcode = Opcode::STRHT_add;
                                        inst.opcode = Opcode::Incomplete(word);
                                        let imm = (HiOffset << 4) as u16 | LoOffset as u16;
                                        inst.operands = Operands::ThreeOperandImm(Rn, Rd, imm);
                                    }
                                    _ => {
                                        return Err(DecodeError::Incomplete);
//                                        unreachable!();
                                    }
                                }
                                return Err(DecodeError::Incomplete);
//                                panic!("page a5-201");
                            }
                            0b10 => {
                    // |c o n d|0 0 0 x|x x x x x x x x x x x x x x x x|1 1 0 1|x x x x|
                    // page A5-201
                                inst.opcode = Opcode::Incomplete(word);
                                return Ok(());
                            }
                            0b11 => {
                    // |c o n d|0 0 0 x|x x x x x x x x x x x x x x x x|1 1 1 1|x x x x|
                    // page A5-201
                                inst.opcode = Opcode::Incomplete(word);
                                return Ok(());
                            }
                            _ => { unreachable!(); }
                        }
                    }
                } else {
                    // we know this is data processing with imm or reg shift, OR
                    // misc instructions in Figure A3-4

                    if s == false && opcode >= 0b1000 && opcode < 0b1100 {
                        let op2 = ((word >> 4) & 0x0f) as u8;
                        // the instruction looks like
                        // |c o n d|0 0 0|1 0 x x|0|x x x x|x x x x|x x x x x|x x|x|x x x x|
                        if op2 & 0x08 == 0x00 {
                            let op2 = op2 & 0x07;
                            // |c o n d|0 0 0|1 0 x x|0|x x x x|x x x x|x x x x|0|x x|x|x x x x|
                            // misc instructions (page A5-194)
                            match op2 {
                                0b000 => {
                                    
                                },
                                0b001 => {
                                    
                                },
                                0b010 => {
                                    
                                },
                                0b011 => {
                                    if opcode & 0b11 == 0b01 {
                                        inst.opcode = Opcode::BLX;
                                        inst.operands = Operands::OneOperand((word & 0x0f) as u8);
                                        return Ok(());
                                    } else {
                                        return Err(DecodeError::InvalidOpcode);
                                    }
                                },
                                0b100 => {
                                    inst.opcode = Opcode::Incomplete(word);
                                    return Ok(());
                                },
                                0b101 => {

                                }
                                0b110 => {
                                },
                                0b111 => {

                                },
                                _ => {
                                    unreachable!();
                                }
                            }
                        } else {
                            // |c o n d|0 0 0|1 0 x x|0|x x x x|x x x x|x x x x|1|x x|x|x x x x|
                            // multiply and multiply-accumulate 
                            inst.opcode = Opcode::Incomplete(word);
                            return Ok(());
                        }
                    } else {
                        if opcode >= 16 {
                            unreachable!();
                        }
                        inst.opcode = DATA_PROCESSING_OPCODES[opcode as usize];
                        inst.set_s(s);

                        // at this point we know this is a data processing instruction
                        // either immediate shift or register shift
                        if word & 0b00010000 == 0 {
                    // |c o n d|0 0 0|1 0 x x|0|x x x x|x x x x|x x x x x|x x|0|x x x x|
                    // interpret the operands as
                    // | Rn | Rd | shift amount | shift | 0 | Rm |
                            let (Rn, Rd, shift_spec, Rm) = {
                                let Rm = (word & 0x0f) as u8;
                                let word = word >> 5;
                                let shift_spec = (word & 0x7f) as u8;
                                let word = word >> 7;
                                let Rd = (word & 0x0f) as u8;
                                let Rn = ((word >> 4) & 0x0f) as u8;
                                (Rn, Rd, shift_spec, Rm)
                            };

                            if shift_spec == 0 {
                                if (0b1101 & opcode) == 0b1101 {
                                    // MOV or MVN
                                    inst.operands = Operands::TwoOperand(Rd, Rm);
                                } else {
                                    inst.operands = Operands::ThreeOperand(Rd, Rn, Rm);
                                }
                            } else {
                                /*
                                 * TODO: look at how this interacts with mov and mvn
                                 */
                                inst.operands = Operands::ThreeOperandWithShift(Rd, Rn, Rm, ShiftSpec::Immediate(shift_spec));
                            }
                        } else {
                    //    known 0 because it and bit 5 are not both 1 --v
                    // |c o n d|0 0 0|1 0 x x|0|x x x x|x x x x|x x x x 0|x x|1|x x x x|
                            // interpret the operands as
                            // | Rn | Rd | Rs | 0 | shift | 1 | Rm |
                            let (Rn, Rd, shift_spec, Rm) = {
                                let Rm = (word & 0x0f) as u8;
                                let word = word >> 5;
                                let shift_spec = (word & 0x7f) as u8;
                                let word = word >> 7;
                                let Rd = (word & 0x0f) as u8;
                                let Rn = ((word >> 4) & 0x0f) as u8;
                                (Rn, Rd, shift_spec, Rm)
                            };
                            // page A5-200 indicates that saturating add and subtract should be
                            // here?
                            if (0b1101 & opcode) == 0b1101 {
                                // these are all invalid
                                inst.opcode = Opcode::Invalid;
                                return Err(DecodeError::InvalidOpcode);
                            } else {
                                inst.operands = Operands::ThreeOperandWithShift(Rd, Rn, Rm, ShiftSpec::Register(shift_spec));
                            }
                        }
                    }
                }
            },
            0b001 => {
                // the instruction looks like
                // |c o n d|0 0 1|x x x x|x|x x x x|x x x x|x x x x x|x x|x|x x x x|
                // bottom part of table A5-2 on page A5-194
                let (s, opcode) = {
                    let part = word >> 20;
                    (
                        (part & 0x01) == 1,
                        ((part >> 1) & 0x0f) as u8
                    )
                };
                if s == false && opcode >= 0b1000 && opcode < 0b1100 {
                // the instruction looks like
                // |c o n d|0 0 0|1 0 x x|0|x x x x|x x x x|x x x x x|x x|x|x x x x|
                // misc instructions (page A5-194)
                    inst.opcode = Opcode::Incomplete(word);
                    return Ok(());
                } else {
                    if opcode >= 16 {
                        unreachable!();
                    }
                    inst.opcode = DATA_PROCESSING_OPCODES[opcode as usize];
                    inst.set_s(s);

                    let (Rn, imm) = {
                        let imm = word & 0x0000ffff;
                        let word = word >> 16;
                        ((word & 0x0f) as u8, imm)
                    };
                    if (opcode == 0b0010 || opcode == 0b0100) && Rn == 0b1111 {
                        inst.opcode = Opcode::ADR;
                    }
                    match opcode {
                        0b1101 => {
                            inst.operands = Operands::RegImm(
                                ((word >> 12) & 0xf) as u8,
                                (word & 0x0fff) as u32
                            );
                        }
                        _ => {
                            inst.operands = Operands::RegImm(Rn, imm);
                        }
                    }

                }
                /* ... */
            }
            0b010 => {
                let Rn = ((word >> 16) & 0x0f) as u8;
                let op = ((word >> 20) & 0x1f) as u8;
                let add = (op & 0b01000) != 0;
                let (imm, Rt) = {
                    ((word & 0x0fff) as u16, ((word >> 12) & 0x0f) as u8)
                };
                if (op & 0b10010) == 0b00010 {
                    let op = op & 0b00111;
                // |c o n d|0 1 0|0 x x 1 x|x x x x x x x x x x x x x x x|x|x x x x|
                    /*
                    0x010 -> STRT
                    0x011 -> LDRT
                    0x110 -> STRBT
                    0x111 -> LDRBT
                    */
                    inst.opcode = match op {
                        0b010 => Opcode::STRT(add),
                        0b011 => Opcode::LDRT(add),
                        0b110 => Opcode::STRBT(add),
                        0b111 => Opcode::LDRBT(add),
                        _ => { unreachable!(); }
                    };
                } else {
                    /*
                    xx0x0 not 0x010 -> STR (imm)
                    xx0x1 not 0x011 -> LDR (imm)
                    xx1x0 not 0x110 -> STRB (imm)
                    xx1x1 not 0x111 -> LDRB (imm)
                    */
                    let pre = (op & 0b10000) != 0;
                    let wback = (op & 0b00010) != 0;
                    let op = op & 0b00101;
                    inst.opcode = match op {
                        0b000 => Opcode::STR(add, pre, wback),
                        0b001 => {
                            if Rn == 0b1111 {
                                inst.operands = Operands::RegImm(Rt, imm.into());
                                inst.opcode = Opcode::LDR(add, pre, wback);
                                return Ok(());
                            }
                            Opcode::LDR(add, pre, wback)
                        },
                        0b100 => Opcode::STRB(add, pre, wback),
                        0b101 => {
                            if Rn == 0b1111 {
                                inst.operands = Operands::RegImm(Rt, imm.into());
                                inst.opcode = Opcode::LDRB(add, pre, wback);
                                return Ok(());
                            }
                            Opcode::LDRB(add, pre, wback)
                        },
                        _ => { unreachable!(); }
                    };
                }
                inst.operands = Operands::TwoRegImm(Rn, Rt, imm.into());
            },
            0b011 => {
                // page A5-192 to distinguish the following:
                // check for media instructions, and if not, load/store word and unsigned byte
                if (word & 0x00000010) != 0 {
                // |c o n d|0 1 1|x x x x|x|x x x x|x x x x|x x x x x|x x|1|x x x x|
                    // using language from A5-206: A == 1 and B == 1
                    // so this is media instructions (A5-207)
                } else {
                // |c o n d|0 1 1|x x x x|x|x x x x|x x x x|x x x x x|x x|0|x x x x|
                    // instructions here are A == 1, B == 0 in A5-206
                    let op = ((word >> 20) & 0x1f) as u8;

                    let add = (op & 0b01000) != 0;
                    /*
                        xx0x0 not 0x010 -> STR (register)
                        0x010 -> STRT
                        xx0x1 not 0x011 -> LDR (register)
                        0x011 -> LDRT
                        xx1x0 not 0x110 -> STRB (register)
                        0x110 -> STRBT
                        xx1x1 not 0x111 -> LDRB (register)
                        0x111 -> LDRBT
                    */
                    let Rn = ((word >> 16) & 0x0f) as u8;
                    if (op & 0b10010) == 0b00010 {
                        let op = op & 0b00111;
                // |c o n d|0 1 1|0 x x 1 x|x x x x x x x x x x x x x x x|0|x x x x|
                        /*
                        0x010 -> STRT
                        0x011 -> LDRT
                        0x110 -> STRBT
                        0x111 -> LDRBT
                        */
                        inst.opcode = match op {
                            0b010 => Opcode::STRT(add),
                            0b011 => Opcode::LDRT(add),
                            0b110 => Opcode::STRBT(add),
                            0b111 => Opcode::LDRBT(add),
                            _ => { unreachable!(); }
                        };
                    } else {
                        /*
                        xx0x0 not 0x010 -> STR (imm)
                        xx0x1 not 0x011 -> LDR (imm)
                        xx1x0 not 0x110 -> STRB (imm)
                        xx1x1 not 0x111 -> LDRB (imm)
                        */
                        let pre = (op & 0b10000) != 0;
                        let wback = (op & 0b00010) != 0;
                        let op = op & 0b00101;
                        inst.opcode = match op {
                            0b000 => Opcode::STR(add, pre, wback),
                            0b001 => Opcode::LDR(add, pre, wback),
                            0b100 => Opcode::STRB(add, pre, wback),
                            0b101 => Opcode::LDRB(add, pre, wback),
                            _ => { unreachable!(); }
                        };
                    }
                    let (Rt, Rm, shift) = {
                        let Rm = (word & 0xf) as u8;
                        let word = word >> 5;
                        let shift = (word & 0x7f) as u8;
                        let word = word >> 7;
                        let Rt = (word & 0xf) as u8;
                        (Rt, Rm, shift)
                    };
                    inst.operands = Operands::ThreeOperandWithShift(Rn, Rt, Rm, ShiftSpec::Immediate(shift));
                }
                return Ok(());
            },
            0b100 | 0b101 => {
                // branch, branch with link, and block data transfer
                // page A5-212
                let op = (word >> 20) & 0x3f;
                if op < 0b100000 {
                    let wback = (op & 0b000010) != 0;
                    let add = (op & 0b001000) != 0;
                    let pre = (op & 0b010000) != 0;
                    let usermode = (op & 0b000100) != 0;
                    inst.opcode = if (op & 1) == 0 {
                            Opcode::STM(add, pre, wback, usermode)
                        } else {
                            Opcode::LDM(add, pre, wback, usermode)
                        };
                    inst.operands = Operands::RegRegList(
                        ((word >> 16) & 0xf) as u8,
                        (word & 0xffff) as u16
                    );
                } else if op < 0b110000 {
                    // 10xxxx
                    // the + 1 is to compensate for an architecturally-defined initial offset
                    inst.opcode = Opcode::B;
                    inst.operands = Operands::BranchOffset(((word & 0x00ffff) + 1) as i16 as i32);
                } else {
                    // 11xxxx
                    // the + 1 is to compensate for an architecturally-defined initial offset
                    inst.opcode = Opcode::BL;
                    inst.operands = Operands::BranchOffset(((word & 0x00ffff) + 1) as i16 as i32);
                }
            },
            0b110 | 0b111 => {
                // coprocessor instructions and supervisor call
                // page A5-213
                inst.opcode = Opcode::Incomplete(word);
                return Ok(());
            },
            _ => { unreachable!(); }
        }
        Ok(())
    }
}

#[cfg(feature="use-serde")]
#[derive(Debug, Serialize, Deserialize)]
pub struct ARMv7;

#[cfg(not(feature="use-serde"))]
#[derive(Debug)]
pub struct ARMv7;

impl Arch for ARMv7 {
    type Address = u32;
    type Instruction = Instruction;
    type DecodeError = DecodeError;
    type Decoder = InstDecoder;
    type Operand = Operands;
}


/*
 * tests: (armv7?)
 * [0x00, 0x00, 0x90, 0xe0]
 * adds r0, r0, r0
 *
 * [0x00, 0x00, 0x82, 0xe0]
 * add r0, r2, r0
 *
 * [0x00, 0x00, 0x88, 0xe0]
 * add r0, r8, r0
 *
 * [0x00, 0x01, 0x80, 0xe0]
 * add r0, r0, r0, lsl 2
 *
 * [0x00, 0x80, 0x00, 0x00]
 * andeq r8, r0, r0
 *
 * [0xc0, 0x80, 0x20, 0x00]
 * eoreq r8, r0, r0, asr 1
 *
 * [0x00, 0x00, 0xa2, 0xe1]
 * mov r0, r0
 *
 * [0x00, 0x00, 0xaf, 0xe1]
 * mov r0, r0
 *
 * [0x10, 0x00, 0xaf, 0xe1]
 * invalid
 *
 * [0x01, 0x00, 0xaf, 0xe1]
 * mov r0, r1
 *
 * [0x00, 0x01, 0xaf, 0xe1]
 * invalid
 *
 * [0x00, 0x00, 0xa0, 0xe1]
 * mov r0, r0
 *
 * [0x00, 0x01, 0xa0, 0xe1]
 * lsl r0, r0, 2
 * # is this equivalent to mov r0, r0<<2?
 * 0180afe1 invalid
 * 018076e1 cmn r6, r1
 * 015096e1 orrs r5, r6, r1
 * 018086e1 orr r8, r6, r1
 * 0180a6e1 invalid
 * 0180d6e1 bics r8, r6, r1
 * 0180d0e1 bics r8, r0, r1
 * 8110d0e1 bics r1, r0, r1, lsl 1
 * 1200dfe1 bics r0, pc, r2, lsl r0
 * f110d0e1 ldrsh r1, [r0, 1]
 * 0101a0e1 lsl r0, r1, 2
 * 0110a0e1 mov r1, r1
 * 0111a0e1 lsl r1, r1, 2
 * 4110a0e1 asr r1, r1, 0x20
 * 2110a0e1 lsr r1, r1, 0x20
 *
 */